1 /* 2 * Copyright (C) 2006-2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server.am; 18 19 import static android.Manifest.permission.CHANGE_CONFIGURATION; 20 import static android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST; 21 import static android.Manifest.permission.FILTER_EVENTS; 22 import static android.Manifest.permission.INTERACT_ACROSS_USERS; 23 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL; 24 import static android.Manifest.permission.REMOVE_TASKS; 25 import static android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; 26 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS; 27 import static android.app.ActivityManager.INSTR_FLAG_MOUNT_EXTERNAL_STORAGE_FULL; 28 import static android.app.ActivityManager.PROCESS_STATE_LAST_ACTIVITY; 29 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT; 30 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY; 31 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL; 32 import static android.app.AppOpsManager.OP_NONE; 33 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; 34 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 35 import static android.content.pm.PackageManager.GET_PROVIDERS; 36 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES; 37 import static android.content.pm.PackageManager.MATCH_ALL; 38 import static android.content.pm.PackageManager.MATCH_ANY_USER; 39 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 40 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 41 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 42 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 43 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 44 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 45 import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode; 46 import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground; 47 import static android.os.FactoryTest.FACTORY_TEST_OFF; 48 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL; 49 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH; 50 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL; 51 import static android.os.IServiceManager.DUMP_FLAG_PROTO; 52 import static android.os.Process.BLUETOOTH_UID; 53 import static android.os.Process.FIRST_APPLICATION_UID; 54 import static android.os.Process.NETWORK_STACK_UID; 55 import static android.os.Process.NFC_UID; 56 import static android.os.Process.PHONE_UID; 57 import static android.os.Process.PROC_CHAR; 58 import static android.os.Process.PROC_OUT_LONG; 59 import static android.os.Process.PROC_PARENS; 60 import static android.os.Process.PROC_SPACE_TERM; 61 import static android.os.Process.ROOT_UID; 62 import static android.os.Process.SCHED_FIFO; 63 import static android.os.Process.SCHED_RESET_ON_FORK; 64 import static android.os.Process.SE_UID; 65 import static android.os.Process.SHELL_UID; 66 import static android.os.Process.SIGNAL_USR1; 67 import static android.os.Process.SYSTEM_UID; 68 import static android.os.Process.THREAD_PRIORITY_FOREGROUND; 69 import static android.os.Process.ZYGOTE_PROCESS; 70 import static android.os.Process.getTotalMemory; 71 import static android.os.Process.isThreadInProcess; 72 import static android.os.Process.killProcess; 73 import static android.os.Process.killProcessQuiet; 74 import static android.os.Process.myPid; 75 import static android.os.Process.myUid; 76 import static android.os.Process.readProcFile; 77 import static android.os.Process.removeAllProcessGroups; 78 import static android.os.Process.sendSignal; 79 import static android.os.Process.setThreadPriority; 80 import static android.os.Process.setThreadScheduler; 81 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES; 82 import static android.provider.Settings.Global.DEBUG_APP; 83 import static android.provider.Settings.Global.NETWORK_ACCESS_TIMEOUT_MS; 84 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER; 85 import static android.text.format.DateUtils.DAY_IN_MILLIS; 86 87 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL; 88 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR; 89 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK; 90 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP; 91 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; 92 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND; 93 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; 94 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 95 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK; 96 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ; 97 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW; 98 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER; 99 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES; 100 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESS_OBSERVERS; 101 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROVIDER; 102 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PSS; 103 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE; 104 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_UID_OBSERVERS; 105 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_WHITELISTS; 106 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP; 107 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; 108 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP; 109 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU; 110 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; 111 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK; 112 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ; 113 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER; 114 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES; 115 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESS_OBSERVERS; 116 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROVIDER; 117 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PSS; 118 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE; 119 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS; 120 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 121 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 122 import static com.android.server.am.MemoryStatUtil.hasMemcg; 123 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 124 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP; 125 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION; 126 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH; 127 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION; 128 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK; 129 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH; 130 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD; 131 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD; 132 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD; 133 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD; 134 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD; 135 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD; 136 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD; 137 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD; 138 import static com.android.server.wm.ActivityTaskManagerService.KEY_DISPATCHING_TIMEOUT_MS; 139 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE; 140 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString; 141 142 import android.Manifest; 143 import android.Manifest.permission; 144 import android.annotation.NonNull; 145 import android.annotation.Nullable; 146 import android.annotation.UserIdInt; 147 import android.app.Activity; 148 import android.app.ActivityManager; 149 import android.app.ActivityManager.RunningTaskInfo; 150 import android.app.ActivityManager.StackInfo; 151 import android.app.ActivityManagerInternal; 152 import android.app.ActivityManagerProto; 153 import android.app.ActivityThread; 154 import android.app.AppGlobals; 155 import android.app.AppOpsManager; 156 import android.app.AppOpsManagerInternal.CheckOpsDelegate; 157 import android.app.ApplicationErrorReport; 158 import android.app.ApplicationThreadConstants; 159 import android.app.BroadcastOptions; 160 import android.app.ContentProviderHolder; 161 import android.app.Dialog; 162 import android.app.IActivityController; 163 import android.app.IActivityManager; 164 import android.app.IApplicationThread; 165 import android.app.IAssistDataReceiver; 166 import android.app.IInstrumentationWatcher; 167 import android.app.INotificationManager; 168 import android.app.IProcessObserver; 169 import android.app.IServiceConnection; 170 import android.app.IStopUserCallback; 171 import android.app.ITaskStackListener; 172 import android.app.IUiAutomationConnection; 173 import android.app.IUidObserver; 174 import android.app.IUserSwitchObserver; 175 import android.app.Instrumentation; 176 import android.app.Notification; 177 import android.app.NotificationManager; 178 import android.app.PendingIntent; 179 import android.app.ProcessMemoryState; 180 import android.app.ProfilerInfo; 181 import android.app.WaitResult; 182 import android.app.WindowConfiguration.ActivityType; 183 import android.app.WindowConfiguration.WindowingMode; 184 import android.app.backup.IBackupManager; 185 import android.app.usage.UsageEvents; 186 import android.app.usage.UsageEvents.Event; 187 import android.app.usage.UsageStatsManagerInternal; 188 import android.appwidget.AppWidgetManager; 189 import android.content.AutofillOptions; 190 import android.content.BroadcastReceiver; 191 import android.content.ComponentCallbacks2; 192 import android.content.ComponentName; 193 import android.content.ContentCaptureOptions; 194 import android.content.ContentProvider; 195 import android.content.ContentResolver; 196 import android.content.Context; 197 import android.content.IContentProvider; 198 import android.content.IIntentReceiver; 199 import android.content.IIntentSender; 200 import android.content.Intent; 201 import android.content.IntentFilter; 202 import android.content.pm.ActivityInfo; 203 import android.content.pm.ActivityPresentationInfo; 204 import android.content.pm.ApplicationInfo; 205 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy; 206 import android.content.pm.IPackageDataObserver; 207 import android.content.pm.IPackageManager; 208 import android.content.pm.InstrumentationInfo; 209 import android.content.pm.PackageInfo; 210 import android.content.pm.PackageManager; 211 import android.content.pm.PackageManager.NameNotFoundException; 212 import android.content.pm.PackageManagerInternal; 213 import android.content.pm.PackageManagerInternal.CheckPermissionDelegate; 214 import android.content.pm.PackageParser; 215 import android.content.pm.ParceledListSlice; 216 import android.content.pm.PathPermission; 217 import android.content.pm.PermissionInfo; 218 import android.content.pm.ProviderInfo; 219 import android.content.pm.ResolveInfo; 220 import android.content.pm.SELinuxUtil; 221 import android.content.pm.ServiceInfo; 222 import android.content.pm.UserInfo; 223 import android.content.res.CompatibilityInfo; 224 import android.content.res.Configuration; 225 import android.content.res.Resources; 226 import android.database.ContentObserver; 227 import android.graphics.Rect; 228 import android.hardware.display.DisplayManagerInternal; 229 import android.location.LocationManager; 230 import android.media.audiofx.AudioEffect; 231 import android.net.Proxy; 232 import android.net.Uri; 233 import android.os.AppZygote; 234 import android.os.BatteryStats; 235 import android.os.Binder; 236 import android.os.BinderProxy; 237 import android.os.Build; 238 import android.os.Bundle; 239 import android.os.Debug; 240 import android.os.DropBoxManager; 241 import android.os.FactoryTest; 242 import android.os.FileUtils; 243 import android.os.Handler; 244 import android.os.IBinder; 245 import android.os.IDeviceIdentifiersPolicyService; 246 import android.os.IPermissionController; 247 import android.os.IProcessInfoService; 248 import android.os.IProgressListener; 249 import android.os.Looper; 250 import android.os.Message; 251 import android.os.Parcel; 252 import android.os.ParcelFileDescriptor; 253 import android.os.PowerManager; 254 import android.os.PowerManager.ServiceType; 255 import android.os.PowerManagerInternal; 256 import android.os.Process; 257 import android.os.RemoteCallback; 258 import android.os.RemoteCallbackList; 259 import android.os.RemoteException; 260 import android.os.ResultReceiver; 261 import android.os.ServiceManager; 262 import android.os.ShellCallback; 263 import android.os.StrictMode; 264 import android.os.SystemClock; 265 import android.os.SystemProperties; 266 import android.os.Trace; 267 import android.os.TransactionTooLargeException; 268 import android.os.UserHandle; 269 import android.os.UserManager; 270 import android.os.WorkSource; 271 import android.os.storage.IStorageManager; 272 import android.os.storage.StorageManager; 273 import android.provider.DeviceConfig; 274 import android.provider.Settings; 275 import android.provider.DeviceConfig.Properties; 276 import android.server.ServerProtoEnums; 277 import android.sysprop.VoldProperties; 278 import android.text.TextUtils; 279 import android.text.format.DateUtils; 280 import android.text.style.SuggestionSpan; 281 import android.util.ArrayMap; 282 import android.util.ArraySet; 283 import android.util.DebugUtils; 284 import android.util.EventLog; 285 import android.util.Log; 286 import android.util.Pair; 287 import android.util.PrintWriterPrinter; 288 import android.util.Slog; 289 import android.util.SparseArray; 290 import android.util.SparseIntArray; 291 import android.util.StatsLog; 292 import android.util.TimeUtils; 293 import android.util.TimingsTraceLog; 294 import android.util.proto.ProtoOutputStream; 295 import android.util.proto.ProtoUtils; 296 import android.view.Display; 297 import android.view.Gravity; 298 import android.view.IRecentsAnimationRunner; 299 import android.view.LayoutInflater; 300 import android.view.View; 301 import android.view.WindowManager; 302 import android.view.autofill.AutofillManagerInternal; 303 304 import com.android.internal.R; 305 import com.android.internal.annotations.GuardedBy; 306 import com.android.internal.annotations.VisibleForTesting; 307 import com.android.internal.app.DumpHeapActivity; 308 import com.android.internal.app.IAppOpsCallback; 309 import com.android.internal.app.IAppOpsService; 310 import com.android.internal.app.ProcessMap; 311 import com.android.internal.app.SystemUserHomeActivity; 312 import com.android.internal.app.procstats.ProcessStats; 313 import com.android.internal.content.PackageHelper; 314 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 315 import com.android.internal.notification.SystemNotificationChannels; 316 import com.android.internal.os.BackgroundThread; 317 import com.android.internal.os.BatteryStatsImpl; 318 import com.android.internal.os.BinderInternal; 319 import com.android.internal.os.ByteTransferPipe; 320 import com.android.internal.os.IResultReceiver; 321 import com.android.internal.os.ProcessCpuTracker; 322 import com.android.internal.os.TransferPipe; 323 import com.android.internal.os.Zygote; 324 import com.android.internal.telephony.TelephonyIntents; 325 import com.android.internal.util.ArrayUtils; 326 import com.android.internal.util.DumpUtils; 327 import com.android.internal.util.FastPrintWriter; 328 import com.android.internal.util.MemInfoReader; 329 import com.android.internal.util.Preconditions; 330 import com.android.internal.util.function.QuadFunction; 331 import com.android.internal.util.function.TriFunction; 332 import com.android.server.AlarmManagerInternal; 333 import com.android.server.AttributeCache; 334 import com.android.server.DeviceIdleController; 335 import com.android.server.DisplayThread; 336 import com.android.server.IntentResolver; 337 import com.android.server.IoThread; 338 import com.android.server.LocalServices; 339 import com.android.server.LockGuard; 340 import com.android.server.NetworkManagementInternal; 341 import com.android.server.PackageWatchdog; 342 import com.android.server.RescueParty; 343 import com.android.server.ServiceThread; 344 import com.android.server.SystemConfig; 345 import com.android.server.SystemService; 346 import com.android.server.SystemServiceManager; 347 import com.android.server.ThreadPriorityBooster; 348 import com.android.server.Watchdog; 349 import com.android.server.am.ActivityManagerServiceDumpProcessesProto.UidObserverRegistrationProto; 350 import com.android.server.appop.AppOpsService; 351 import com.android.server.contentcapture.ContentCaptureManagerInternal; 352 import com.android.server.firewall.IntentFirewall; 353 import com.android.server.job.JobSchedulerInternal; 354 import com.android.server.pm.Installer; 355 import com.android.server.pm.Installer.InstallerException; 356 import com.android.server.uri.GrantUri; 357 import com.android.server.uri.UriGrantsManagerInternal; 358 import com.android.server.utils.PriorityDump; 359 import com.android.server.vr.VrManagerInternal; 360 import com.android.server.wm.ActivityMetricsLaunchObserver; 361 import com.android.server.wm.ActivityServiceConnectionsHolder; 362 import com.android.server.wm.ActivityTaskManagerInternal; 363 import com.android.server.wm.ActivityTaskManagerService; 364 import com.android.server.wm.WindowManagerService; 365 import com.android.server.wm.WindowProcessController; 366 367 import dalvik.system.VMRuntime; 368 369 import libcore.util.EmptyArray; 370 371 import java.io.File; 372 import java.io.FileDescriptor; 373 import java.io.FileNotFoundException; 374 import java.io.FileOutputStream; 375 import java.io.IOException; 376 import java.io.InputStreamReader; 377 import java.io.PrintWriter; 378 import java.io.StringWriter; 379 import java.io.UnsupportedEncodingException; 380 import java.text.SimpleDateFormat; 381 import java.util.ArrayList; 382 import java.util.Arrays; 383 import java.util.Collections; 384 import java.util.Comparator; 385 import java.util.Date; 386 import java.util.HashMap; 387 import java.util.HashSet; 388 import java.util.Iterator; 389 import java.util.List; 390 import java.util.Locale; 391 import java.util.Map; 392 import java.util.Objects; 393 import java.util.Set; 394 import java.util.concurrent.CountDownLatch; 395 import java.util.concurrent.Executor; 396 import java.util.concurrent.atomic.AtomicBoolean; 397 import java.util.concurrent.atomic.AtomicInteger; 398 import java.util.concurrent.atomic.AtomicLong; 399 import java.util.function.BiFunction; 400 401 public class ActivityManagerService extends IActivityManager.Stub 402 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 403 404 /** 405 * Priority we boost main thread and RT of top app to. 406 */ 407 public static final int TOP_APP_PRIORITY_BOOST = -10; 408 409 private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED = 410 "persist.sys.device_provisioned"; 411 412 static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM; 413 static final String TAG_BACKUP = TAG + POSTFIX_BACKUP; 414 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 415 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 416 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION; 417 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; 418 static final String TAG_LRU = TAG + POSTFIX_LRU; 419 private static final String TAG_MU = TAG + POSTFIX_MU; 420 private static final String TAG_NETWORK = TAG + POSTFIX_NETWORK; 421 static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ; 422 private static final String TAG_POWER = TAG + POSTFIX_POWER; 423 static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS; 424 static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES; 425 private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER; 426 static final String TAG_PSS = TAG + POSTFIX_PSS; 427 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 428 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 429 static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS; 430 431 // Mock "pretend we're idle now" broadcast action to the job scheduler; declared 432 // here so that while the job scheduler can depend on AMS, the other way around 433 // need not be the case. 434 public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE"; 435 436 /** Control over CPU and battery monitoring */ 437 // write battery stats every 30 minutes. 438 static final long BATTERY_STATS_TIME = 30 * 60 * 1000; 439 static final boolean MONITOR_CPU_USAGE = true; 440 // don't sample cpu less than every 5 seconds. 441 static final long MONITOR_CPU_MIN_TIME = 5 * 1000; 442 // wait possibly forever for next cpu sample. 443 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; 444 static final boolean MONITOR_THREAD_CPU_USAGE = false; 445 446 // The flags that are set for all calls we make to the package manager. 447 public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 448 449 static final String SYSTEM_DEBUGGABLE = "ro.debuggable"; 450 451 public static final String ANR_TRACE_DIR = "/data/anr"; 452 453 // Maximum number of receivers an app can register. 454 private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000; 455 456 // How long we wait for a launched process to attach to the activity manager 457 // before we decide it's never going to come up for real. 458 static final int PROC_START_TIMEOUT = 10*1000; 459 // How long we wait for an attached process to publish its content providers 460 // before we decide it must be hung. 461 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000; 462 463 // How long we wait to kill an application zygote, after the last process using 464 // it has gone away. 465 static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000; 466 /** 467 * How long we wait for an provider to be published. Should be longer than 468 * {@link #CONTENT_PROVIDER_PUBLISH_TIMEOUT}. 469 */ 470 static final int CONTENT_PROVIDER_WAIT_TIMEOUT = 20 * 1000; 471 472 // How long we wait for a launched process to attach to the activity manager 473 // before we decide it's never going to come up for real, when the process was 474 // started with a wrapper for instrumentation (such as Valgrind) because it 475 // could take much longer than usual. 476 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 477 478 // How long we allow a receiver to run before giving up on it. 479 static final int BROADCAST_FG_TIMEOUT = 10*1000; 480 static final int BROADCAST_BG_TIMEOUT = 60*1000; 481 482 public static final int MY_PID = myPid(); 483 484 static final String[] EMPTY_STRING_ARRAY = new String[0]; 485 486 // How many bytes to write into the dropbox log before truncating 487 static final int DROPBOX_MAX_SIZE = 192 * 1024; 488 // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count 489 // as one line, but close enough for now. 490 static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100; 491 492 /** If a UID observer takes more than this long, send a WTF. */ 493 private static final int SLOW_UID_OBSERVER_THRESHOLD_MS = 20; 494 495 // Necessary ApplicationInfo flags to mark an app as persistent 496 static final int PERSISTENT_MASK = 497 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT; 498 499 // Intent sent when remote bugreport collection has been completed 500 private static final String INTENT_REMOTE_BUGREPORT_FINISHED = 501 "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED"; 502 503 // If set, we will push process association information in to procstats. 504 static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true; 505 506 /** 507 * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}. 508 */ 509 private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec 510 511 // The minimum memory growth threshold (in KB) for low RAM devices. 512 private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB 513 514 /** 515 * The number of binder proxies we need to have before we start warning and 516 * dumping debug info. 517 */ 518 private static final int BINDER_PROXY_HIGH_WATERMARK = 6000; 519 520 /** 521 * Low watermark that needs to be met before we consider dumping info again, 522 * after already hitting the high watermark. 523 */ 524 private static final int BINDER_PROXY_LOW_WATERMARK = 5500; 525 526 /** 527 * State indicating that there is no need for any blocking for network. 528 */ 529 @VisibleForTesting 530 static final int NETWORK_STATE_NO_CHANGE = 0; 531 532 /** 533 * State indicating that the main thread needs to be informed about the network wait. 534 */ 535 @VisibleForTesting 536 static final int NETWORK_STATE_BLOCK = 1; 537 538 /** 539 * State indicating that any threads waiting for network state to get updated can be unblocked. 540 */ 541 @VisibleForTesting 542 static final int NETWORK_STATE_UNBLOCK = 2; 543 544 // Max character limit for a notification title. If the notification title is larger than this 545 // the notification will not be legible to the user. 546 private static final int MAX_BUGREPORT_TITLE_SIZE = 50; 547 548 private static final int NATIVE_DUMP_TIMEOUT_MS = 2000; // 2 seconds; 549 private static final int JAVA_DUMP_MINIMUM_SIZE = 100; // 100 bytes. 550 551 OomAdjuster mOomAdjuster; 552 final LowMemDetector mLowMemDetector; 553 554 /** All system services */ 555 SystemServiceManager mSystemServiceManager; 556 557 private Installer mInstaller; 558 559 final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter(); 560 561 final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>(); 562 563 public final IntentFirewall mIntentFirewall; 564 565 public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler(); 566 567 // Whether we should use SCHED_FIFO for UI and RenderThreads. 568 boolean mUseFifoUiScheduling = false; 569 570 // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED. 571 // For simplicity, since we statically declare the size of the array of BroadcastQueues, 572 // we still create this new offload queue, but never ever put anything on it. 573 boolean mEnableOffloadQueue; 574 575 BroadcastQueue mFgBroadcastQueue; 576 BroadcastQueue mBgBroadcastQueue; 577 BroadcastQueue mOffloadBroadcastQueue; 578 // Convenient for easy iteration over the queues. Foreground is first 579 // so that dispatch of foreground broadcasts gets precedence. 580 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[3]; 581 582 BroadcastStats mLastBroadcastStats; 583 BroadcastStats mCurBroadcastStats; 584 broadcastQueueForIntent(Intent intent)585 BroadcastQueue broadcastQueueForIntent(Intent intent) { 586 if (isOnOffloadQueue(intent.getFlags())) { 587 if (DEBUG_BROADCAST_BACKGROUND) { 588 Slog.i(TAG_BROADCAST, 589 "Broadcast intent " + intent + " on offload queue"); 590 } 591 return mOffloadBroadcastQueue; 592 } 593 594 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 595 if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST, 596 "Broadcast intent " + intent + " on " 597 + (isFg ? "foreground" : "background") + " queue"); 598 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 599 } 600 601 /** 602 * The package name of the DeviceOwner. This package is not permitted to have its data cleared. 603 */ 604 String mDeviceOwnerName; 605 606 final UserController mUserController; 607 @VisibleForTesting 608 public final PendingIntentController mPendingIntentController; 609 610 final AppErrors mAppErrors; 611 final PackageWatchdog mPackageWatchdog; 612 613 /** 614 * Indicates the maximum time spent waiting for the network rules to get updated. 615 */ 616 @VisibleForTesting 617 long mWaitForNetworkTimeoutMs; 618 619 /** Total # of UID change events dispatched, shown in dumpsys. */ 620 int mUidChangeDispatchCount; 621 622 /** 623 * Helper class which strips out priority and proto arguments then calls the dump function with 624 * the appropriate arguments. If priority arguments are omitted, function calls the legacy 625 * dump command. 626 * If priority arguments are omitted all sections are dumped, otherwise sections are dumped 627 * according to their priority. 628 */ 629 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() { 630 @Override 631 public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args, 632 boolean asProto) { 633 if (asProto) return; 634 doDump(fd, pw, new String[]{"activities"}, asProto); 635 doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto); 636 } 637 638 @Override 639 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 640 doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto); 641 } 642 643 @Override 644 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 645 doDump(fd, pw, args, asProto); 646 } 647 }; 648 649 private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster( 650 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY); 651 boostPriorityForLockedSection()652 static void boostPriorityForLockedSection() { 653 sThreadPriorityBooster.boost(); 654 } 655 resetPriorityAfterLockedSection()656 static void resetPriorityAfterLockedSection() { 657 sThreadPriorityBooster.reset(); 658 } 659 660 /** 661 * Process management. 662 */ 663 final ProcessList mProcessList = new ProcessList(); 664 665 /** 666 * Tracking long-term execution of processes to look for abuse and other 667 * bad app behavior. 668 */ 669 final ProcessStatsService mProcessStats; 670 671 /** 672 * Non-persistent appId whitelist for background restrictions 673 */ 674 int[] mBackgroundAppIdWhitelist = new int[] { 675 BLUETOOTH_UID 676 }; 677 678 /** 679 * Broadcast actions that will always be deliverable to unlaunched/background apps 680 */ 681 ArraySet<String> mBackgroundLaunchBroadcasts; 682 683 /** 684 * When an app has restrictions on the other apps that can have associations with it, 685 * it appears here with a set of the allowed apps and also track debuggability of the app. 686 */ 687 ArrayMap<String, PackageAssociationInfo> mAllowedAssociations; 688 689 /** 690 * Tracks association information for a particular package along with debuggability. 691 * <p> Associations for a package A are allowed to package B if B is part of the 692 * allowed associations for A or if A is debuggable. 693 */ 694 private final class PackageAssociationInfo { 695 private final String mSourcePackage; 696 private final ArraySet<String> mAllowedPackageAssociations; 697 private boolean mIsDebuggable; 698 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)699 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, 700 boolean isDebuggable) { 701 mSourcePackage = sourcePackage; 702 mAllowedPackageAssociations = allowedPackages; 703 mIsDebuggable = isDebuggable; 704 } 705 706 /** 707 * Returns true if {@code mSourcePackage} is allowed association with 708 * {@code targetPackage}. 709 */ isPackageAssociationAllowed(String targetPackage)710 boolean isPackageAssociationAllowed(String targetPackage) { 711 return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage); 712 } 713 isDebuggable()714 boolean isDebuggable() { 715 return mIsDebuggable; 716 } 717 setDebuggable(boolean isDebuggable)718 void setDebuggable(boolean isDebuggable) { 719 mIsDebuggable = isDebuggable; 720 } 721 getAllowedPackageAssociations()722 ArraySet<String> getAllowedPackageAssociations() { 723 return mAllowedPackageAssociations; 724 } 725 } 726 727 /** 728 * All of the processes we currently have running organized by pid. 729 * The keys are the pid running the application. 730 * 731 * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock! 732 */ 733 final PidMap mPidsSelfLocked = new PidMap(); 734 final class PidMap { 735 private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>(); 736 737 /** 738 * Puts the process record in the map. 739 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 740 * method. 741 */ put(ProcessRecord app)742 void put(ProcessRecord app) { 743 synchronized (this) { 744 mPidMap.put(app.pid, app); 745 } 746 mAtmInternal.onProcessMapped(app.pid, app.getWindowProcessController()); 747 } 748 749 /** 750 * Removes the process record from the map. 751 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 752 * method. 753 */ remove(ProcessRecord app)754 void remove(ProcessRecord app) { 755 boolean removed = false; 756 synchronized (this) { 757 final ProcessRecord existingApp = mPidMap.get(app.pid); 758 if (existingApp != null && existingApp.startSeq == app.startSeq) { 759 mPidMap.remove(app.pid); 760 removed = true; 761 } 762 } 763 if (removed) { 764 mAtmInternal.onProcessUnMapped(app.pid); 765 } 766 } 767 768 /** 769 * Removes the process record from the map if it has a thread. 770 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 771 * method. 772 */ removeIfNoThread(ProcessRecord app)773 boolean removeIfNoThread(ProcessRecord app) { 774 boolean removed = false; 775 synchronized (this) { 776 final ProcessRecord existingApp = get(app.pid); 777 if (existingApp != null && existingApp.startSeq == app.startSeq 778 && app.thread == null) { 779 mPidMap.remove(app.pid); 780 removed = true; 781 } 782 } 783 if (removed) { 784 mAtmInternal.onProcessUnMapped(app.pid); 785 } 786 return removed; 787 } 788 get(int pid)789 ProcessRecord get(int pid) { 790 return mPidMap.get(pid); 791 } 792 size()793 int size() { 794 return mPidMap.size(); 795 } 796 valueAt(int index)797 ProcessRecord valueAt(int index) { 798 return mPidMap.valueAt(index); 799 } 800 keyAt(int index)801 int keyAt(int index) { 802 return mPidMap.keyAt(index); 803 } 804 indexOfKey(int key)805 int indexOfKey(int key) { 806 return mPidMap.indexOfKey(key); 807 } 808 } 809 810 /** 811 * All of the processes that have been forced to be important. The key 812 * is the pid of the caller who requested it (we hold a death 813 * link on it). 814 */ 815 abstract class ImportanceToken implements IBinder.DeathRecipient { 816 final int pid; 817 final IBinder token; 818 final String reason; 819 ImportanceToken(int _pid, IBinder _token, String _reason)820 ImportanceToken(int _pid, IBinder _token, String _reason) { 821 pid = _pid; 822 token = _token; 823 reason = _reason; 824 } 825 826 @Override toString()827 public String toString() { 828 return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this)) 829 + " " + reason + " " + pid + " " + token + " }"; 830 } 831 writeToProto(ProtoOutputStream proto, long fieldId)832 void writeToProto(ProtoOutputStream proto, long fieldId) { 833 final long pToken = proto.start(fieldId); 834 proto.write(ImportanceTokenProto.PID, pid); 835 if (token != null) { 836 proto.write(ImportanceTokenProto.TOKEN, token.toString()); 837 } 838 proto.write(ImportanceTokenProto.REASON, reason); 839 proto.end(pToken); 840 } 841 } 842 final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>(); 843 844 /** 845 * List of records for processes that someone had tried to start before the 846 * system was ready. We don't start them at that point, but ensure they 847 * are started by the time booting is complete. 848 */ 849 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 850 851 /** 852 * List of persistent applications that are in the process 853 * of being started. 854 */ 855 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 856 857 /** 858 * List of processes that should gc as soon as things are idle. 859 */ 860 final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>(); 861 862 /** 863 * Processes we want to collect PSS data from. 864 */ 865 final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>(); 866 867 /** 868 * Depth of overlapping activity-start PSS deferral notes 869 */ 870 private final AtomicInteger mActivityStartingNesting = new AtomicInteger(0); 871 872 private final ActivityMetricsLaunchObserver mActivityLaunchObserver = 873 new ActivityMetricsLaunchObserver() { 874 @Override 875 public void onActivityLaunched(byte[] activity, int temperature) { 876 // This is safe to force to the head of the queue because it relies only 877 // on refcounting to track begin/end of deferrals, not on actual 878 // message ordering. We don't care *what* activity is being 879 // launched; only that we're doing so. 880 if (mPssDeferralTime > 0) { 881 final Message msg = mBgHandler.obtainMessage(DEFER_PSS_MSG); 882 mBgHandler.sendMessageAtFrontOfQueue(msg); 883 } 884 } 885 886 // The other observer methods are unused 887 @Override 888 public void onIntentStarted(Intent intent) { 889 } 890 891 @Override 892 public void onIntentFailed() { 893 } 894 895 @Override 896 public void onActivityLaunchCancelled(byte[] abortingActivity) { 897 } 898 899 @Override 900 public void onActivityLaunchFinished(byte[] finalActivity) { 901 } 902 }; 903 904 /** 905 * How long we defer PSS gathering while activities are starting, in milliseconds. 906 * This is adjustable via DeviceConfig. If it is zero or negative, no PSS deferral 907 * is done. 908 */ 909 private volatile long mPssDeferralTime = 0; 910 private static final String ACTIVITY_START_PSS_DEFER_CONFIG = "activity_start_pss_defer"; 911 912 private boolean mBinderTransactionTrackingEnabled = false; 913 914 /** 915 * Last time we requested PSS data of all processes. 916 */ 917 long mLastFullPssTime = SystemClock.uptimeMillis(); 918 919 /** 920 * If set, the next time we collect PSS data we should do a full collection 921 * with data from native processes and the kernel. 922 */ 923 boolean mFullPssPending = false; 924 925 /** 926 * Observe DeviceConfig changes to the PSS calculation interval 927 */ 928 private final DeviceConfig.OnPropertiesChangedListener mPssDelayConfigListener = 929 new DeviceConfig.OnPropertiesChangedListener() { 930 @Override 931 public void onPropertiesChanged(Properties properties) { 932 mPssDeferralTime = properties.getLong(ACTIVITY_START_PSS_DEFER_CONFIG, 0); 933 if (DEBUG_PSS) { 934 Slog.d(TAG_PSS, "Activity-start PSS delay now " 935 + mPssDeferralTime + " ms"); 936 } 937 } 938 }; 939 940 /** 941 * This is for verifying the UID report flow. 942 */ 943 static final boolean VALIDATE_UID_STATES = true; 944 final ActiveUids mValidateUids = new ActiveUids(this, false /* postChangesToAtm */); 945 946 /** 947 * Fingerprints (hashCode()) of stack traces that we've 948 * already logged DropBox entries for. Guarded by itself. If 949 * something (rogue user app) forces this over 950 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 951 */ 952 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 953 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 954 955 /** 956 * Keeps track of all IIntentReceivers that have been registered for broadcasts. 957 * Hash keys are the receiver IBinder, hash value is a ReceiverList. 958 */ 959 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>(); 960 961 /** 962 * Resolver for broadcast intents to registered receivers. 963 * Holds BroadcastFilter (subclass of IntentFilter). 964 */ 965 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 966 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 967 @Override 968 protected boolean allowFilterResult( 969 BroadcastFilter filter, List<BroadcastFilter> dest) { 970 IBinder target = filter.receiverList.receiver.asBinder(); 971 for (int i = dest.size() - 1; i >= 0; i--) { 972 if (dest.get(i).receiverList.receiver.asBinder() == target) { 973 return false; 974 } 975 } 976 return true; 977 } 978 979 @Override 980 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 981 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 982 || userId == filter.owningUserId) { 983 return super.newResult(filter, match, userId); 984 } 985 return null; 986 } 987 988 @Override 989 protected BroadcastFilter[] newArray(int size) { 990 return new BroadcastFilter[size]; 991 } 992 993 @Override 994 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 995 return packageName.equals(filter.packageName); 996 } 997 }; 998 999 /** 1000 * State of all active sticky broadcasts per user. Keys are the action of the 1001 * sticky Intent, values are an ArrayList of all broadcasted intents with 1002 * that action (which should usually be one). The SparseArray is keyed 1003 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 1004 * for stickies that are sent to all users. 1005 */ 1006 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts = 1007 new SparseArray<ArrayMap<String, ArrayList<Intent>>>(); 1008 1009 final ActiveServices mServices; 1010 1011 final static class Association { 1012 final int mSourceUid; 1013 final String mSourceProcess; 1014 final int mTargetUid; 1015 final ComponentName mTargetComponent; 1016 final String mTargetProcess; 1017 1018 int mCount; 1019 long mTime; 1020 1021 int mNesting; 1022 long mStartTime; 1023 1024 // states of the source process when the bind occurred. 1025 int mLastState = ActivityManager.MAX_PROCESS_STATE + 1; 1026 long mLastStateUptime; 1027 long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE 1028 - ActivityManager.MIN_PROCESS_STATE+1]; 1029 Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1030 Association(int sourceUid, String sourceProcess, int targetUid, 1031 ComponentName targetComponent, String targetProcess) { 1032 mSourceUid = sourceUid; 1033 mSourceProcess = sourceProcess; 1034 mTargetUid = targetUid; 1035 mTargetComponent = targetComponent; 1036 mTargetProcess = targetProcess; 1037 } 1038 } 1039 1040 /** 1041 * When service association tracking is enabled, this is all of the associations we 1042 * have seen. Mapping is target uid -> target component -> source uid -> source process name 1043 * -> association data. 1044 */ 1045 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>> 1046 mAssociations = new SparseArray<>(); 1047 boolean mTrackingAssociations; 1048 1049 /** 1050 * Backup/restore process management 1051 */ 1052 @GuardedBy("this") 1053 final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>(); 1054 1055 final ProviderMap mProviderMap; 1056 1057 /** 1058 * List of content providers who have clients waiting for them. The 1059 * application is currently being launched and the provider will be 1060 * removed from this list once it is published. 1061 */ 1062 final ArrayList<ContentProviderRecord> mLaunchingProviders = new ArrayList<>(); 1063 1064 boolean mSystemProvidersInstalled; 1065 1066 CoreSettingsObserver mCoreSettingsObserver; 1067 1068 DevelopmentSettingsObserver mDevelopmentSettingsObserver; 1069 1070 private final class DevelopmentSettingsObserver extends ContentObserver { 1071 private final Uri mUri = Settings.Global 1072 .getUriFor(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); 1073 1074 private final ComponentName mBugreportStorageProvider = new ComponentName( 1075 "com.android.shell", "com.android.shell.BugreportStorageProvider"); 1076 DevelopmentSettingsObserver()1077 public DevelopmentSettingsObserver() { 1078 super(mHandler); 1079 mContext.getContentResolver().registerContentObserver(mUri, false, this, 1080 UserHandle.USER_ALL); 1081 // Always kick once to ensure that we match current state 1082 onChange(); 1083 } 1084 1085 @Override onChange(boolean selfChange, Uri uri, @UserIdInt int userId)1086 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) { 1087 if (mUri.equals(uri)) { 1088 onChange(); 1089 } 1090 } 1091 onChange()1092 public void onChange() { 1093 final boolean enabled = Settings.Global.getInt(mContext.getContentResolver(), 1094 Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, Build.IS_ENG ? 1 : 0) != 0; 1095 mContext.getPackageManager().setComponentEnabledSetting(mBugreportStorageProvider, 1096 enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED 1097 : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 1098 0); 1099 } 1100 } 1101 1102 /** 1103 * Thread-local storage used to carry caller permissions over through 1104 * indirect content-provider access. 1105 */ 1106 private class Identity { 1107 public final IBinder token; 1108 public final int pid; 1109 public final int uid; 1110 Identity(IBinder _token, int _pid, int _uid)1111 Identity(IBinder _token, int _pid, int _uid) { 1112 token = _token; 1113 pid = _pid; 1114 uid = _uid; 1115 } 1116 } 1117 1118 private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>(); 1119 1120 /** 1121 * All information we have collected about the runtime performance of 1122 * any user id that can impact battery performance. 1123 */ 1124 final BatteryStatsService mBatteryStatsService; 1125 1126 /** 1127 * Information about component usage 1128 */ 1129 UsageStatsManagerInternal mUsageStatsService; 1130 1131 /** 1132 * Access to DeviceIdleController service. 1133 */ 1134 DeviceIdleController.LocalService mLocalDeviceIdleController; 1135 1136 /** 1137 * Power-save whitelisted app-ids (not including except-idle-whitelisted ones). 1138 */ 1139 int[] mDeviceIdleWhitelist = new int[0]; 1140 1141 /** 1142 * Power-save whitelisted app-ids (including except-idle-whitelisted ones). 1143 */ 1144 int[] mDeviceIdleExceptIdleWhitelist = new int[0]; 1145 1146 /** 1147 * Set of app ids that are temporarily allowed to escape bg check due to high-pri message 1148 */ 1149 int[] mDeviceIdleTempWhitelist = new int[0]; 1150 1151 static final class PendingTempWhitelist { 1152 final int targetUid; 1153 final long duration; 1154 final String tag; 1155 PendingTempWhitelist(int _targetUid, long _duration, String _tag)1156 PendingTempWhitelist(int _targetUid, long _duration, String _tag) { 1157 targetUid = _targetUid; 1158 duration = _duration; 1159 tag = _tag; 1160 } 1161 writeToProto(ProtoOutputStream proto, long fieldId)1162 void writeToProto(ProtoOutputStream proto, long fieldId) { 1163 final long token = proto.start(fieldId); 1164 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID, targetUid); 1165 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS, duration); 1166 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag); 1167 proto.end(token); 1168 } 1169 } 1170 1171 final PendingTempWhitelists mPendingTempWhitelist = new PendingTempWhitelists(this); 1172 1173 /** 1174 * Information about and control over application operations 1175 */ 1176 final AppOpsService mAppOpsService; 1177 1178 /** 1179 * List of initialization arguments to pass to all processes when binding applications to them. 1180 * For example, references to the commonly used services. 1181 */ 1182 ArrayMap<String, IBinder> mAppBindArgs; 1183 ArrayMap<String, IBinder> mIsolatedAppBindArgs; 1184 1185 /** 1186 * Temporary to avoid allocations. Protected by main lock. 1187 */ 1188 final StringBuilder mStringBuilder = new StringBuilder(256); 1189 1190 volatile boolean mProcessesReady = false; 1191 volatile boolean mSystemReady = false; 1192 volatile boolean mOnBattery = false; 1193 final int mFactoryTest; 1194 volatile boolean mBooting = false; 1195 1196 @GuardedBy("this") boolean mCallFinishBooting = false; 1197 @GuardedBy("this") boolean mBootAnimationComplete = false; 1198 1199 final Context mContext; 1200 1201 /** 1202 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can 1203 * change at runtime. Use mContext for non-UI purposes. 1204 */ 1205 final Context mUiContext; 1206 1207 /** 1208 * Last time (in uptime) at which we checked for power usage. 1209 */ 1210 long mLastPowerCheckUptime; 1211 1212 /** 1213 * For some direct access we need to power manager. 1214 */ 1215 PowerManagerInternal mLocalPowerManager; 1216 1217 /** 1218 * State of external calls telling us if the device is awake or asleep. 1219 */ 1220 int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE; 1221 1222 /** 1223 * Allow the current computed overall memory level of the system to go down? 1224 * This is set to false when we are killing processes for reasons other than 1225 * memory management, so that the now smaller process list will not be taken as 1226 * an indication that memory is tighter. 1227 */ 1228 boolean mAllowLowerMemLevel = false; 1229 1230 /** 1231 * The last computed memory level, for holding when we are in a state that 1232 * processes are going away for other reasons. 1233 */ 1234 int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 1235 1236 /** 1237 * The last total number of process we have, to determine if changes actually look 1238 * like a shrinking number of process due to lower RAM. 1239 */ 1240 int mLastNumProcesses; 1241 1242 /** 1243 * The uptime of the last time we performed idle maintenance. 1244 */ 1245 long mLastIdleTime = SystemClock.uptimeMillis(); 1246 1247 /** 1248 * Total time spent with RAM that has been added in the past since the last idle time. 1249 */ 1250 long mLowRamTimeSinceLastIdle = 0; 1251 1252 /** 1253 * If RAM is currently low, when that horrible situation started. 1254 */ 1255 long mLowRamStartTime = 0; 1256 1257 /** 1258 * For reporting to battery stats the current top application. 1259 */ 1260 private String mCurResumedPackage = null; 1261 private int mCurResumedUid = -1; 1262 1263 /** 1264 * For reporting to battery stats the apps currently running foreground 1265 * service. The ProcessMap is package/uid tuples; each of these contain 1266 * an array of the currently foreground processes. 1267 */ 1268 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1269 = new ProcessMap<ArrayList<ProcessRecord>>(); 1270 1271 /** 1272 * Set if the systemServer made a call to enterSafeMode. 1273 */ 1274 boolean mSafeMode; 1275 1276 /** 1277 * If true, we are running under a test environment so will sample PSS from processes 1278 * much more rapidly to try to collect better data when the tests are rapidly 1279 * running through apps. 1280 */ 1281 boolean mTestPssMode = false; 1282 1283 String mDebugApp = null; 1284 boolean mWaitForDebugger = false; 1285 boolean mDebugTransient = false; 1286 String mOrigDebugApp = null; 1287 boolean mOrigWaitForDebugger = false; 1288 boolean mAlwaysFinishActivities = false; 1289 1290 class ProfileData { 1291 private String mProfileApp = null; 1292 private ProcessRecord mProfileProc = null; 1293 private ProfilerInfo mProfilerInfo = null; 1294 setProfileApp(String profileApp)1295 void setProfileApp(String profileApp) { 1296 mProfileApp = profileApp; 1297 if (mAtmInternal != null) { 1298 mAtmInternal.setProfileApp(profileApp); 1299 } 1300 } 1301 getProfileApp()1302 String getProfileApp() { 1303 return mProfileApp; 1304 } 1305 setProfileProc(ProcessRecord profileProc)1306 void setProfileProc(ProcessRecord profileProc) { 1307 mProfileProc = profileProc; 1308 if (mAtmInternal != null) { 1309 mAtmInternal.setProfileProc(profileProc == null ? null 1310 : profileProc.getWindowProcessController()); 1311 } 1312 } 1313 getProfileProc()1314 ProcessRecord getProfileProc() { 1315 return mProfileProc; 1316 } 1317 setProfilerInfo(ProfilerInfo profilerInfo)1318 void setProfilerInfo(ProfilerInfo profilerInfo) { 1319 mProfilerInfo = profilerInfo; 1320 if (mAtmInternal != null) { 1321 mAtmInternal.setProfilerInfo(profilerInfo); 1322 } 1323 } 1324 getProfilerInfo()1325 ProfilerInfo getProfilerInfo() { 1326 return mProfilerInfo; 1327 } 1328 } 1329 final ProfileData mProfileData = new ProfileData(); 1330 1331 /** 1332 * Stores a map of process name -> agent string. When a process is started and mAgentAppMap 1333 * is not null, this map is checked and the mapped agent installed during bind-time. Note: 1334 * A non-null agent in mProfileInfo overrides this. 1335 */ 1336 private @Nullable Map<String, String> mAppAgentMap = null; 1337 1338 int mProfileType = 0; 1339 final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>(); 1340 String mMemWatchDumpProcName; 1341 String mMemWatchDumpFile; 1342 int mMemWatchDumpPid; 1343 int mMemWatchDumpUid; 1344 private boolean mMemWatchIsUserInitiated; 1345 String mTrackAllocationApp = null; 1346 String mNativeDebuggingApp = null; 1347 1348 private final Injector mInjector; 1349 1350 static final class ProcessChangeItem { 1351 static final int CHANGE_ACTIVITIES = 1<<0; 1352 static final int CHANGE_FOREGROUND_SERVICES = 1<<1; 1353 int changes; 1354 int uid; 1355 int pid; 1356 int processState; 1357 boolean foregroundActivities; 1358 int foregroundServiceTypes; 1359 } 1360 1361 static final class UidObserverRegistration { 1362 final int uid; 1363 final String pkg; 1364 final int which; 1365 final int cutpoint; 1366 1367 /** 1368 * Total # of callback calls that took more than {@link #SLOW_UID_OBSERVER_THRESHOLD_MS}. 1369 * We show it in dumpsys. 1370 */ 1371 int mSlowDispatchCount; 1372 1373 /** Max time it took for each dispatch. */ 1374 int mMaxDispatchTime; 1375 1376 final SparseIntArray lastProcStates; 1377 1378 // Please keep the enum lists in sync 1379 private static int[] ORIG_ENUMS = new int[]{ 1380 ActivityManager.UID_OBSERVER_IDLE, 1381 ActivityManager.UID_OBSERVER_ACTIVE, 1382 ActivityManager.UID_OBSERVER_GONE, 1383 ActivityManager.UID_OBSERVER_PROCSTATE, 1384 }; 1385 private static int[] PROTO_ENUMS = new int[]{ 1386 ActivityManagerProto.UID_OBSERVER_FLAG_IDLE, 1387 ActivityManagerProto.UID_OBSERVER_FLAG_ACTIVE, 1388 ActivityManagerProto.UID_OBSERVER_FLAG_GONE, 1389 ActivityManagerProto.UID_OBSERVER_FLAG_PROCSTATE, 1390 }; 1391 UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint)1392 UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint) { 1393 uid = _uid; 1394 pkg = _pkg; 1395 which = _which; 1396 cutpoint = _cutpoint; 1397 if (cutpoint >= ActivityManager.MIN_PROCESS_STATE) { 1398 lastProcStates = new SparseIntArray(); 1399 } else { 1400 lastProcStates = null; 1401 } 1402 } 1403 writeToProto(ProtoOutputStream proto, long fieldId)1404 void writeToProto(ProtoOutputStream proto, long fieldId) { 1405 final long token = proto.start(fieldId); 1406 proto.write(UidObserverRegistrationProto.UID, uid); 1407 proto.write(UidObserverRegistrationProto.PACKAGE, pkg); 1408 ProtoUtils.writeBitWiseFlagsToProtoEnum(proto, UidObserverRegistrationProto.FLAGS, 1409 which, ORIG_ENUMS, PROTO_ENUMS); 1410 proto.write(UidObserverRegistrationProto.CUT_POINT, cutpoint); 1411 if (lastProcStates != null) { 1412 final int NI = lastProcStates.size(); 1413 for (int i=0; i<NI; i++) { 1414 final long pToken = proto.start(UidObserverRegistrationProto.LAST_PROC_STATES); 1415 proto.write(UidObserverRegistrationProto.ProcState.UID, lastProcStates.keyAt(i)); 1416 proto.write(UidObserverRegistrationProto.ProcState.STATE, lastProcStates.valueAt(i)); 1417 proto.end(pToken); 1418 } 1419 } 1420 proto.end(token); 1421 } 1422 } 1423 1424 // TODO: Move below 4 members and code to ProcessList 1425 final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>(); 1426 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5]; 1427 1428 final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>(); 1429 final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>(); 1430 1431 final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>(); 1432 UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5]; 1433 1434 final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>(); 1435 final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>(); 1436 1437 OomAdjObserver mCurOomAdjObserver; 1438 int mCurOomAdjUid; 1439 1440 interface OomAdjObserver { onOomAdjMessage(String msg)1441 void onOomAdjMessage(String msg); 1442 } 1443 1444 /** 1445 * Runtime CPU use collection thread. This object's lock is used to 1446 * perform synchronization with the thread (notifying it to run). 1447 */ 1448 final Thread mProcessCpuThread; 1449 1450 /** 1451 * Used to collect per-process CPU use for ANRs, battery stats, etc. 1452 * Must acquire this object's lock when accessing it. 1453 * NOTE: this lock will be held while doing long operations (trawling 1454 * through all processes in /proc), so it should never be acquired by 1455 * any critical paths such as when holding the main activity manager lock. 1456 */ 1457 final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker( 1458 MONITOR_THREAD_CPU_USAGE); 1459 final AtomicLong mLastCpuTime = new AtomicLong(0); 1460 final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true); 1461 final CountDownLatch mProcessCpuInitLatch = new CountDownLatch(1); 1462 1463 long mLastWriteTime = 0; 1464 1465 /** Set to true after the system has finished booting. */ 1466 volatile boolean mBooted = false; 1467 1468 /** 1469 * Current boot phase. 1470 */ 1471 int mBootPhase; 1472 1473 @VisibleForTesting 1474 public WindowManagerService mWindowManager; 1475 @VisibleForTesting 1476 public ActivityTaskManagerService mActivityTaskManager; 1477 @VisibleForTesting 1478 public ActivityTaskManagerInternal mAtmInternal; 1479 @VisibleForTesting 1480 public UriGrantsManagerInternal mUgmInternal; 1481 final ActivityThread mSystemThread; 1482 1483 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1484 final ProcessRecord mApp; 1485 final int mPid; 1486 final IApplicationThread mAppThread; 1487 AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1488 AppDeathRecipient(ProcessRecord app, int pid, 1489 IApplicationThread thread) { 1490 if (DEBUG_ALL) Slog.v( 1491 TAG, "New death recipient " + this 1492 + " for thread " + thread.asBinder()); 1493 mApp = app; 1494 mPid = pid; 1495 mAppThread = thread; 1496 } 1497 1498 @Override binderDied()1499 public void binderDied() { 1500 if (DEBUG_ALL) Slog.v( 1501 TAG, "Death received in " + this 1502 + " for thread " + mAppThread.asBinder()); 1503 synchronized(ActivityManagerService.this) { 1504 appDiedLocked(mApp, mPid, mAppThread, true); 1505 } 1506 } 1507 } 1508 1509 static final int SHOW_ERROR_UI_MSG = 1; 1510 static final int SHOW_NOT_RESPONDING_UI_MSG = 2; 1511 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1512 static final int WAIT_FOR_DEBUGGER_UI_MSG = 6; 1513 static final int SERVICE_TIMEOUT_MSG = 12; 1514 static final int UPDATE_TIME_ZONE = 13; 1515 static final int PROC_START_TIMEOUT_MSG = 20; 1516 static final int KILL_APPLICATION_MSG = 22; 1517 static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26; 1518 static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27; 1519 static final int CLEAR_DNS_CACHE_MSG = 28; 1520 static final int UPDATE_HTTP_PROXY_MSG = 29; 1521 static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31; 1522 static final int DISPATCH_PROCESS_DIED_UI_MSG = 32; 1523 static final int REPORT_MEM_USAGE_MSG = 33; 1524 static final int UPDATE_TIME_PREFERENCE_MSG = 41; 1525 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49; 1526 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50; 1527 static final int DELETE_DUMPHEAP_MSG = 51; 1528 static final int DISPATCH_UIDS_CHANGED_UI_MSG = 53; 1529 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56; 1530 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57; 1531 static final int IDLE_UIDS_MSG = 58; 1532 static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63; 1533 static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66; 1534 static final int PUSH_TEMP_WHITELIST_UI_MSG = 68; 1535 static final int SERVICE_FOREGROUND_CRASH_MSG = 69; 1536 static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70; 1537 static final int KILL_APP_ZYGOTE_MSG = 71; 1538 1539 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1540 1541 static final String SERVICE_RECORD_KEY = "servicerecord"; 1542 1543 long mLastMemUsageReportTime = 0; 1544 1545 /** 1546 * Flag whether the current user is a "monkey", i.e. whether 1547 * the UI is driven by a UI automation tool. 1548 */ 1549 private boolean mUserIsMonkey; 1550 1551 @VisibleForTesting 1552 public final ServiceThread mHandlerThread; 1553 final MainHandler mHandler; 1554 final Handler mUiHandler; 1555 final ServiceThread mProcStartHandlerThread; 1556 final Handler mProcStartHandler; 1557 1558 ActivityManagerConstants mConstants; 1559 1560 // Encapsulates the global setting "hidden_api_blacklist_exemptions" 1561 final HiddenApiSettings mHiddenApiBlacklist; 1562 1563 PackageManagerInternal mPackageManagerInt; 1564 1565 /** 1566 * Whether to force background check on all apps (for battery saver) or not. 1567 */ 1568 boolean mForceBackgroundCheck; 1569 1570 private static String sTheRealBuildSerial = Build.UNKNOWN; 1571 1572 private ParcelFileDescriptor[] mLifeMonitorFds; 1573 1574 static final HostingRecord sNullHostingRecord = new HostingRecord(null); 1575 /** 1576 * Used to notify activity lifecycle events. 1577 */ 1578 @Nullable ContentCaptureManagerInternal mContentCaptureService; 1579 1580 final class UiHandler extends Handler { UiHandler()1581 public UiHandler() { 1582 super(com.android.server.UiThread.get().getLooper(), null, true); 1583 } 1584 1585 @Override handleMessage(Message msg)1586 public void handleMessage(Message msg) { 1587 switch (msg.what) { 1588 case SHOW_ERROR_UI_MSG: { 1589 mAppErrors.handleShowAppErrorUi(msg); 1590 ensureBootCompleted(); 1591 } break; 1592 case SHOW_NOT_RESPONDING_UI_MSG: { 1593 mAppErrors.handleShowAnrUi(msg); 1594 ensureBootCompleted(); 1595 } break; 1596 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: { 1597 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1598 synchronized (ActivityManagerService.this) { 1599 ProcessRecord proc = (ProcessRecord) data.get("app"); 1600 if (proc == null) { 1601 Slog.e(TAG, "App not found when showing strict mode dialog."); 1602 break; 1603 } 1604 if (proc.crashDialog != null) { 1605 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1606 return; 1607 } 1608 AppErrorResult res = (AppErrorResult) data.get("result"); 1609 if (mAtmInternal.showStrictModeViolationDialog()) { 1610 Dialog d = new StrictModeViolationDialog(mUiContext, 1611 ActivityManagerService.this, res, proc); 1612 d.show(); 1613 proc.crashDialog = d; 1614 } else { 1615 // The device is asleep, so just pretend that the user 1616 // saw a crash dialog and hit "force quit". 1617 res.set(0); 1618 } 1619 } 1620 ensureBootCompleted(); 1621 } break; 1622 case WAIT_FOR_DEBUGGER_UI_MSG: { 1623 synchronized (ActivityManagerService.this) { 1624 ProcessRecord app = (ProcessRecord)msg.obj; 1625 if (msg.arg1 != 0) { 1626 if (!app.waitedForDebugger) { 1627 Dialog d = new AppWaitingForDebuggerDialog( 1628 ActivityManagerService.this, 1629 mUiContext, app); 1630 app.waitDialog = d; 1631 app.waitedForDebugger = true; 1632 d.show(); 1633 } 1634 } else { 1635 if (app.waitDialog != null) { 1636 app.waitDialog.dismiss(); 1637 app.waitDialog = null; 1638 } 1639 } 1640 } 1641 } break; 1642 case DISPATCH_PROCESSES_CHANGED_UI_MSG: { 1643 dispatchProcessesChanged(); 1644 break; 1645 } 1646 case DISPATCH_PROCESS_DIED_UI_MSG: { 1647 final int pid = msg.arg1; 1648 final int uid = msg.arg2; 1649 dispatchProcessDied(pid, uid); 1650 break; 1651 } 1652 case DISPATCH_UIDS_CHANGED_UI_MSG: { 1653 if (false) { // DO NOT SUBMIT WITH TRUE 1654 maybeTriggerWatchdog(); 1655 } 1656 dispatchUidsChanged(); 1657 } break; 1658 case DISPATCH_OOM_ADJ_OBSERVER_MSG: { 1659 dispatchOomAdjObserver((String)msg.obj); 1660 } break; 1661 case PUSH_TEMP_WHITELIST_UI_MSG: { 1662 pushTempWhitelist(); 1663 } break; 1664 } 1665 } 1666 } 1667 1668 final class MainHandler extends Handler { MainHandler(Looper looper)1669 public MainHandler(Looper looper) { 1670 super(looper, null, true); 1671 } 1672 1673 @Override handleMessage(Message msg)1674 public void handleMessage(Message msg) { 1675 switch (msg.what) { 1676 case GC_BACKGROUND_PROCESSES_MSG: { 1677 synchronized (ActivityManagerService.this) { 1678 performAppGcsIfAppropriateLocked(); 1679 } 1680 } break; 1681 case SERVICE_TIMEOUT_MSG: { 1682 mServices.serviceTimeout((ProcessRecord)msg.obj); 1683 } break; 1684 case SERVICE_FOREGROUND_TIMEOUT_MSG: { 1685 mServices.serviceForegroundTimeout((ServiceRecord)msg.obj); 1686 } break; 1687 case SERVICE_FOREGROUND_CRASH_MSG: { 1688 mServices.serviceForegroundCrash( 1689 (ProcessRecord) msg.obj, msg.getData().getCharSequence(SERVICE_RECORD_KEY)); 1690 } break; 1691 case UPDATE_TIME_ZONE: { 1692 synchronized (ActivityManagerService.this) { 1693 for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; i--) { 1694 ProcessRecord r = mProcessList.mLruProcesses.get(i); 1695 if (r.thread != null) { 1696 try { 1697 r.thread.updateTimeZone(); 1698 } catch (RemoteException ex) { 1699 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 1700 } 1701 } 1702 } 1703 } 1704 } break; 1705 case CLEAR_DNS_CACHE_MSG: { 1706 synchronized (ActivityManagerService.this) { 1707 mProcessList.clearAllDnsCacheLocked(); 1708 } 1709 } break; 1710 case UPDATE_HTTP_PROXY_MSG: { 1711 mProcessList.setAllHttpProxy(); 1712 } break; 1713 case PROC_START_TIMEOUT_MSG: { 1714 ProcessRecord app = (ProcessRecord)msg.obj; 1715 synchronized (ActivityManagerService.this) { 1716 processStartTimedOutLocked(app); 1717 } 1718 } break; 1719 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: { 1720 ProcessRecord app = (ProcessRecord)msg.obj; 1721 synchronized (ActivityManagerService.this) { 1722 processContentProviderPublishTimedOutLocked(app); 1723 } 1724 } break; 1725 case KILL_APPLICATION_MSG: { 1726 synchronized (ActivityManagerService.this) { 1727 final int appId = msg.arg1; 1728 final int userId = msg.arg2; 1729 Bundle bundle = (Bundle)msg.obj; 1730 String pkg = bundle.getString("pkg"); 1731 String reason = bundle.getString("reason"); 1732 forceStopPackageLocked(pkg, appId, false, false, true, false, 1733 false, userId, reason); 1734 } 1735 } break; 1736 case KILL_APP_ZYGOTE_MSG: { 1737 synchronized (ActivityManagerService.this) { 1738 final AppZygote appZygote = (AppZygote) msg.obj; 1739 mProcessList.killAppZygoteIfNeededLocked(appZygote); 1740 } 1741 } break; 1742 case CHECK_EXCESSIVE_POWER_USE_MSG: { 1743 synchronized (ActivityManagerService.this) { 1744 checkExcessivePowerUsageLocked(); 1745 removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG); 1746 Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 1747 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 1748 } 1749 } break; 1750 case REPORT_MEM_USAGE_MSG: { 1751 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj; 1752 Thread thread = new Thread() { 1753 @Override public void run() { 1754 reportMemUsage(memInfos); 1755 } 1756 }; 1757 thread.start(); 1758 break; 1759 } 1760 case UPDATE_TIME_PREFERENCE_MSG: { 1761 // The user's time format preference might have changed. 1762 // For convenience we re-use the Intent extra values. 1763 synchronized (ActivityManagerService.this) { 1764 mProcessList.updateAllTimePrefsLocked(msg.arg1); 1765 } 1766 break; 1767 } 1768 case NOTIFY_CLEARTEXT_NETWORK_MSG: { 1769 final int uid = msg.arg1; 1770 final byte[] firstPacket = (byte[]) msg.obj; 1771 1772 synchronized (mPidsSelfLocked) { 1773 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 1774 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 1775 if (p.uid == uid && p.thread != null) { 1776 try { 1777 p.thread.notifyCleartextNetwork(firstPacket); 1778 } catch (RemoteException ignored) { 1779 } 1780 } 1781 } 1782 } 1783 break; 1784 } 1785 case POST_DUMP_HEAP_NOTIFICATION_MSG: { 1786 final String procName; 1787 final int uid; 1788 final long memLimit; 1789 final String reportPackage; 1790 final boolean isUserInitiated; 1791 synchronized (ActivityManagerService.this) { 1792 uid = mMemWatchDumpUid; 1793 if (uid == SYSTEM_UID) { 1794 procName = mContext.getString(R.string.android_system_label); 1795 } else { 1796 procName = mMemWatchDumpProcName; 1797 } 1798 Pair<Long, String> val = mMemWatchProcesses.get(procName, uid); 1799 if (val == null) { 1800 val = mMemWatchProcesses.get(procName, 0); 1801 } 1802 if (val != null) { 1803 memLimit = val.first; 1804 reportPackage = val.second; 1805 } else { 1806 memLimit = 0; 1807 reportPackage = null; 1808 } 1809 isUserInitiated = mMemWatchIsUserInitiated; 1810 } 1811 if (procName == null) { 1812 return; 1813 } 1814 1815 if (DEBUG_PSS) Slog.d(TAG_PSS, 1816 "Showing dump heap notification from " + procName + "/" + uid); 1817 1818 INotificationManager inm = NotificationManager.getService(); 1819 if (inm == null) { 1820 return; 1821 } 1822 1823 final int titleId = isUserInitiated 1824 ? R.string.dump_heap_ready_notification : R.string.dump_heap_notification; 1825 String text = mContext.getString(titleId, procName); 1826 1827 Intent deleteIntent = new Intent(); 1828 deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP); 1829 Intent intent = new Intent(); 1830 intent.setClassName("android", DumpHeapActivity.class.getName()); 1831 intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName); 1832 intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit); 1833 intent.putExtra(DumpHeapActivity.KEY_IS_USER_INITIATED, isUserInitiated); 1834 intent.putExtra(DumpHeapActivity.KEY_IS_SYSTEM_PROCESS, uid == SYSTEM_UID); 1835 if (reportPackage != null) { 1836 intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage); 1837 } 1838 int userId = UserHandle.getUserId(uid); 1839 Notification notification = 1840 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 1841 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 1842 .setAutoCancel(true) 1843 .setTicker(text) 1844 .setColor(mContext.getColor( 1845 com.android.internal.R.color.system_notification_accent_color)) 1846 .setContentTitle(text) 1847 .setContentText( 1848 mContext.getText(R.string.dump_heap_notification_detail)) 1849 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, 1850 intent, PendingIntent.FLAG_CANCEL_CURRENT, null, 1851 new UserHandle(userId))) 1852 .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0, 1853 deleteIntent, 0, UserHandle.SYSTEM)) 1854 .build(); 1855 1856 try { 1857 inm.enqueueNotificationWithTag("android", "android", null, 1858 SystemMessage.NOTE_DUMP_HEAP_NOTIFICATION, 1859 notification, userId); 1860 } catch (RuntimeException e) { 1861 Slog.w(ActivityManagerService.TAG, 1862 "Error showing notification for dump heap", e); 1863 } catch (RemoteException e) { 1864 } 1865 } break; 1866 case DELETE_DUMPHEAP_MSG: { 1867 revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(), 1868 null, DumpHeapActivity.JAVA_URI, 1869 Intent.FLAG_GRANT_READ_URI_PERMISSION 1870 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 1871 UserHandle.myUserId()); 1872 synchronized (ActivityManagerService.this) { 1873 mMemWatchDumpFile = null; 1874 mMemWatchDumpProcName = null; 1875 mMemWatchDumpPid = -1; 1876 mMemWatchDumpUid = -1; 1877 } 1878 } break; 1879 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: { 1880 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj; 1881 try { 1882 connection.shutdown(); 1883 } catch (RemoteException e) { 1884 Slog.w(TAG, "Error shutting down UiAutomationConnection"); 1885 } 1886 // Only a UiAutomation can set this flag and now that 1887 // it is finished we make sure it is reset to its default. 1888 mUserIsMonkey = false; 1889 } break; 1890 case IDLE_UIDS_MSG: { 1891 idleUids(); 1892 } break; 1893 case HANDLE_TRUST_STORAGE_UPDATE_MSG: { 1894 synchronized (ActivityManagerService.this) { 1895 mProcessList.handleAllTrustStorageUpdateLocked(); 1896 } 1897 } break; 1898 } 1899 } 1900 } 1901 1902 static final int COLLECT_PSS_BG_MSG = 1; 1903 static final int DEFER_PSS_MSG = 2; 1904 static final int STOP_DEFERRING_PSS_MSG = 3; 1905 1906 final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) { 1907 @Override 1908 public void handleMessage(Message msg) { 1909 switch (msg.what) { 1910 case COLLECT_PSS_BG_MSG: { 1911 long start = SystemClock.uptimeMillis(); 1912 MemInfoReader memInfo = null; 1913 synchronized (ActivityManagerService.this) { 1914 if (mFullPssPending) { 1915 mFullPssPending = false; 1916 memInfo = new MemInfoReader(); 1917 } 1918 } 1919 if (memInfo != null) { 1920 updateCpuStatsNow(); 1921 long nativeTotalPss = 0; 1922 final List<ProcessCpuTracker.Stats> stats; 1923 synchronized (mProcessCpuTracker) { 1924 stats = mProcessCpuTracker.getStats( (st)-> { 1925 return st.vsize > 0 && st.uid < FIRST_APPLICATION_UID; 1926 }); 1927 } 1928 final int N = stats.size(); 1929 for (int j = 0; j < N; j++) { 1930 synchronized (mPidsSelfLocked) { 1931 if (mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) { 1932 // This is one of our own processes; skip it. 1933 continue; 1934 } 1935 } 1936 nativeTotalPss += Debug.getPss(stats.get(j).pid, null, null); 1937 } 1938 memInfo.readMemInfo(); 1939 synchronized (ActivityManagerService.this) { 1940 if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in " 1941 + (SystemClock.uptimeMillis()-start) + "ms"); 1942 final long cachedKb = memInfo.getCachedSizeKb(); 1943 final long freeKb = memInfo.getFreeSizeKb(); 1944 final long zramKb = memInfo.getZramTotalSizeKb(); 1945 final long kernelKb = memInfo.getKernelUsedSizeKb(); 1946 EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024, 1947 kernelKb*1024, nativeTotalPss*1024); 1948 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 1949 nativeTotalPss); 1950 } 1951 } 1952 1953 int num = 0; 1954 long[] tmp = new long[3]; 1955 do { 1956 ProcessRecord proc; 1957 int procState; 1958 int statType; 1959 int pid = -1; 1960 long lastPssTime; 1961 synchronized (ActivityManagerService.this) { 1962 if (mPendingPssProcesses.size() <= 0) { 1963 if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS, 1964 "Collected pss of " + num + " processes in " 1965 + (SystemClock.uptimeMillis() - start) + "ms"); 1966 mPendingPssProcesses.clear(); 1967 return; 1968 } 1969 proc = mPendingPssProcesses.remove(0); 1970 procState = proc.pssProcState; 1971 statType = proc.pssStatType; 1972 lastPssTime = proc.lastPssTime; 1973 long now = SystemClock.uptimeMillis(); 1974 if (proc.thread != null && procState == proc.setProcState 1975 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE) 1976 < now) { 1977 pid = proc.pid; 1978 } else { 1979 ProcessList.abortNextPssTime(proc.procStateMemTracker); 1980 if (DEBUG_PSS) Slog.d(TAG_PSS, "Skipped pss collection of " + pid + 1981 ": still need " + 1982 (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE-now) + 1983 "ms until safe"); 1984 proc = null; 1985 pid = 0; 1986 } 1987 } 1988 if (proc != null) { 1989 long startTime = SystemClock.currentThreadTimeMillis(); 1990 long pss = Debug.getPss(pid, tmp, null); 1991 long endTime = SystemClock.currentThreadTimeMillis(); 1992 synchronized (ActivityManagerService.this) { 1993 if (pss != 0 && proc.thread != null && proc.setProcState == procState 1994 && proc.pid == pid && proc.lastPssTime == lastPssTime) { 1995 num++; 1996 ProcessList.commitNextPssTime(proc.procStateMemTracker); 1997 recordPssSampleLocked(proc, procState, pss, tmp[0], tmp[1], tmp[2], 1998 statType, endTime-startTime, SystemClock.uptimeMillis()); 1999 } else { 2000 ProcessList.abortNextPssTime(proc.procStateMemTracker); 2001 if (DEBUG_PSS) Slog.d(TAG_PSS, "Skipped pss collection of " + pid + 2002 ": " + (proc.thread == null ? "NO_THREAD " : "") + 2003 (proc.pid != pid ? "PID_CHANGED " : "") + 2004 " initState=" + procState + " curState=" + 2005 proc.setProcState + " " + 2006 (proc.lastPssTime != lastPssTime ? "TIME_CHANGED" : "")); 2007 } 2008 } 2009 } 2010 } while (true); 2011 } 2012 2013 case DEFER_PSS_MSG: { 2014 deferPssForActivityStart(); 2015 } break; 2016 2017 case STOP_DEFERRING_PSS_MSG: { 2018 final int nesting = mActivityStartingNesting.decrementAndGet(); 2019 if (nesting <= 0) { 2020 if (DEBUG_PSS) { 2021 Slog.d(TAG_PSS, "PSS activity start deferral interval ended; now " 2022 + nesting); 2023 } 2024 if (nesting < 0) { 2025 Slog.wtf(TAG, "Activity start nesting undercount!"); 2026 mActivityStartingNesting.incrementAndGet(); 2027 } 2028 } else { 2029 if (DEBUG_PSS) { 2030 Slog.d(TAG_PSS, "Still deferring PSS, nesting=" + nesting); 2031 } 2032 } 2033 } 2034 break; 2035 2036 } 2037 } 2038 }; 2039 setSystemProcess()2040 public void setSystemProcess() { 2041 try { 2042 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, 2043 DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); 2044 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 2045 ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false, 2046 DUMP_FLAG_PRIORITY_HIGH); 2047 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 2048 ServiceManager.addService("dbinfo", new DbBinder(this)); 2049 if (MONITOR_CPU_USAGE) { 2050 ServiceManager.addService("cpuinfo", new CpuBinder(this), 2051 /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL); 2052 } 2053 ServiceManager.addService("permission", new PermissionController(this)); 2054 ServiceManager.addService("processinfo", new ProcessInfoService(this)); 2055 2056 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 2057 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); 2058 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 2059 2060 synchronized (this) { 2061 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName, 2062 false, 2063 0, 2064 new HostingRecord("system")); 2065 app.setPersistent(true); 2066 app.pid = MY_PID; 2067 app.getWindowProcessController().setPid(MY_PID); 2068 app.maxAdj = ProcessList.SYSTEM_ADJ; 2069 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 2070 mPidsSelfLocked.put(app); 2071 mProcessList.updateLruProcessLocked(app, false, null); 2072 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 2073 } 2074 } catch (PackageManager.NameNotFoundException e) { 2075 throw new RuntimeException( 2076 "Unable to find android system package", e); 2077 } 2078 2079 // Start watching app ops after we and the package manager are up and running. 2080 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null, 2081 new IAppOpsCallback.Stub() { 2082 @Override public void opChanged(int op, int uid, String packageName) { 2083 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) { 2084 if (mAppOpsService.checkOperation(op, uid, packageName) 2085 != AppOpsManager.MODE_ALLOWED) { 2086 runInBackgroundDisabled(uid); 2087 } 2088 } 2089 } 2090 }); 2091 } 2092 setWindowManager(WindowManagerService wm)2093 public void setWindowManager(WindowManagerService wm) { 2094 synchronized (this) { 2095 mWindowManager = wm; 2096 mActivityTaskManager.setWindowManager(wm); 2097 } 2098 } 2099 setUsageStatsManager(UsageStatsManagerInternal usageStatsManager)2100 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) { 2101 mUsageStatsService = usageStatsManager; 2102 mActivityTaskManager.setUsageStatsManager(usageStatsManager); 2103 } 2104 2105 /** 2106 * Sets the internal content capture manager service. 2107 * 2108 * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock. 2109 */ setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)2110 public void setContentCaptureManager( 2111 @Nullable ContentCaptureManagerInternal contentCaptureManager) { 2112 mContentCaptureService = contentCaptureManager; 2113 } 2114 startObservingNativeCrashes()2115 public void startObservingNativeCrashes() { 2116 final NativeCrashListener ncl = new NativeCrashListener(this); 2117 ncl.start(); 2118 } 2119 getAppOpsService()2120 public IAppOpsService getAppOpsService() { 2121 return mAppOpsService; 2122 } 2123 2124 static class MemBinder extends Binder { 2125 ActivityManagerService mActivityManagerService; 2126 private final PriorityDump.PriorityDumper mPriorityDumper = 2127 new PriorityDump.PriorityDumper() { 2128 @Override 2129 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, 2130 boolean asProto) { 2131 dump(fd, pw, new String[] {"-a"}, asProto); 2132 } 2133 2134 @Override 2135 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 2136 mActivityManagerService.dumpApplicationMemoryUsage( 2137 fd, pw, " ", args, false, null, asProto); 2138 } 2139 }; 2140 MemBinder(ActivityManagerService activityManagerService)2141 MemBinder(ActivityManagerService activityManagerService) { 2142 mActivityManagerService = activityManagerService; 2143 } 2144 2145 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2146 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2147 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2148 "meminfo", pw)) return; 2149 PriorityDump.dump(mPriorityDumper, fd, pw, args); 2150 } 2151 } 2152 2153 static class GraphicsBinder extends Binder { 2154 ActivityManagerService mActivityManagerService; GraphicsBinder(ActivityManagerService activityManagerService)2155 GraphicsBinder(ActivityManagerService activityManagerService) { 2156 mActivityManagerService = activityManagerService; 2157 } 2158 2159 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2160 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2161 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2162 "gfxinfo", pw)) return; 2163 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 2164 } 2165 } 2166 2167 static class DbBinder extends Binder { 2168 ActivityManagerService mActivityManagerService; DbBinder(ActivityManagerService activityManagerService)2169 DbBinder(ActivityManagerService activityManagerService) { 2170 mActivityManagerService = activityManagerService; 2171 } 2172 2173 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2174 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2175 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2176 "dbinfo", pw)) return; 2177 mActivityManagerService.dumpDbInfo(fd, pw, args); 2178 } 2179 } 2180 2181 static class CpuBinder extends Binder { 2182 ActivityManagerService mActivityManagerService; 2183 private final PriorityDump.PriorityDumper mPriorityDumper = 2184 new PriorityDump.PriorityDumper() { 2185 @Override 2186 public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args, 2187 boolean asProto) { 2188 if (asProto) return; 2189 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2190 "cpuinfo", pw)) return; 2191 synchronized (mActivityManagerService.mProcessCpuTracker) { 2192 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad()); 2193 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState( 2194 SystemClock.uptimeMillis())); 2195 } 2196 } 2197 }; 2198 CpuBinder(ActivityManagerService activityManagerService)2199 CpuBinder(ActivityManagerService activityManagerService) { 2200 mActivityManagerService = activityManagerService; 2201 } 2202 2203 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2204 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2205 PriorityDump.dump(mPriorityDumper, fd, pw, args); 2206 } 2207 } 2208 2209 public static final class Lifecycle extends SystemService { 2210 private final ActivityManagerService mService; 2211 private static ActivityTaskManagerService sAtm; 2212 Lifecycle(Context context)2213 public Lifecycle(Context context) { 2214 super(context); 2215 mService = new ActivityManagerService(context, sAtm); 2216 } 2217 startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2218 public static ActivityManagerService startService( 2219 SystemServiceManager ssm, ActivityTaskManagerService atm) { 2220 sAtm = atm; 2221 return ssm.startService(ActivityManagerService.Lifecycle.class).getService(); 2222 } 2223 2224 @Override onStart()2225 public void onStart() { 2226 mService.start(); 2227 } 2228 2229 @Override onBootPhase(int phase)2230 public void onBootPhase(int phase) { 2231 mService.mBootPhase = phase; 2232 if (phase == PHASE_SYSTEM_SERVICES_READY) { 2233 mService.mBatteryStatsService.systemServicesReady(); 2234 mService.mServices.systemServicesReady(); 2235 } else if (phase == PHASE_ACTIVITY_MANAGER_READY) { 2236 mService.startBroadcastObservers(); 2237 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { 2238 mService.mPackageWatchdog.onPackagesReady(); 2239 } 2240 } 2241 2242 @Override onCleanupUser(int userId)2243 public void onCleanupUser(int userId) { 2244 mService.mBatteryStatsService.onCleanupUser(userId); 2245 } 2246 getService()2247 public ActivityManagerService getService() { 2248 return mService; 2249 } 2250 } 2251 2252 /** 2253 * Encapsulates global settings related to hidden API enforcement behaviour, including tracking 2254 * the latest value via a content observer. 2255 */ 2256 static class HiddenApiSettings extends ContentObserver 2257 implements DeviceConfig.OnPropertiesChangedListener { 2258 2259 private final Context mContext; 2260 private boolean mBlacklistDisabled; 2261 private String mExemptionsStr; 2262 private List<String> mExemptions = Collections.emptyList(); 2263 private int mLogSampleRate = -1; 2264 private int mStatslogSampleRate = -1; 2265 @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT; 2266 2267 /** 2268 * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in 2269 * the range 0 to 0x10000 inclusive. 2270 * 2271 * @hide 2272 */ 2273 public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE = 2274 "hidden_api_access_log_sampling_rate"; 2275 2276 /** 2277 * Sampling rate for hidden API access event logging with statslog, as an integer in the 2278 * range 0 to 0x10000 inclusive. 2279 * 2280 * @hide 2281 */ 2282 public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE = 2283 "hidden_api_access_statslog_sampling_rate"; 2284 onPropertiesChanged(DeviceConfig.Properties properties)2285 public void onPropertiesChanged(DeviceConfig.Properties properties) { 2286 int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 2287 mLogSampleRate); 2288 int statslogSampleRate = properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 2289 mStatslogSampleRate); 2290 setSampleRates(logSampleRate, statslogSampleRate); 2291 } 2292 setSampleRates(int logSampleRate, int statslogSampleRate)2293 private void setSampleRates(int logSampleRate, int statslogSampleRate) { 2294 if (logSampleRate >= 0 && logSampleRate <= 0x10000 2295 && logSampleRate != mLogSampleRate) { 2296 mLogSampleRate = logSampleRate; 2297 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate); 2298 } 2299 2300 if (statslogSampleRate >= 0 && statslogSampleRate <= 0x10000 2301 && statslogSampleRate != mStatslogSampleRate) { 2302 mStatslogSampleRate = statslogSampleRate; 2303 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate); 2304 } 2305 2306 } 2307 2308 /** 2309 * Set initial sampling rates from DeviceConfig. This is required after each restart, 2310 * if they never get updated. 2311 */ initializeSampleRates()2312 private void initializeSampleRates() { 2313 int logSampleRate = DeviceConfig.getInt(DeviceConfig.NAMESPACE_APP_COMPAT, 2314 HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0); 2315 int statslogSampleRate = DeviceConfig.getInt(DeviceConfig.NAMESPACE_APP_COMPAT, 2316 HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0); 2317 setSampleRates(logSampleRate, statslogSampleRate); 2318 } 2319 HiddenApiSettings(Handler handler, Context context)2320 public HiddenApiSettings(Handler handler, Context context) { 2321 super(handler); 2322 mContext = context; 2323 } 2324 registerObserver()2325 public void registerObserver() { 2326 mContext.getContentResolver().registerContentObserver( 2327 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS), 2328 false, 2329 this); 2330 mContext.getContentResolver().registerContentObserver( 2331 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY), 2332 false, 2333 this); 2334 initializeSampleRates(); 2335 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT, 2336 mContext.getMainExecutor(), this); 2337 update(); 2338 } 2339 update()2340 private void update() { 2341 String exemptions = Settings.Global.getString(mContext.getContentResolver(), 2342 Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS); 2343 if (!TextUtils.equals(exemptions, mExemptionsStr)) { 2344 mExemptionsStr = exemptions; 2345 if ("*".equals(exemptions)) { 2346 mBlacklistDisabled = true; 2347 mExemptions = Collections.emptyList(); 2348 } else { 2349 mBlacklistDisabled = false; 2350 mExemptions = TextUtils.isEmpty(exemptions) 2351 ? Collections.emptyList() 2352 : Arrays.asList(exemptions.split(",")); 2353 } 2354 if (!ZYGOTE_PROCESS.setApiBlacklistExemptions(mExemptions)) { 2355 Slog.e(TAG, "Failed to set API blacklist exemptions!"); 2356 // leave mExemptionsStr as is, so we don't try to send the same list again. 2357 mExemptions = Collections.emptyList(); 2358 } 2359 } 2360 mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY); 2361 } 2362 getValidEnforcementPolicy(String settingsKey)2363 private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) { 2364 int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey, 2365 ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT); 2366 if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) { 2367 return policy; 2368 } else { 2369 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 2370 } 2371 } 2372 isDisabled()2373 boolean isDisabled() { 2374 return mBlacklistDisabled; 2375 } 2376 getPolicy()2377 @HiddenApiEnforcementPolicy int getPolicy() { 2378 return mPolicy; 2379 } 2380 onChange(boolean selfChange)2381 public void onChange(boolean selfChange) { 2382 update(); 2383 } 2384 } 2385 2386 @VisibleForTesting ActivityManagerService(Injector injector)2387 public ActivityManagerService(Injector injector) { 2388 this(injector, null /* handlerThread */); 2389 } 2390 2391 /** 2392 * Provides the basic functionality for activity task related tests when a handler thread is 2393 * given to initialize the dependency members. 2394 */ 2395 @VisibleForTesting ActivityManagerService(Injector injector, ServiceThread handlerThread)2396 public ActivityManagerService(Injector injector, ServiceThread handlerThread) { 2397 final boolean hasHandlerThread = handlerThread != null; 2398 mInjector = injector; 2399 mContext = mInjector.getContext(); 2400 mUiContext = null; 2401 mAppErrors = null; 2402 mPackageWatchdog = null; 2403 mAppOpsService = mInjector.getAppOpsService(null /* file */, null /* handler */); 2404 mBatteryStatsService = null; 2405 mHandler = hasHandlerThread ? new MainHandler(handlerThread.getLooper()) : null; 2406 mHandlerThread = handlerThread; 2407 mConstants = hasHandlerThread 2408 ? new ActivityManagerConstants(mContext, this, mHandler) : null; 2409 final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */); 2410 mProcessList.init(this, activeUids); 2411 mLowMemDetector = null; 2412 mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids); 2413 2414 mIntentFirewall = hasHandlerThread 2415 ? new IntentFirewall(new IntentFirewallInterface(), mHandler) : null; 2416 mProcessCpuThread = null; 2417 mProcessStats = null; 2418 mProviderMap = null; 2419 // For the usage of {@link ActiveServices#cleanUpServices} that may be invoked from 2420 // {@link ActivityStackSupervisor#cleanUpRemovedTaskLocked}. 2421 mServices = hasHandlerThread ? new ActiveServices(this) : null; 2422 mSystemThread = null; 2423 mUiHandler = injector.getUiHandler(null /* service */); 2424 mUserController = hasHandlerThread ? new UserController(this) : null; 2425 mPendingIntentController = hasHandlerThread 2426 ? new PendingIntentController(handlerThread.getLooper(), mUserController) : null; 2427 mProcStartHandlerThread = null; 2428 mProcStartHandler = null; 2429 mHiddenApiBlacklist = null; 2430 mFactoryTest = FACTORY_TEST_OFF; 2431 } 2432 2433 // Note: This method is invoked on the main thread but may need to attach various 2434 // handlers to other threads. So take care to be explicit about the looper. ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2435 public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) { 2436 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); 2437 mInjector = new Injector(); 2438 mContext = systemContext; 2439 2440 mFactoryTest = FactoryTest.getMode(); 2441 mSystemThread = ActivityThread.currentActivityThread(); 2442 mUiContext = mSystemThread.getSystemUiContext(); 2443 2444 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2445 2446 mHandlerThread = new ServiceThread(TAG, 2447 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2448 mHandlerThread.start(); 2449 mHandler = new MainHandler(mHandlerThread.getLooper()); 2450 mUiHandler = mInjector.getUiHandler(this); 2451 2452 mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", 2453 THREAD_PRIORITY_FOREGROUND, false /* allowIo */); 2454 mProcStartHandlerThread.start(); 2455 mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper()); 2456 2457 mConstants = new ActivityManagerConstants(mContext, this, mHandler); 2458 final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */); 2459 mProcessList.init(this, activeUids); 2460 mLowMemDetector = new LowMemDetector(this); 2461 mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids); 2462 2463 // Broadcast policy parameters 2464 final BroadcastConstants foreConstants = new BroadcastConstants( 2465 Settings.Global.BROADCAST_FG_CONSTANTS); 2466 foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT; 2467 2468 final BroadcastConstants backConstants = new BroadcastConstants( 2469 Settings.Global.BROADCAST_BG_CONSTANTS); 2470 backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; 2471 2472 final BroadcastConstants offloadConstants = new BroadcastConstants( 2473 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS); 2474 offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; 2475 // by default, no "slow" policy in this queue 2476 offloadConstants.SLOW_TIME = Integer.MAX_VALUE; 2477 2478 mEnableOffloadQueue = SystemProperties.getBoolean( 2479 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false); 2480 2481 mFgBroadcastQueue = new BroadcastQueue(this, mHandler, 2482 "foreground", foreConstants, false); 2483 mBgBroadcastQueue = new BroadcastQueue(this, mHandler, 2484 "background", backConstants, true); 2485 mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, 2486 "offload", offloadConstants, true); 2487 mBroadcastQueues[0] = mFgBroadcastQueue; 2488 mBroadcastQueues[1] = mBgBroadcastQueue; 2489 mBroadcastQueues[2] = mOffloadBroadcastQueue; 2490 2491 mServices = new ActiveServices(this); 2492 mProviderMap = new ProviderMap(this); 2493 mPackageWatchdog = PackageWatchdog.getInstance(mUiContext); 2494 mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog); 2495 2496 final File systemDir = SystemServiceManager.ensureSystemDir(); 2497 2498 // TODO: Move creation of battery stats service outside of activity manager service. 2499 mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, 2500 BackgroundThread.get().getHandler()); 2501 mBatteryStatsService.getActiveStatistics().readLocked(); 2502 mBatteryStatsService.scheduleWriteToDisk(); 2503 mOnBattery = DEBUG_POWER ? true 2504 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2505 mBatteryStatsService.getActiveStatistics().setCallback(this); 2506 mOomAdjProfiler.batteryPowerChanged(mOnBattery); 2507 2508 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2509 2510 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler); 2511 2512 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2513 2514 mUserController = new UserController(this); 2515 2516 mPendingIntentController = new PendingIntentController( 2517 mHandlerThread.getLooper(), mUserController); 2518 2519 if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) { 2520 mUseFifoUiScheduling = true; 2521 } 2522 2523 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations")); 2524 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2525 2526 mActivityTaskManager = atm; 2527 mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, 2528 DisplayThread.get().getLooper()); 2529 mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class); 2530 2531 mProcessCpuThread = new Thread("CpuTracker") { 2532 @Override 2533 public void run() { 2534 synchronized (mProcessCpuTracker) { 2535 mProcessCpuInitLatch.countDown(); 2536 mProcessCpuTracker.init(); 2537 } 2538 while (true) { 2539 try { 2540 try { 2541 synchronized(this) { 2542 final long now = SystemClock.uptimeMillis(); 2543 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 2544 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 2545 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 2546 // + ", write delay=" + nextWriteDelay); 2547 if (nextWriteDelay < nextCpuDelay) { 2548 nextCpuDelay = nextWriteDelay; 2549 } 2550 if (nextCpuDelay > 0) { 2551 mProcessCpuMutexFree.set(true); 2552 this.wait(nextCpuDelay); 2553 } 2554 } 2555 } catch (InterruptedException e) { 2556 } 2557 updateCpuStatsNow(); 2558 } catch (Exception e) { 2559 Slog.e(TAG, "Unexpected exception collecting process stats", e); 2560 } 2561 } 2562 } 2563 }; 2564 2565 mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext); 2566 2567 Watchdog.getInstance().addMonitor(this); 2568 Watchdog.getInstance().addThread(mHandler); 2569 2570 // bind background threads to little cores 2571 // this is expected to fail inside of framework tests because apps can't touch cpusets directly 2572 // make sure we've already adjusted system_server's internal view of itself first 2573 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 2574 try { 2575 Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(), 2576 Process.THREAD_GROUP_SYSTEM); 2577 Process.setThreadGroupAndCpuset( 2578 mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(), 2579 Process.THREAD_GROUP_SYSTEM); 2580 } catch (Exception e) { 2581 Slog.w(TAG, "Setting background thread cpuset failed"); 2582 } 2583 2584 } 2585 setSystemServiceManager(SystemServiceManager mgr)2586 public void setSystemServiceManager(SystemServiceManager mgr) { 2587 mSystemServiceManager = mgr; 2588 } 2589 setInstaller(Installer installer)2590 public void setInstaller(Installer installer) { 2591 mInstaller = installer; 2592 } 2593 start()2594 private void start() { 2595 removeAllProcessGroups(); 2596 mProcessCpuThread.start(); 2597 2598 mBatteryStatsService.publish(); 2599 mAppOpsService.publish(mContext); 2600 Slog.d("AppOps", "AppOpsService published"); 2601 LocalServices.addService(ActivityManagerInternal.class, new LocalService()); 2602 mActivityTaskManager.onActivityManagerInternalAdded(); 2603 mUgmInternal.onActivityManagerInternalAdded(); 2604 mPendingIntentController.onActivityManagerInternalAdded(); 2605 // Wait for the synchronized block started in mProcessCpuThread, 2606 // so that any other access to mProcessCpuTracker from main thread 2607 // will be blocked during mProcessCpuTracker initialization. 2608 try { 2609 mProcessCpuInitLatch.await(); 2610 } catch (InterruptedException e) { 2611 Slog.wtf(TAG, "Interrupted wait during start", e); 2612 Thread.currentThread().interrupt(); 2613 throw new IllegalStateException("Interrupted wait during start"); 2614 } 2615 } 2616 initPowerManagement()2617 public void initPowerManagement() { 2618 mActivityTaskManager.onInitPowerManagement(); 2619 mBatteryStatsService.initPowerManagement(); 2620 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); 2621 } 2622 getBackgroundLaunchBroadcasts()2623 private ArraySet<String> getBackgroundLaunchBroadcasts() { 2624 if (mBackgroundLaunchBroadcasts == null) { 2625 mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts(); 2626 } 2627 return mBackgroundLaunchBroadcasts; 2628 } 2629 2630 /** 2631 * Ensures that the given package name has an explicit set of allowed associations. 2632 * If it does not, give it an empty set. 2633 */ requireAllowedAssociationsLocked(String packageName)2634 void requireAllowedAssociationsLocked(String packageName) { 2635 ensureAllowedAssociations(); 2636 if (mAllowedAssociations.get(packageName) == null) { 2637 mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName, 2638 new ArraySet<>(), /* isDebuggable = */ false)); 2639 } 2640 } 2641 2642 /** 2643 * Returns true if the package {@code pkg1} running under user handle {@code uid1} is 2644 * allowed association with the package {@code pkg2} running under user handle {@code uid2}. 2645 * <p> If either of the packages are running as part of the core system, then the 2646 * association is implicitly allowed. 2647 */ validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2648 boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) { 2649 ensureAllowedAssociations(); 2650 // Interactions with the system uid are always allowed, since that is the core system 2651 // that everyone needs to be able to interact with. Also allow reflexive associations 2652 // within the same uid. 2653 if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID 2654 || UserHandle.getAppId(uid2) == SYSTEM_UID) { 2655 return true; 2656 } 2657 2658 // Check for association on both source and target packages. 2659 PackageAssociationInfo pai = mAllowedAssociations.get(pkg1); 2660 if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) { 2661 return false; 2662 } 2663 pai = mAllowedAssociations.get(pkg2); 2664 if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) { 2665 return false; 2666 } 2667 // If no explicit associations are provided in the manifest, then assume the app is 2668 // allowed associations with any package. 2669 return true; 2670 } 2671 2672 /** Sets up allowed associations for system prebuilt packages from system config (if needed). */ ensureAllowedAssociations()2673 private void ensureAllowedAssociations() { 2674 if (mAllowedAssociations == null) { 2675 ArrayMap<String, ArraySet<String>> allowedAssociations = 2676 SystemConfig.getInstance().getAllowedAssociations(); 2677 mAllowedAssociations = new ArrayMap<>(allowedAssociations.size()); 2678 PackageManagerInternal pm = getPackageManagerInternalLocked(); 2679 for (int i = 0; i < allowedAssociations.size(); i++) { 2680 final String pkg = allowedAssociations.keyAt(i); 2681 final ArraySet<String> asc = allowedAssociations.valueAt(i); 2682 2683 // Query latest debuggable flag from package-manager. 2684 boolean isDebuggable = false; 2685 try { 2686 ApplicationInfo ai = AppGlobals.getPackageManager() 2687 .getApplicationInfo(pkg, MATCH_ALL, 0); 2688 if (ai != null) { 2689 isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 2690 } 2691 } catch (RemoteException e) { 2692 /* ignore */ 2693 } 2694 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable)); 2695 } 2696 } 2697 } 2698 2699 /** Updates allowed associations for app info (specifically, based on debuggability). */ updateAssociationForApp(ApplicationInfo appInfo)2700 private void updateAssociationForApp(ApplicationInfo appInfo) { 2701 ensureAllowedAssociations(); 2702 PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName); 2703 if (pai != null) { 2704 pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); 2705 } 2706 } 2707 2708 @Override onTransact(int code, Parcel data, Parcel reply, int flags)2709 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2710 throws RemoteException { 2711 if (code == SYSPROPS_TRANSACTION) { 2712 // We need to tell all apps about the system property change. 2713 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2714 synchronized (this) { 2715 final int NP = mProcessList.mProcessNames.getMap().size(); 2716 for (int ip = 0; ip < NP; ip++) { 2717 SparseArray<ProcessRecord> apps = 2718 mProcessList.mProcessNames.getMap().valueAt(ip); 2719 final int NA = apps.size(); 2720 for (int ia = 0; ia < NA; ia++) { 2721 ProcessRecord app = apps.valueAt(ia); 2722 if (app.thread != null) { 2723 procs.add(app.thread.asBinder()); 2724 } 2725 } 2726 } 2727 } 2728 2729 int N = procs.size(); 2730 for (int i=0; i<N; i++) { 2731 Parcel data2 = Parcel.obtain(); 2732 try { 2733 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 2734 Binder.FLAG_ONEWAY); 2735 } catch (RemoteException e) { 2736 } 2737 data2.recycle(); 2738 } 2739 } 2740 try { 2741 return super.onTransact(code, data, reply, flags); 2742 } catch (RuntimeException e) { 2743 // The activity manager only throws certain exceptions intentionally, so let's 2744 // log all others. 2745 if (!(e instanceof SecurityException 2746 || e instanceof IllegalArgumentException 2747 || e instanceof IllegalStateException)) { 2748 Slog.wtf(TAG, "Activity Manager Crash." 2749 + " UID:" + Binder.getCallingUid() 2750 + " PID:" + Binder.getCallingPid() 2751 + " TRANS:" + code, e); 2752 } 2753 throw e; 2754 } 2755 } 2756 updateCpuStats()2757 void updateCpuStats() { 2758 final long now = SystemClock.uptimeMillis(); 2759 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 2760 return; 2761 } 2762 if (mProcessCpuMutexFree.compareAndSet(true, false)) { 2763 synchronized (mProcessCpuThread) { 2764 mProcessCpuThread.notify(); 2765 } 2766 } 2767 } 2768 updateCpuStatsNow()2769 void updateCpuStatsNow() { 2770 synchronized (mProcessCpuTracker) { 2771 mProcessCpuMutexFree.set(false); 2772 final long now = SystemClock.uptimeMillis(); 2773 boolean haveNewCpuStats = false; 2774 2775 if (MONITOR_CPU_USAGE && 2776 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 2777 mLastCpuTime.set(now); 2778 mProcessCpuTracker.update(); 2779 if (mProcessCpuTracker.hasGoodLastStats()) { 2780 haveNewCpuStats = true; 2781 //Slog.i(TAG, mProcessCpu.printCurrentState()); 2782 //Slog.i(TAG, "Total CPU usage: " 2783 // + mProcessCpu.getTotalCpuPercent() + "%"); 2784 2785 // Slog the cpu usage if the property is set. 2786 if ("true".equals(SystemProperties.get("events.cpu"))) { 2787 int user = mProcessCpuTracker.getLastUserTime(); 2788 int system = mProcessCpuTracker.getLastSystemTime(); 2789 int iowait = mProcessCpuTracker.getLastIoWaitTime(); 2790 int irq = mProcessCpuTracker.getLastIrqTime(); 2791 int softIrq = mProcessCpuTracker.getLastSoftIrqTime(); 2792 int idle = mProcessCpuTracker.getLastIdleTime(); 2793 2794 int total = user + system + iowait + irq + softIrq + idle; 2795 if (total == 0) total = 1; 2796 2797 EventLog.writeEvent(EventLogTags.CPU, 2798 ((user+system+iowait+irq+softIrq) * 100) / total, 2799 (user * 100) / total, 2800 (system * 100) / total, 2801 (iowait * 100) / total, 2802 (irq * 100) / total, 2803 (softIrq * 100) / total); 2804 } 2805 } 2806 } 2807 2808 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 2809 synchronized(bstats) { 2810 synchronized(mPidsSelfLocked) { 2811 if (haveNewCpuStats) { 2812 if (bstats.startAddingCpuLocked()) { 2813 int totalUTime = 0; 2814 int totalSTime = 0; 2815 final int N = mProcessCpuTracker.countStats(); 2816 for (int i=0; i<N; i++) { 2817 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 2818 if (!st.working) { 2819 continue; 2820 } 2821 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 2822 totalUTime += st.rel_utime; 2823 totalSTime += st.rel_stime; 2824 if (pr != null) { 2825 BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats; 2826 if (ps == null || !ps.isActive()) { 2827 pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked( 2828 pr.info.uid, pr.processName); 2829 } 2830 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime); 2831 pr.curCpuTime += st.rel_utime + st.rel_stime; 2832 if (pr.lastCpuTime == 0) { 2833 pr.lastCpuTime = pr.curCpuTime; 2834 } 2835 } else { 2836 BatteryStatsImpl.Uid.Proc ps = st.batteryStats; 2837 if (ps == null || !ps.isActive()) { 2838 st.batteryStats = ps = bstats.getProcessStatsLocked( 2839 bstats.mapUid(st.uid), st.name); 2840 } 2841 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime); 2842 } 2843 } 2844 final int userTime = mProcessCpuTracker.getLastUserTime(); 2845 final int systemTime = mProcessCpuTracker.getLastSystemTime(); 2846 final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime(); 2847 final int irqTime = mProcessCpuTracker.getLastIrqTime(); 2848 final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime(); 2849 final int idleTime = mProcessCpuTracker.getLastIdleTime(); 2850 bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime, 2851 systemTime, iowaitTime, irqTime, softIrqTime, idleTime); 2852 } 2853 } 2854 } 2855 2856 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 2857 mLastWriteTime = now; 2858 mBatteryStatsService.scheduleWriteToDisk(); 2859 } 2860 } 2861 } 2862 } 2863 2864 @Override batteryNeedsCpuUpdate()2865 public void batteryNeedsCpuUpdate() { 2866 updateCpuStatsNow(); 2867 } 2868 2869 @Override batteryPowerChanged(boolean onBattery)2870 public void batteryPowerChanged(boolean onBattery) { 2871 // When plugging in, update the CPU stats first before changing 2872 // the plug state. 2873 updateCpuStatsNow(); 2874 synchronized (this) { 2875 synchronized(mPidsSelfLocked) { 2876 mOnBattery = DEBUG_POWER ? true : onBattery; 2877 } 2878 mOomAdjProfiler.batteryPowerChanged(onBattery); 2879 } 2880 } 2881 2882 @Override batteryStatsReset()2883 public void batteryStatsReset() { 2884 mOomAdjProfiler.reset(); 2885 } 2886 2887 @Override batterySendBroadcast(Intent intent)2888 public void batterySendBroadcast(Intent intent) { 2889 synchronized (this) { 2890 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 2891 OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(), 2892 Binder.getCallingPid(), UserHandle.USER_ALL); 2893 } 2894 } 2895 2896 /** 2897 * Initialize the application bind args. These are passed to each 2898 * process when the bindApplication() IPC is sent to the process. They're 2899 * lazily setup to make sure the services are running when they're asked for. 2900 */ getCommonServicesLocked(boolean isolated)2901 private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) { 2902 // Isolated processes won't get this optimization, so that we don't 2903 // violate the rules about which services they have access to. 2904 if (isolated) { 2905 if (mIsolatedAppBindArgs == null) { 2906 mIsolatedAppBindArgs = new ArrayMap<>(1); 2907 addServiceToMap(mIsolatedAppBindArgs, "package"); 2908 } 2909 return mIsolatedAppBindArgs; 2910 } 2911 2912 if (mAppBindArgs == null) { 2913 mAppBindArgs = new ArrayMap<>(); 2914 2915 // Add common services. 2916 // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too. 2917 // Enable the check in ApplicationThread.bindApplication() to make sure. 2918 addServiceToMap(mAppBindArgs, "package"); 2919 addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE); 2920 addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE); 2921 addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE); 2922 addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE); 2923 addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE); 2924 addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE); 2925 addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE); 2926 addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE); 2927 addServiceToMap(mAppBindArgs, "graphicsstats"); 2928 addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE); 2929 addServiceToMap(mAppBindArgs, "content"); 2930 addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE); 2931 addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE); 2932 addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE); 2933 addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE); 2934 addServiceToMap(mAppBindArgs, Context.POWER_SERVICE); 2935 addServiceToMap(mAppBindArgs, Context.USER_SERVICE); 2936 addServiceToMap(mAppBindArgs, "mount"); 2937 } 2938 return mAppBindArgs; 2939 } 2940 addServiceToMap(ArrayMap<String, IBinder> map, String name)2941 private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) { 2942 final IBinder service = ServiceManager.getService(name); 2943 if (service != null) { 2944 map.put(name, service); 2945 if (false) { 2946 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache."); 2947 } 2948 } 2949 } 2950 2951 @Override setFocusedStack(int stackId)2952 public void setFocusedStack(int stackId) { 2953 mActivityTaskManager.setFocusedStack(stackId); 2954 } 2955 2956 /** Sets the task stack listener that gets callbacks when a task stack changes. */ 2957 @Override registerTaskStackListener(ITaskStackListener listener)2958 public void registerTaskStackListener(ITaskStackListener listener) { 2959 mActivityTaskManager.registerTaskStackListener(listener); 2960 } 2961 2962 /** 2963 * Unregister a task stack listener so that it stops receiving callbacks. 2964 */ 2965 @Override unregisterTaskStackListener(ITaskStackListener listener)2966 public void unregisterTaskStackListener(ITaskStackListener listener) { 2967 mActivityTaskManager.unregisterTaskStackListener(listener); 2968 } 2969 updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2970 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2971 ProcessRecord client) { 2972 mProcessList.updateLruProcessLocked(app, activityChange, client); 2973 } 2974 removeLruProcessLocked(ProcessRecord app)2975 final void removeLruProcessLocked(ProcessRecord app) { 2976 mProcessList.removeLruProcessLocked(app); 2977 } 2978 getProcessRecordLocked(String processName, int uid, boolean keepIfLarge)2979 final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) { 2980 return mProcessList.getProcessRecordLocked(processName, uid, keepIfLarge); 2981 } 2982 getProcessNames()2983 final ProcessMap<ProcessRecord> getProcessNames() { 2984 return mProcessList.mProcessNames; 2985 } 2986 notifyPackageUse(String packageName, int reason)2987 void notifyPackageUse(String packageName, int reason) { 2988 synchronized(this) { 2989 getPackageManagerInternalLocked().notifyPackageUse(packageName, reason); 2990 } 2991 } 2992 startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2993 boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 2994 String processName, String abiOverride, int uid, Runnable crashHandler) { 2995 synchronized(this) { 2996 ApplicationInfo info = new ApplicationInfo(); 2997 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 2998 // For isolated processes, the former contains the parent's uid and the latter the 2999 // actual uid of the isolated process. 3000 // In the special case introduced by this method (which is, starting an isolated 3001 // process directly from the SystemServer without an actual parent app process) the 3002 // closest thing to a parent's uid is SYSTEM_UID. 3003 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 3004 // the |isolated| logic in the ProcessRecord constructor. 3005 info.uid = SYSTEM_UID; 3006 info.processName = processName; 3007 info.className = entryPoint; 3008 info.packageName = "android"; 3009 info.seInfoUser = SELinuxUtil.COMPLETE_STR; 3010 info.targetSdkVersion = Build.VERSION.SDK_INT; 3011 ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */, 3012 false /* knownToBeDead */, 0 /* intentFlags */, 3013 sNullHostingRecord /* hostingRecord */, 3014 true /* allowWhileBooting */, true /* isolated */, 3015 uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs, 3016 crashHandler); 3017 return proc != null; 3018 } 3019 } 3020 3021 @GuardedBy("this") startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge)3022 final ProcessRecord startProcessLocked(String processName, 3023 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 3024 HostingRecord hostingRecord, boolean allowWhileBooting, 3025 boolean isolated, boolean keepIfLarge) { 3026 return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, 3027 hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge, 3028 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */, 3029 null /* crashHandler */); 3030 } 3031 isAllowedWhileBooting(ApplicationInfo ai)3032 boolean isAllowedWhileBooting(ApplicationInfo ai) { 3033 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 3034 } 3035 3036 /** 3037 * Update battery stats on the activity' usage. 3038 * @param activity 3039 * @param uid 3040 * @param userId 3041 * @param resumed 3042 */ updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)3043 void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) { 3044 if (DEBUG_SWITCH) { 3045 Slog.d(TAG_SWITCH, 3046 "updateBatteryStats: comp=" + activity + "res=" + resumed); 3047 } 3048 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 3049 StatsLog.write(StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED, 3050 uid, activity.getPackageName(), activity.getShortClassName(), 3051 resumed ? StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__STATE__FOREGROUND : 3052 StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__STATE__BACKGROUND); 3053 synchronized (stats) { 3054 if (resumed) { 3055 stats.noteActivityResumedLocked(uid); 3056 } else { 3057 stats.noteActivityPausedLocked(uid); 3058 } 3059 } 3060 } 3061 3062 /** 3063 * Update UsageStas on the activity's usage. 3064 * @param activity 3065 * @param userId 3066 * @param event 3067 * @param appToken ActivityRecord's appToken. 3068 * @param taskRoot TaskRecord's root 3069 */ updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)3070 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 3071 IBinder appToken, ComponentName taskRoot) { 3072 if (DEBUG_SWITCH) { 3073 Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp=" 3074 + activity + " hash=" + appToken.hashCode() + " event=" + event); 3075 } 3076 synchronized (this) { 3077 if (mUsageStatsService != null) { 3078 mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(), 3079 taskRoot); 3080 } 3081 } 3082 if (mContentCaptureService != null && (event == Event.ACTIVITY_PAUSED 3083 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED 3084 || event == Event.ACTIVITY_DESTROYED)) { 3085 mContentCaptureService.notifyActivityEvent(userId, activity, event); 3086 } 3087 } 3088 3089 /** 3090 * Update UsageStats on this package's usage. 3091 * @param packageName 3092 * @param userId 3093 * @param event 3094 */ updateActivityUsageStats(String packageName, int userId, int event)3095 public void updateActivityUsageStats(String packageName, int userId, int event) { 3096 if (DEBUG_SWITCH) { 3097 Slog.d(TAG_SWITCH, "updateActivityUsageStats: package=" 3098 + packageName + " event=" + event); 3099 } 3100 synchronized (this) { 3101 if (mUsageStatsService != null) { 3102 mUsageStatsService.reportEvent(packageName, userId, event); 3103 } 3104 } 3105 } 3106 3107 /** 3108 * Update Usages on this foreground service's usage. 3109 * @param service 3110 * @param userId 3111 * @param started 3112 */ updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)3113 void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) { 3114 if (DEBUG_SWITCH) { 3115 Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp=" 3116 + service + " started=" + started); 3117 } 3118 synchronized (this) { 3119 if (mUsageStatsService != null) { 3120 mUsageStatsService.reportEvent(service, userId, 3121 started ? UsageEvents.Event.FOREGROUND_SERVICE_START 3122 : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null); 3123 } 3124 } 3125 } 3126 compatibilityInfoForPackage(ApplicationInfo ai)3127 CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) { 3128 return mAtmInternal.compatibilityInfoForPackage(ai); 3129 } 3130 enforceNotIsolatedCaller(String caller)3131 private void enforceNotIsolatedCaller(String caller) { 3132 if (UserHandle.isIsolated(Binder.getCallingUid())) { 3133 throw new SecurityException("Isolated process not allowed to call " + caller); 3134 } 3135 } 3136 3137 @Override setPackageScreenCompatMode(String packageName, int mode)3138 public void setPackageScreenCompatMode(String packageName, int mode) { 3139 mActivityTaskManager.setPackageScreenCompatMode(packageName, mode); 3140 } 3141 hasUsageStatsPermission(String callingPackage)3142 private boolean hasUsageStatsPermission(String callingPackage) { 3143 final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS, 3144 Binder.getCallingUid(), callingPackage); 3145 if (mode == AppOpsManager.MODE_DEFAULT) { 3146 return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS) 3147 == PackageManager.PERMISSION_GRANTED; 3148 } 3149 return mode == AppOpsManager.MODE_ALLOWED; 3150 } 3151 3152 @Override getPackageProcessState(String packageName, String callingPackage)3153 public int getPackageProcessState(String packageName, String callingPackage) { 3154 if (!hasUsageStatsPermission(callingPackage)) { 3155 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 3156 "getPackageProcessState"); 3157 } 3158 3159 int procState = PROCESS_STATE_NONEXISTENT; 3160 synchronized (this) { 3161 for (int i=mProcessList.mLruProcesses.size()-1; i>=0; i--) { 3162 final ProcessRecord proc = mProcessList.mLruProcesses.get(i); 3163 if (procState > proc.setProcState) { 3164 if (proc.pkgList.containsKey(packageName) || 3165 (proc.pkgDeps != null && proc.pkgDeps.contains(packageName))) { 3166 procState = proc.setProcState; 3167 } 3168 } 3169 } 3170 } 3171 return procState; 3172 } 3173 3174 @Override setProcessMemoryTrimLevel(String process, int userId, int level)3175 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) 3176 throws RemoteException { 3177 synchronized (this) { 3178 final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel"); 3179 if (app == null) { 3180 throw new IllegalArgumentException("Unknown process: " + process); 3181 } 3182 if (app.thread == null) { 3183 throw new IllegalArgumentException("Process has no app thread"); 3184 } 3185 if (app.trimMemoryLevel >= level) { 3186 throw new IllegalArgumentException( 3187 "Unable to set a higher trim level than current level"); 3188 } 3189 if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || 3190 app.getCurProcState() > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND)) { 3191 throw new IllegalArgumentException("Unable to set a background trim level " 3192 + "on a foreground process"); 3193 } 3194 app.thread.scheduleTrimMemory(level); 3195 app.trimMemoryLevel = level; 3196 return true; 3197 } 3198 } 3199 dispatchProcessesChanged()3200 private void dispatchProcessesChanged() { 3201 int N; 3202 synchronized (this) { 3203 N = mPendingProcessChanges.size(); 3204 if (mActiveProcessChanges.length < N) { 3205 mActiveProcessChanges = new ProcessChangeItem[N]; 3206 } 3207 mPendingProcessChanges.toArray(mActiveProcessChanges); 3208 mPendingProcessChanges.clear(); 3209 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3210 "*** Delivering " + N + " process changes"); 3211 } 3212 3213 int i = mProcessObservers.beginBroadcast(); 3214 while (i > 0) { 3215 i--; 3216 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 3217 if (observer != null) { 3218 try { 3219 for (int j=0; j<N; j++) { 3220 ProcessChangeItem item = mActiveProcessChanges[j]; 3221 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) { 3222 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3223 "ACTIVITIES CHANGED pid=" + item.pid + " uid=" 3224 + item.uid + ": " + item.foregroundActivities); 3225 observer.onForegroundActivitiesChanged(item.pid, item.uid, 3226 item.foregroundActivities); 3227 } 3228 if ((item.changes & ProcessChangeItem.CHANGE_FOREGROUND_SERVICES) != 0) { 3229 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3230 "FOREGROUND SERVICES CHANGED pid=" + item.pid + " uid=" 3231 + item.uid + ": " + item.foregroundServiceTypes); 3232 observer.onForegroundServicesChanged(item.pid, item.uid, 3233 item.foregroundServiceTypes); 3234 } 3235 } 3236 } catch (RemoteException e) { 3237 } 3238 } 3239 } 3240 mProcessObservers.finishBroadcast(); 3241 3242 synchronized (this) { 3243 for (int j=0; j<N; j++) { 3244 mAvailProcessChanges.add(mActiveProcessChanges[j]); 3245 } 3246 } 3247 } 3248 3249 @GuardedBy("this") enqueueProcessChangeItemLocked(int pid, int uid)3250 ProcessChangeItem enqueueProcessChangeItemLocked(int pid, int uid) { 3251 int i = mPendingProcessChanges.size()-1; 3252 ActivityManagerService.ProcessChangeItem item = null; 3253 while (i >= 0) { 3254 item = mPendingProcessChanges.get(i); 3255 if (item.pid == pid) { 3256 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3257 "Re-using existing item: " + item); 3258 break; 3259 } 3260 i--; 3261 } 3262 3263 if (i < 0) { 3264 // No existing item in pending changes; need a new one. 3265 final int NA = mAvailProcessChanges.size(); 3266 if (NA > 0) { 3267 item = mAvailProcessChanges.remove(NA-1); 3268 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3269 "Retrieving available item: " + item); 3270 } else { 3271 item = new ActivityManagerService.ProcessChangeItem(); 3272 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3273 "Allocating new item: " + item); 3274 } 3275 item.changes = 0; 3276 item.pid = pid; 3277 item.uid = uid; 3278 if (mPendingProcessChanges.size() == 0) { 3279 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3280 "*** Enqueueing dispatch processes changed!"); 3281 mUiHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED_UI_MSG) 3282 .sendToTarget(); 3283 } 3284 mPendingProcessChanges.add(item); 3285 } 3286 3287 return item; 3288 } 3289 dispatchProcessDied(int pid, int uid)3290 private void dispatchProcessDied(int pid, int uid) { 3291 int i = mProcessObservers.beginBroadcast(); 3292 while (i > 0) { 3293 i--; 3294 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 3295 if (observer != null) { 3296 try { 3297 observer.onProcessDied(pid, uid); 3298 } catch (RemoteException e) { 3299 } 3300 } 3301 } 3302 mProcessObservers.finishBroadcast(); 3303 } 3304 3305 @VisibleForTesting dispatchUidsChanged()3306 void dispatchUidsChanged() { 3307 int N; 3308 synchronized (this) { 3309 N = mPendingUidChanges.size(); 3310 if (mActiveUidChanges.length < N) { 3311 mActiveUidChanges = new UidRecord.ChangeItem[N]; 3312 } 3313 for (int i=0; i<N; i++) { 3314 final UidRecord.ChangeItem change = mPendingUidChanges.get(i); 3315 mActiveUidChanges[i] = change; 3316 if (change.uidRecord != null) { 3317 change.uidRecord.pendingChange = null; 3318 change.uidRecord = null; 3319 } 3320 } 3321 mPendingUidChanges.clear(); 3322 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3323 "*** Delivering " + N + " uid changes"); 3324 } 3325 3326 mUidChangeDispatchCount += N; 3327 int i = mUidObservers.beginBroadcast(); 3328 while (i > 0) { 3329 i--; 3330 dispatchUidsChangedForObserver(mUidObservers.getBroadcastItem(i), 3331 (UidObserverRegistration) mUidObservers.getBroadcastCookie(i), N); 3332 } 3333 mUidObservers.finishBroadcast(); 3334 3335 if (VALIDATE_UID_STATES && mUidObservers.getRegisteredCallbackCount() > 0) { 3336 for (int j = 0; j < N; ++j) { 3337 final UidRecord.ChangeItem item = mActiveUidChanges[j]; 3338 if ((item.change & UidRecord.CHANGE_GONE) != 0) { 3339 mValidateUids.remove(item.uid); 3340 } else { 3341 UidRecord validateUid = mValidateUids.get(item.uid); 3342 if (validateUid == null) { 3343 validateUid = new UidRecord(item.uid); 3344 mValidateUids.put(item.uid, validateUid); 3345 } 3346 if ((item.change & UidRecord.CHANGE_IDLE) != 0) { 3347 validateUid.idle = true; 3348 } else if ((item.change & UidRecord.CHANGE_ACTIVE) != 0) { 3349 validateUid.idle = false; 3350 } 3351 validateUid.setCurProcState(validateUid.setProcState = item.processState); 3352 validateUid.lastDispatchedProcStateSeq = item.procStateSeq; 3353 } 3354 } 3355 } 3356 3357 synchronized (this) { 3358 for (int j = 0; j < N; j++) { 3359 mAvailUidChanges.add(mActiveUidChanges[j]); 3360 } 3361 } 3362 } 3363 dispatchUidsChangedForObserver(IUidObserver observer, UidObserverRegistration reg, int changesSize)3364 private void dispatchUidsChangedForObserver(IUidObserver observer, 3365 UidObserverRegistration reg, int changesSize) { 3366 if (observer == null) { 3367 return; 3368 } 3369 try { 3370 for (int j = 0; j < changesSize; j++) { 3371 UidRecord.ChangeItem item = mActiveUidChanges[j]; 3372 final int change = item.change; 3373 if (change == UidRecord.CHANGE_PROCSTATE && 3374 (reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) == 0) { 3375 // No-op common case: no significant change, the observer is not 3376 // interested in all proc state changes. 3377 continue; 3378 } 3379 final long start = SystemClock.uptimeMillis(); 3380 if ((change & UidRecord.CHANGE_IDLE) != 0) { 3381 if ((reg.which & ActivityManager.UID_OBSERVER_IDLE) != 0) { 3382 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3383 "UID idle uid=" + item.uid); 3384 observer.onUidIdle(item.uid, item.ephemeral); 3385 } 3386 } else if ((change & UidRecord.CHANGE_ACTIVE) != 0) { 3387 if ((reg.which & ActivityManager.UID_OBSERVER_ACTIVE) != 0) { 3388 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3389 "UID active uid=" + item.uid); 3390 observer.onUidActive(item.uid); 3391 } 3392 } 3393 if ((reg.which & ActivityManager.UID_OBSERVER_CACHED) != 0) { 3394 if ((change & UidRecord.CHANGE_CACHED) != 0) { 3395 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3396 "UID cached uid=" + item.uid); 3397 observer.onUidCachedChanged(item.uid, true); 3398 } else if ((change & UidRecord.CHANGE_UNCACHED) != 0) { 3399 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3400 "UID active uid=" + item.uid); 3401 observer.onUidCachedChanged(item.uid, false); 3402 } 3403 } 3404 if ((change & UidRecord.CHANGE_GONE) != 0) { 3405 if ((reg.which & ActivityManager.UID_OBSERVER_GONE) != 0) { 3406 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3407 "UID gone uid=" + item.uid); 3408 observer.onUidGone(item.uid, item.ephemeral); 3409 } 3410 if (reg.lastProcStates != null) { 3411 reg.lastProcStates.delete(item.uid); 3412 } 3413 } else { 3414 if ((reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) != 0) { 3415 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3416 "UID CHANGED uid=" + item.uid 3417 + ": " + item.processState); 3418 boolean doReport = true; 3419 if (reg.cutpoint >= ActivityManager.MIN_PROCESS_STATE) { 3420 final int lastState = reg.lastProcStates.get(item.uid, 3421 ActivityManager.PROCESS_STATE_UNKNOWN); 3422 if (lastState != ActivityManager.PROCESS_STATE_UNKNOWN) { 3423 final boolean lastAboveCut = lastState <= reg.cutpoint; 3424 final boolean newAboveCut = item.processState <= reg.cutpoint; 3425 doReport = lastAboveCut != newAboveCut; 3426 } else { 3427 doReport = item.processState != PROCESS_STATE_NONEXISTENT; 3428 } 3429 } 3430 if (doReport) { 3431 if (reg.lastProcStates != null) { 3432 reg.lastProcStates.put(item.uid, item.processState); 3433 } 3434 observer.onUidStateChanged(item.uid, item.processState, 3435 item.procStateSeq); 3436 } 3437 } 3438 } 3439 final int duration = (int) (SystemClock.uptimeMillis() - start); 3440 if (reg.mMaxDispatchTime < duration) { 3441 reg.mMaxDispatchTime = duration; 3442 } 3443 if (duration >= SLOW_UID_OBSERVER_THRESHOLD_MS) { 3444 reg.mSlowDispatchCount++; 3445 } 3446 } 3447 } catch (RemoteException e) { 3448 } 3449 } 3450 dispatchOomAdjObserver(String msg)3451 void dispatchOomAdjObserver(String msg) { 3452 OomAdjObserver observer; 3453 synchronized (this) { 3454 observer = mCurOomAdjObserver; 3455 } 3456 3457 if (observer != null) { 3458 observer.onOomAdjMessage(msg); 3459 } 3460 } 3461 setOomAdjObserver(int uid, OomAdjObserver observer)3462 void setOomAdjObserver(int uid, OomAdjObserver observer) { 3463 synchronized (this) { 3464 mCurOomAdjUid = uid; 3465 mCurOomAdjObserver = observer; 3466 } 3467 } 3468 clearOomAdjObserver()3469 void clearOomAdjObserver() { 3470 synchronized (this) { 3471 mCurOomAdjUid = -1; 3472 mCurOomAdjObserver = null; 3473 } 3474 } 3475 reportOomAdjMessageLocked(String tag, String msg)3476 void reportOomAdjMessageLocked(String tag, String msg) { 3477 Slog.d(tag, msg); 3478 if (mCurOomAdjObserver != null) { 3479 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget(); 3480 } 3481 } 3482 reportUidInfoMessageLocked(String tag, String msg, int uid)3483 void reportUidInfoMessageLocked(String tag, String msg, int uid) { 3484 Slog.i(TAG, msg); 3485 if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) { 3486 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget(); 3487 } 3488 3489 } 3490 3491 @Override startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3492 public int startActivity(IApplicationThread caller, String callingPackage, 3493 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3494 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { 3495 return mActivityTaskManager.startActivity(caller, callingPackage, intent, resolvedType, 3496 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 3497 } 3498 3499 @Override startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3500 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 3501 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3502 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 3503 3504 return mActivityTaskManager.startActivityAsUser(caller, callingPackage, intent, 3505 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, 3506 bOptions, userId); 3507 } 3508 startActivityAndWait(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3509 WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 3510 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3511 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 3512 return mActivityTaskManager.startActivityAndWait(caller, callingPackage, intent, 3513 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, 3514 bOptions, userId); 3515 } 3516 3517 @Override startActivityFromRecents(int taskId, Bundle bOptions)3518 public final int startActivityFromRecents(int taskId, Bundle bOptions) { 3519 return mActivityTaskManager.startActivityFromRecents(taskId, bOptions); 3520 } 3521 3522 @Override startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver, IRecentsAnimationRunner recentsAnimationRunner)3523 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver, 3524 IRecentsAnimationRunner recentsAnimationRunner) { 3525 mActivityTaskManager.startRecentsActivity( 3526 intent, assistDataReceiver, recentsAnimationRunner); 3527 } 3528 3529 @Override cancelRecentsAnimation(boolean restoreHomeStackPosition)3530 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) { 3531 mActivityTaskManager.cancelRecentsAnimation(restoreHomeStackPosition); 3532 } 3533 3534 /** 3535 * This is the internal entry point for handling Activity.finish(). 3536 * 3537 * @param token The Binder token referencing the Activity we want to finish. 3538 * @param resultCode Result code, if any, from this Activity. 3539 * @param resultData Result data (Intent), if any, from this Activity. 3540 * @param finishTask Whether to finish the task associated with this Activity. 3541 * 3542 * @return Returns true if the activity successfully finished, or false if it is still running. 3543 */ 3544 @Override finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3545 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 3546 int finishTask) { 3547 return mActivityTaskManager.finishActivity(token, resultCode, resultData, finishTask); 3548 } 3549 3550 @Override setRequestedOrientation(IBinder token, int requestedOrientation)3551 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 3552 mActivityTaskManager.setRequestedOrientation(token, requestedOrientation); 3553 } 3554 3555 @Override finishHeavyWeightApp()3556 public final void finishHeavyWeightApp() { 3557 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3558 != PackageManager.PERMISSION_GRANTED) { 3559 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 3560 + Binder.getCallingPid() 3561 + ", uid=" + Binder.getCallingUid() 3562 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3563 Slog.w(TAG, msg); 3564 throw new SecurityException(msg); 3565 } 3566 mAtmInternal.finishHeavyWeightApp(); 3567 } 3568 3569 @Override crashApplication(int uid, int initialPid, String packageName, int userId, String message)3570 public void crashApplication(int uid, int initialPid, String packageName, int userId, 3571 String message) { 3572 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3573 != PackageManager.PERMISSION_GRANTED) { 3574 String msg = "Permission Denial: crashApplication() from pid=" 3575 + Binder.getCallingPid() 3576 + ", uid=" + Binder.getCallingUid() 3577 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3578 Slog.w(TAG, msg); 3579 throw new SecurityException(msg); 3580 } 3581 3582 synchronized(this) { 3583 mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId, message); 3584 } 3585 } 3586 3587 /** 3588 * Main function for removing an existing process from the activity manager 3589 * as a result of that process going away. Clears out all connections 3590 * to the process. 3591 */ 3592 @GuardedBy("this") handleAppDiedLocked(ProcessRecord app, boolean restarting, boolean allowRestart)3593 final void handleAppDiedLocked(ProcessRecord app, 3594 boolean restarting, boolean allowRestart) { 3595 int pid = app.pid; 3596 boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1, 3597 false /*replacingPid*/); 3598 if (!kept && !restarting) { 3599 removeLruProcessLocked(app); 3600 if (pid > 0) { 3601 ProcessList.remove(pid); 3602 } 3603 } 3604 3605 if (mProfileData.getProfileProc() == app) { 3606 clearProfilerLocked(); 3607 } 3608 3609 mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> { 3610 Slog.w(TAG, "Crash of app " + app.processName 3611 + " running instrumentation " + app.getActiveInstrumentation().mClass); 3612 Bundle info = new Bundle(); 3613 info.putString("shortMsg", "Process crashed."); 3614 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 3615 }); 3616 } 3617 getRecordForAppLocked(IApplicationThread thread)3618 ProcessRecord getRecordForAppLocked(IApplicationThread thread) { 3619 if (thread == null) { 3620 return null; 3621 } 3622 3623 ProcessRecord record = mProcessList.getLRURecordForAppLocked(thread); 3624 if (record != null) return record; 3625 3626 // Validation: if it isn't in the LRU list, it shouldn't exist, but let's 3627 // double-check that. 3628 final IBinder threadBinder = thread.asBinder(); 3629 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 3630 mProcessList.mProcessNames.getMap(); 3631 for (int i = pmap.size()-1; i >= 0; i--) { 3632 final SparseArray<ProcessRecord> procs = pmap.valueAt(i); 3633 for (int j = procs.size()-1; j >= 0; j--) { 3634 final ProcessRecord proc = procs.valueAt(j); 3635 if (proc.thread != null && proc.thread.asBinder() == threadBinder) { 3636 Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: " 3637 + proc); 3638 return proc; 3639 } 3640 } 3641 } 3642 3643 return null; 3644 } 3645 doLowMemReportIfNeededLocked(ProcessRecord dyingProc)3646 final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) { 3647 // If there are no longer any background processes running, 3648 // and the app that died was not running instrumentation, 3649 // then tell everyone we are now low on memory. 3650 if (!mProcessList.haveBackgroundProcessLocked()) { 3651 boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 3652 if (doReport) { 3653 long now = SystemClock.uptimeMillis(); 3654 if (now < (mLastMemUsageReportTime+5*60*1000)) { 3655 doReport = false; 3656 } else { 3657 mLastMemUsageReportTime = now; 3658 } 3659 } 3660 final ArrayList<ProcessMemInfo> memInfos 3661 = doReport ? new ArrayList<ProcessMemInfo>(mProcessList.getLruSizeLocked()) 3662 : null; 3663 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mProcessList.getLruSizeLocked()); 3664 long now = SystemClock.uptimeMillis(); 3665 for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; i--) { 3666 ProcessRecord rec = mProcessList.mLruProcesses.get(i); 3667 if (rec == dyingProc || rec.thread == null) { 3668 continue; 3669 } 3670 if (doReport) { 3671 memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj, 3672 rec.setProcState, rec.adjType, rec.makeAdjReason())); 3673 } 3674 if ((rec.lastLowMemory+mConstants.GC_MIN_INTERVAL) <= now) { 3675 // The low memory report is overriding any current 3676 // state for a GC request. Make sure to do 3677 // heavy/important/visible/foreground processes first. 3678 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 3679 rec.lastRequestedGc = 0; 3680 } else { 3681 rec.lastRequestedGc = rec.lastLowMemory; 3682 } 3683 rec.reportLowMemory = true; 3684 rec.lastLowMemory = now; 3685 mProcessesToGc.remove(rec); 3686 addProcessToGcListLocked(rec); 3687 } 3688 } 3689 if (doReport) { 3690 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos); 3691 mHandler.sendMessage(msg); 3692 } 3693 scheduleAppGcsLocked(); 3694 } 3695 } 3696 3697 @GuardedBy("this") appDiedLocked(ProcessRecord app)3698 final void appDiedLocked(ProcessRecord app) { 3699 appDiedLocked(app, app.pid, app.thread, false); 3700 } 3701 3702 @GuardedBy("this") appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied)3703 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, 3704 boolean fromBinderDied) { 3705 // First check if this ProcessRecord is actually active for the pid. 3706 synchronized (mPidsSelfLocked) { 3707 ProcessRecord curProc = mPidsSelfLocked.get(pid); 3708 if (curProc != app) { 3709 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc); 3710 return; 3711 } 3712 } 3713 3714 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 3715 synchronized (stats) { 3716 stats.noteProcessDiedLocked(app.info.uid, pid); 3717 } 3718 3719 if (!app.killed) { 3720 if (!fromBinderDied) { 3721 killProcessQuiet(pid); 3722 } 3723 ProcessList.killProcessGroup(app.uid, pid); 3724 app.killed = true; 3725 } 3726 3727 // Clean up already done if the process has been re-started. 3728 if (app.pid == pid && app.thread != null && 3729 app.thread.asBinder() == thread.asBinder()) { 3730 boolean doLowMem = app.getActiveInstrumentation() == null; 3731 boolean doOomAdj = doLowMem; 3732 if (!app.killedByAm) { 3733 reportUidInfoMessageLocked(TAG, 3734 "Process " + app.processName + " (pid " + pid + ") has died: " 3735 + ProcessList.makeOomAdjString(app.setAdj, true) + " " 3736 + ProcessList.makeProcStateString(app.setProcState), app.info.uid); 3737 mAllowLowerMemLevel = true; 3738 } else { 3739 // Note that we always want to do oom adj to update our state with the 3740 // new number of procs. 3741 mAllowLowerMemLevel = false; 3742 doLowMem = false; 3743 } 3744 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName, 3745 app.setAdj, app.setProcState); 3746 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 3747 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder()); 3748 handleAppDiedLocked(app, false, true); 3749 3750 if (doOomAdj) { 3751 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END); 3752 } 3753 if (doLowMem) { 3754 doLowMemReportIfNeededLocked(app); 3755 } 3756 } else if (app.pid != pid) { 3757 // A new process has already been started. 3758 reportUidInfoMessageLocked(TAG, 3759 "Process " + app.processName + " (pid " + pid 3760 + ") has died and restarted (pid " + app.pid + ").", app.info.uid); 3761 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 3762 } else if (DEBUG_PROCESSES) { 3763 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread " 3764 + thread.asBinder()); 3765 } 3766 3767 // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal 3768 // for pulling memory stats of other running processes when this process died. 3769 if (!hasMemcg()) { 3770 StatsLog.write(StatsLog.APP_DIED, SystemClock.elapsedRealtime()); 3771 } 3772 } 3773 3774 /** 3775 * If a stack trace dump file is configured, dump process stack traces. 3776 * @param firstPids of dalvik VM processes to dump stack traces for first 3777 * @param lastPids of dalvik VM processes to dump stack traces for last 3778 * @param nativePids optional list of native pids to dump stack crawls 3779 */ dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids)3780 public static File dumpStackTraces(ArrayList<Integer> firstPids, 3781 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 3782 ArrayList<Integer> nativePids) { 3783 ArrayList<Integer> extraPids = null; 3784 3785 Slog.i(TAG, "dumpStackTraces pids=" + lastPids + " nativepids=" + nativePids); 3786 3787 // Measure CPU usage as soon as we're called in order to get a realistic sampling 3788 // of the top users at the time of the request. 3789 if (processCpuTracker != null) { 3790 processCpuTracker.init(); 3791 try { 3792 Thread.sleep(200); 3793 } catch (InterruptedException ignored) { 3794 } 3795 3796 processCpuTracker.update(); 3797 3798 // We'll take the stack crawls of just the top apps using CPU. 3799 final int N = processCpuTracker.countWorkingStats(); 3800 extraPids = new ArrayList<>(); 3801 for (int i = 0; i < N && extraPids.size() < 5; i++) { 3802 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i); 3803 if (lastPids.indexOfKey(stats.pid) >= 0) { 3804 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid); 3805 3806 extraPids.add(stats.pid); 3807 } else { 3808 Slog.i(TAG, "Skipping next CPU consuming process, not a java proc: " 3809 + stats.pid); 3810 } 3811 } 3812 } 3813 3814 final File tracesDir = new File(ANR_TRACE_DIR); 3815 // Each set of ANR traces is written to a separate file and dumpstate will process 3816 // all such files and add them to a captured bug report if they're recent enough. 3817 maybePruneOldTraces(tracesDir); 3818 3819 // NOTE: We should consider creating the file in native code atomically once we've 3820 // gotten rid of the old scheme of dumping and lot of the code that deals with paths 3821 // can be removed. 3822 File tracesFile = createAnrDumpFile(tracesDir); 3823 if (tracesFile == null) { 3824 return null; 3825 } 3826 3827 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids); 3828 return tracesFile; 3829 } 3830 3831 @GuardedBy("ActivityManagerService.class") 3832 private static SimpleDateFormat sAnrFileDateFormat; 3833 createAnrDumpFile(File tracesDir)3834 private static synchronized File createAnrDumpFile(File tracesDir) { 3835 if (sAnrFileDateFormat == null) { 3836 sAnrFileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS"); 3837 } 3838 3839 final String formattedDate = sAnrFileDateFormat.format(new Date()); 3840 final File anrFile = new File(tracesDir, "anr_" + formattedDate); 3841 3842 try { 3843 if (anrFile.createNewFile()) { 3844 FileUtils.setPermissions(anrFile.getAbsolutePath(), 0600, -1, -1); // -rw------- 3845 return anrFile; 3846 } else { 3847 Slog.w(TAG, "Unable to create ANR dump file: createNewFile failed"); 3848 } 3849 } catch (IOException ioe) { 3850 Slog.w(TAG, "Exception creating ANR dump file:", ioe); 3851 } 3852 3853 return null; 3854 } 3855 3856 /** 3857 * Prune all trace files that are more than a day old. 3858 * 3859 * NOTE: It might make sense to move this functionality to tombstoned eventually, along with a 3860 * shift away from anr_XX and tombstone_XX to a more descriptive name. We do it here for now 3861 * since it's the system_server that creates trace files for most ANRs. 3862 */ maybePruneOldTraces(File tracesDir)3863 private static void maybePruneOldTraces(File tracesDir) { 3864 final File[] files = tracesDir.listFiles(); 3865 if (files == null) return; 3866 3867 final int max = SystemProperties.getInt("tombstoned.max_anr_count", 64); 3868 final long now = System.currentTimeMillis(); 3869 Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed()); 3870 for (int i = 0; i < files.length; ++i) { 3871 if (i > max || (now - files[i].lastModified()) > DAY_IN_MILLIS) { 3872 if (!files[i].delete()) { 3873 Slog.w(TAG, "Unable to prune stale trace file: " + files[i]); 3874 } 3875 } 3876 } 3877 } 3878 3879 /** 3880 * Dump java traces for process {@code pid} to the specified file. If java trace dumping 3881 * fails, a native backtrace is attempted. Note that the timeout {@code timeoutMs} only applies 3882 * to the java section of the trace, a further {@code NATIVE_DUMP_TIMEOUT_MS} might be spent 3883 * attempting to obtain native traces in the case of a failure. Returns the total time spent 3884 * capturing traces. 3885 */ dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs)3886 private static long dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs) { 3887 final long timeStart = SystemClock.elapsedRealtime(); 3888 boolean javaSuccess = Debug.dumpJavaBacktraceToFileTimeout(pid, fileName, 3889 (int) (timeoutMs / 1000)); 3890 if (javaSuccess) { 3891 // Check that something is in the file, actually. Try-catch should not be necessary, 3892 // but better safe than sorry. 3893 try { 3894 long size = new File(fileName).length(); 3895 if (size < JAVA_DUMP_MINIMUM_SIZE) { 3896 Slog.w(TAG, "Successfully created Java ANR file is empty!"); 3897 javaSuccess = false; 3898 } 3899 } catch (Exception e) { 3900 Slog.w(TAG, "Unable to get ANR file size", e); 3901 javaSuccess = false; 3902 } 3903 } 3904 if (!javaSuccess) { 3905 Slog.w(TAG, "Dumping Java threads failed, initiating native stack dump."); 3906 if (!Debug.dumpNativeBacktraceToFileTimeout(pid, fileName, 3907 (NATIVE_DUMP_TIMEOUT_MS / 1000))) { 3908 Slog.w(TAG, "Native stack dump failed!"); 3909 } 3910 } 3911 3912 return SystemClock.elapsedRealtime() - timeStart; 3913 } 3914 dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, ArrayList<Integer> nativePids, ArrayList<Integer> extraPids)3915 public static void dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, 3916 ArrayList<Integer> nativePids, ArrayList<Integer> extraPids) { 3917 3918 Slog.i(TAG, "Dumping to " + tracesFile); 3919 3920 // We don't need any sort of inotify based monitoring when we're dumping traces via 3921 // tombstoned. Data is piped to an "intercept" FD installed in tombstoned so we're in full 3922 // control of all writes to the file in question. 3923 3924 // We must complete all stack dumps within 20 seconds. 3925 long remainingTime = 20 * 1000; 3926 3927 // First collect all of the stacks of the most important pids. 3928 if (firstPids != null) { 3929 int num = firstPids.size(); 3930 for (int i = 0; i < num; i++) { 3931 Slog.i(TAG, "Collecting stacks for pid " + firstPids.get(i)); 3932 final long timeTaken = dumpJavaTracesTombstoned(firstPids.get(i), tracesFile, 3933 remainingTime); 3934 3935 remainingTime -= timeTaken; 3936 if (remainingTime <= 0) { 3937 Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + firstPids.get(i) + 3938 "); deadline exceeded."); 3939 return; 3940 } 3941 3942 if (DEBUG_ANR) { 3943 Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms"); 3944 } 3945 } 3946 } 3947 3948 // Next collect the stacks of the native pids 3949 if (nativePids != null) { 3950 for (int pid : nativePids) { 3951 Slog.i(TAG, "Collecting stacks for native pid " + pid); 3952 final long nativeDumpTimeoutMs = Math.min(NATIVE_DUMP_TIMEOUT_MS, remainingTime); 3953 3954 final long start = SystemClock.elapsedRealtime(); 3955 Debug.dumpNativeBacktraceToFileTimeout( 3956 pid, tracesFile, (int) (nativeDumpTimeoutMs / 1000)); 3957 final long timeTaken = SystemClock.elapsedRealtime() - start; 3958 3959 remainingTime -= timeTaken; 3960 if (remainingTime <= 0) { 3961 Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid + 3962 "); deadline exceeded."); 3963 return; 3964 } 3965 3966 if (DEBUG_ANR) { 3967 Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms"); 3968 } 3969 } 3970 } 3971 3972 // Lastly, dump stacks for all extra PIDs from the CPU tracker. 3973 if (extraPids != null) { 3974 for (int pid : extraPids) { 3975 Slog.i(TAG, "Collecting stacks for extra pid " + pid); 3976 3977 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, remainingTime); 3978 3979 remainingTime -= timeTaken; 3980 if (remainingTime <= 0) { 3981 Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + pid + 3982 "); deadline exceeded."); 3983 return; 3984 } 3985 3986 if (DEBUG_ANR) { 3987 Slog.d(TAG, "Done with extra pid " + pid + " in " + timeTaken + "ms"); 3988 } 3989 } 3990 } 3991 Slog.i(TAG, "Done dumping"); 3992 } 3993 3994 @Override clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)3995 public boolean clearApplicationUserData(final String packageName, boolean keepState, 3996 final IPackageDataObserver observer, int userId) { 3997 enforceNotIsolatedCaller("clearApplicationUserData"); 3998 int uid = Binder.getCallingUid(); 3999 int pid = Binder.getCallingPid(); 4000 final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false, 4001 ALLOW_FULL_ONLY, "clearApplicationUserData", null); 4002 4003 final ApplicationInfo appInfo; 4004 final boolean isInstantApp; 4005 4006 long callingId = Binder.clearCallingIdentity(); 4007 try { 4008 IPackageManager pm = AppGlobals.getPackageManager(); 4009 synchronized(this) { 4010 // Instant packages are not protected 4011 if (getPackageManagerInternalLocked().isPackageDataProtected( 4012 resolvedUserId, packageName)) { 4013 throw new SecurityException( 4014 "Cannot clear data for a protected package: " + packageName); 4015 } 4016 4017 ApplicationInfo applicationInfo = null; 4018 try { 4019 applicationInfo = pm.getApplicationInfo(packageName, 4020 MATCH_UNINSTALLED_PACKAGES, resolvedUserId); 4021 } catch (RemoteException e) { 4022 /* ignore */ 4023 } 4024 appInfo = applicationInfo; 4025 4026 final boolean clearingOwnUidData = appInfo != null && appInfo.uid == uid; 4027 4028 if (!clearingOwnUidData && checkComponentPermission(permission.CLEAR_APP_USER_DATA, 4029 pid, uid, -1, true) != PackageManager.PERMISSION_GRANTED) { 4030 throw new SecurityException("PID " + pid + " does not have permission " 4031 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 4032 + " of package " + packageName); 4033 } 4034 4035 final boolean hasInstantMetadata = getPackageManagerInternalLocked() 4036 .hasInstantApplicationMetadata(packageName, resolvedUserId); 4037 final boolean isUninstalledAppWithoutInstantMetadata = 4038 (appInfo == null && !hasInstantMetadata); 4039 isInstantApp = (appInfo != null && appInfo.isInstantApp()) 4040 || hasInstantMetadata; 4041 final boolean canAccessInstantApps = checkComponentPermission( 4042 permission.ACCESS_INSTANT_APPS, pid, uid, -1, true) 4043 == PackageManager.PERMISSION_GRANTED; 4044 4045 if (isUninstalledAppWithoutInstantMetadata || (isInstantApp 4046 && !canAccessInstantApps)) { 4047 Slog.w(TAG, "Invalid packageName: " + packageName); 4048 if (observer != null) { 4049 try { 4050 observer.onRemoveCompleted(packageName, false); 4051 } catch (RemoteException e) { 4052 Slog.i(TAG, "Observer no longer exists."); 4053 } 4054 } 4055 return false; 4056 } 4057 4058 if (appInfo != null) { 4059 forceStopPackageLocked(packageName, appInfo.uid, "clear data"); 4060 mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId); 4061 } 4062 } 4063 4064 final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() { 4065 @Override 4066 public void onRemoveCompleted(String packageName, boolean succeeded) 4067 throws RemoteException { 4068 if (appInfo != null) { 4069 synchronized (ActivityManagerService.this) { 4070 finishForceStopPackageLocked(packageName, appInfo.uid); 4071 } 4072 } 4073 final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 4074 Uri.fromParts("package", packageName, null)); 4075 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 4076 intent.putExtra(Intent.EXTRA_UID, (appInfo != null) ? appInfo.uid : -1); 4077 intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId); 4078 if (isInstantApp) { 4079 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName); 4080 broadcastIntentInPackage("android", SYSTEM_UID, uid, pid, intent, null, 4081 null, 0, null, null, permission.ACCESS_INSTANT_APPS, null, false, 4082 false, resolvedUserId, false); 4083 } else { 4084 broadcastIntentInPackage("android", SYSTEM_UID, uid, pid, intent, null, 4085 null, 0, null, null, null, null, false, false, resolvedUserId, 4086 false); 4087 } 4088 4089 if (observer != null) { 4090 observer.onRemoveCompleted(packageName, succeeded); 4091 } 4092 } 4093 }; 4094 4095 try { 4096 // Clear application user data 4097 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId); 4098 4099 if (appInfo != null) { 4100 // Restore already established notification state and permission grants, 4101 // so it told us to keep those intact -- it's about to emplace app data 4102 // that is appropriate for those bits of system state. 4103 if (!keepState) { 4104 // Remove all permissions granted from/to this package 4105 mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId, 4106 true, false); 4107 4108 // Reset notification state 4109 INotificationManager inm = NotificationManager.getService(); 4110 inm.clearData(packageName, appInfo.uid, uid == appInfo.uid); 4111 } 4112 4113 // Clear its scheduled jobs 4114 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 4115 js.cancelJobsForUid(appInfo.uid, "clear data"); 4116 4117 // Clear its pending alarms 4118 AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class); 4119 ami.removeAlarmsForUid(appInfo.uid); 4120 } 4121 } catch (RemoteException e) { 4122 } 4123 } finally { 4124 Binder.restoreCallingIdentity(callingId); 4125 } 4126 return true; 4127 } 4128 4129 @Override killBackgroundProcesses(final String packageName, int userId)4130 public void killBackgroundProcesses(final String packageName, int userId) { 4131 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 4132 != PackageManager.PERMISSION_GRANTED && 4133 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 4134 != PackageManager.PERMISSION_GRANTED) { 4135 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 4136 + Binder.getCallingPid() 4137 + ", uid=" + Binder.getCallingUid() 4138 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 4139 Slog.w(TAG, msg); 4140 throw new SecurityException(msg); 4141 } 4142 4143 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 4144 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 4145 final int[] userIds = mUserController.expandUserId(userId); 4146 4147 long callingId = Binder.clearCallingIdentity(); 4148 try { 4149 IPackageManager pm = AppGlobals.getPackageManager(); 4150 for (int targetUserId : userIds) { 4151 int appId = -1; 4152 try { 4153 appId = UserHandle.getAppId( 4154 pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 4155 targetUserId)); 4156 } catch (RemoteException e) { 4157 } 4158 if (appId == -1) { 4159 Slog.w(TAG, "Invalid packageName: " + packageName); 4160 return; 4161 } 4162 synchronized (this) { 4163 mProcessList.killPackageProcessesLocked(packageName, appId, targetUserId, 4164 ProcessList.SERVICE_ADJ, "kill background"); 4165 } 4166 } 4167 } finally { 4168 Binder.restoreCallingIdentity(callingId); 4169 } 4170 } 4171 4172 @Override killAllBackgroundProcesses()4173 public void killAllBackgroundProcesses() { 4174 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 4175 != PackageManager.PERMISSION_GRANTED) { 4176 final String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 4177 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 4178 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 4179 Slog.w(TAG, msg); 4180 throw new SecurityException(msg); 4181 } 4182 4183 final long callingId = Binder.clearCallingIdentity(); 4184 try { 4185 synchronized (this) { 4186 // Allow memory level to go down (the flag needs to be set before updating oom adj) 4187 // because this method is also used to simulate low memory. 4188 mAllowLowerMemLevel = true; 4189 mProcessList.killPackageProcessesLocked(null /* packageName */, -1 /* appId */, 4190 UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ, "kill all background"); 4191 4192 doLowMemReportIfNeededLocked(null); 4193 } 4194 } finally { 4195 Binder.restoreCallingIdentity(callingId); 4196 } 4197 } 4198 4199 /** 4200 * Kills all background processes, except those matching any of the 4201 * specified properties. 4202 * 4203 * @param minTargetSdk the target SDK version at or above which to preserve 4204 * processes, or {@code -1} to ignore the target SDK 4205 * @param maxProcState the process state at or below which to preserve 4206 * processes, or {@code -1} to ignore the process state 4207 */ killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)4208 void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 4209 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 4210 != PackageManager.PERMISSION_GRANTED) { 4211 final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid=" 4212 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 4213 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 4214 Slog.w(TAG, msg); 4215 throw new SecurityException(msg); 4216 } 4217 4218 final long callingId = Binder.clearCallingIdentity(); 4219 try { 4220 synchronized (this) { 4221 mProcessList.killAllBackgroundProcessesExceptLocked(minTargetSdk, maxProcState); 4222 } 4223 } finally { 4224 Binder.restoreCallingIdentity(callingId); 4225 } 4226 } 4227 4228 @Override forceStopPackage(final String packageName, int userId)4229 public void forceStopPackage(final String packageName, int userId) { 4230 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4231 != PackageManager.PERMISSION_GRANTED) { 4232 String msg = "Permission Denial: forceStopPackage() from pid=" 4233 + Binder.getCallingPid() 4234 + ", uid=" + Binder.getCallingUid() 4235 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 4236 Slog.w(TAG, msg); 4237 throw new SecurityException(msg); 4238 } 4239 final int callingPid = Binder.getCallingPid(); 4240 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 4241 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 4242 long callingId = Binder.clearCallingIdentity(); 4243 try { 4244 IPackageManager pm = AppGlobals.getPackageManager(); 4245 synchronized(this) { 4246 int[] users = userId == UserHandle.USER_ALL 4247 ? mUserController.getUsers() : new int[] { userId }; 4248 for (int user : users) { 4249 if (getPackageManagerInternalLocked().isPackageStateProtected( 4250 packageName, user)) { 4251 Slog.w(TAG, "Ignoring request to force stop protected package " 4252 + packageName + " u" + user); 4253 return; 4254 } 4255 4256 int pkgUid = -1; 4257 try { 4258 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 4259 user); 4260 } catch (RemoteException e) { 4261 } 4262 if (pkgUid == -1) { 4263 Slog.w(TAG, "Invalid packageName: " + packageName); 4264 continue; 4265 } 4266 try { 4267 pm.setPackageStoppedState(packageName, true, user); 4268 } catch (RemoteException e) { 4269 } catch (IllegalArgumentException e) { 4270 Slog.w(TAG, "Failed trying to unstop package " 4271 + packageName + ": " + e); 4272 } 4273 if (mUserController.isUserRunning(user, 0)) { 4274 forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid); 4275 finishForceStopPackageLocked(packageName, pkgUid); 4276 } 4277 } 4278 } 4279 } finally { 4280 Binder.restoreCallingIdentity(callingId); 4281 } 4282 } 4283 4284 @Override addPackageDependency(String packageName)4285 public void addPackageDependency(String packageName) { 4286 synchronized (this) { 4287 int callingPid = Binder.getCallingPid(); 4288 if (callingPid == myPid()) { 4289 // Yeah, um, no. 4290 return; 4291 } 4292 ProcessRecord proc; 4293 synchronized (mPidsSelfLocked) { 4294 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 4295 } 4296 if (proc != null) { 4297 if (proc.pkgDeps == null) { 4298 proc.pkgDeps = new ArraySet<String>(1); 4299 } 4300 proc.pkgDeps.add(packageName); 4301 } 4302 } 4303 } 4304 4305 /* 4306 * The pkg name and app id have to be specified. 4307 */ 4308 @Override killApplication(String pkg, int appId, int userId, String reason)4309 public void killApplication(String pkg, int appId, int userId, String reason) { 4310 if (pkg == null) { 4311 return; 4312 } 4313 // Make sure the uid is valid. 4314 if (appId < 0) { 4315 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 4316 return; 4317 } 4318 int callerUid = Binder.getCallingUid(); 4319 // Only the system server can kill an application 4320 if (UserHandle.getAppId(callerUid) == SYSTEM_UID) { 4321 // Post an aysnc message to kill the application 4322 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 4323 msg.arg1 = appId; 4324 msg.arg2 = userId; 4325 Bundle bundle = new Bundle(); 4326 bundle.putString("pkg", pkg); 4327 bundle.putString("reason", reason); 4328 msg.obj = bundle; 4329 mHandler.sendMessage(msg); 4330 } else { 4331 throw new SecurityException(callerUid + " cannot kill pkg: " + 4332 pkg); 4333 } 4334 } 4335 4336 @Override closeSystemDialogs(String reason)4337 public void closeSystemDialogs(String reason) { 4338 mAtmInternal.closeSystemDialogs(reason); 4339 } 4340 4341 @Override getProcessMemoryInfo(int[] pids)4342 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 4343 enforceNotIsolatedCaller("getProcessMemoryInfo"); 4344 4345 final long now = SystemClock.uptimeMillis(); 4346 final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME; 4347 4348 final int callingPid = Binder.getCallingPid(); 4349 final int callingUid = Binder.getCallingUid(); 4350 final int callingUserId = UserHandle.getUserId(callingUid); 4351 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 4352 callingUid) == PackageManager.PERMISSION_GRANTED; 4353 // Check REAL_GET_TASKS to see if they are allowed to access other uids 4354 final boolean allUids = mAtmInternal.isGetTasksAllowed( 4355 "getProcessMemoryInfo", callingPid, callingUid); 4356 4357 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 4358 for (int i=pids.length-1; i>=0; i--) { 4359 infos[i] = new Debug.MemoryInfo(); 4360 final ProcessRecord proc; 4361 final int oomAdj; 4362 synchronized (this) { 4363 synchronized (mPidsSelfLocked) { 4364 proc = mPidsSelfLocked.get(pids[i]); 4365 oomAdj = proc != null ? proc.setAdj : 0; 4366 } 4367 } 4368 final int targetUid = (proc != null) ? proc.uid : -1; 4369 final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1; 4370 4371 if (callingUid != targetUid) { 4372 if (!allUids) { 4373 continue; // Not allowed to see other UIDs. 4374 } 4375 4376 if (!allUsers && (targetUserId != callingUserId)) { 4377 continue; // Not allowed to see other users. 4378 } 4379 } 4380 if (proc != null && proc.lastMemInfoTime >= lastNow && proc.lastMemInfo != null) { 4381 // It hasn't been long enough that we want to take another sample; return 4382 // the last one. 4383 infos[i].set(proc.lastMemInfo); 4384 continue; 4385 } 4386 final long startTime = SystemClock.currentThreadTimeMillis(); 4387 final Debug.MemoryInfo memInfo = new Debug.MemoryInfo(); 4388 Debug.getMemoryInfo(pids[i], memInfo); 4389 final long endTime = SystemClock.currentThreadTimeMillis(); 4390 infos[i].set(memInfo); 4391 if (proc != null) { 4392 synchronized (this) { 4393 proc.lastMemInfo = memInfo; 4394 proc.lastMemInfoTime = SystemClock.uptimeMillis(); 4395 if (proc.thread != null && proc.setAdj == oomAdj) { 4396 // Record this for posterity if the process has been stable. 4397 proc.baseProcessTracker.addPss(infos[i].getTotalPss(), 4398 infos[i].getTotalUss(), infos[i].getTotalRss(), false, 4399 ProcessStats.ADD_PSS_EXTERNAL_SLOW, endTime - startTime, 4400 proc.pkgList.mPkgList); 4401 for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) { 4402 ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg); 4403 StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED, 4404 proc.info.uid, 4405 holder.state.getName(), 4406 holder.state.getPackage(), 4407 infos[i].getTotalPss(), 4408 infos[i].getTotalUss(), 4409 infos[i].getTotalRss(), 4410 ProcessStats.ADD_PSS_EXTERNAL_SLOW, 4411 endTime-startTime, 4412 holder.appVersion); 4413 } 4414 } 4415 } 4416 } 4417 } 4418 return infos; 4419 } 4420 4421 @Override getProcessPss(int[] pids)4422 public long[] getProcessPss(int[] pids) { 4423 enforceNotIsolatedCaller("getProcessPss"); 4424 4425 final int callingPid = Binder.getCallingPid(); 4426 final int callingUid = Binder.getCallingUid(); 4427 final int userId = UserHandle.getUserId(callingUid); 4428 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 4429 callingUid) == PackageManager.PERMISSION_GRANTED; 4430 // Check REAL_GET_TASKS to see if they are allowed to access other uids 4431 final boolean allUids = mAtmInternal.isGetTasksAllowed( 4432 "getProcessPss", callingPid, callingUid); 4433 4434 long[] pss = new long[pids.length]; 4435 for (int i=pids.length-1; i>=0; i--) { 4436 ProcessRecord proc; 4437 int oomAdj; 4438 synchronized (this) { 4439 synchronized (mPidsSelfLocked) { 4440 proc = mPidsSelfLocked.get(pids[i]); 4441 oomAdj = proc != null ? proc.setAdj : 0; 4442 } 4443 } 4444 if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) { 4445 // The caller is not allow to get information about this other process... 4446 // just leave it empty. 4447 continue; 4448 } 4449 long[] tmpUss = new long[3]; 4450 long startTime = SystemClock.currentThreadTimeMillis(); 4451 pss[i] = Debug.getPss(pids[i], tmpUss, null); 4452 long endTime = SystemClock.currentThreadTimeMillis(); 4453 if (proc != null) { 4454 synchronized (this) { 4455 if (proc.thread != null && proc.setAdj == oomAdj) { 4456 // Record this for posterity if the process has been stable. 4457 proc.baseProcessTracker.addPss(pss[i], tmpUss[0], tmpUss[2], false, 4458 ProcessStats.ADD_PSS_EXTERNAL, endTime-startTime, proc.pkgList.mPkgList); 4459 for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) { 4460 ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg); 4461 StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED, 4462 proc.info.uid, 4463 holder.state.getName(), 4464 holder.state.getPackage(), 4465 pss[i], tmpUss[0], tmpUss[2], 4466 ProcessStats.ADD_PSS_EXTERNAL, endTime-startTime, 4467 holder.appVersion); 4468 } 4469 } 4470 } 4471 } 4472 } 4473 return pss; 4474 } 4475 4476 @Override killApplicationProcess(String processName, int uid)4477 public void killApplicationProcess(String processName, int uid) { 4478 if (processName == null) { 4479 return; 4480 } 4481 4482 int callerUid = Binder.getCallingUid(); 4483 // Only the system server can kill an application 4484 if (callerUid == SYSTEM_UID) { 4485 synchronized (this) { 4486 ProcessRecord app = getProcessRecordLocked(processName, uid, true); 4487 if (app != null && app.thread != null) { 4488 try { 4489 app.thread.scheduleSuicide(); 4490 } catch (RemoteException e) { 4491 // If the other end already died, then our work here is done. 4492 } 4493 } else { 4494 Slog.w(TAG, "Process/uid not found attempting kill of " 4495 + processName + " / " + uid); 4496 } 4497 } 4498 } else { 4499 throw new SecurityException(callerUid + " cannot kill app process: " + 4500 processName); 4501 } 4502 } 4503 4504 @GuardedBy("this") forceStopPackageLocked(final String packageName, int uid, String reason)4505 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 4506 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 4507 false, true, false, false, UserHandle.getUserId(uid), reason); 4508 } 4509 4510 @GuardedBy("this") finishForceStopPackageLocked(final String packageName, int uid)4511 private void finishForceStopPackageLocked(final String packageName, int uid) { 4512 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 4513 Uri.fromParts("package", packageName, null)); 4514 if (!mProcessesReady) { 4515 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 4516 | Intent.FLAG_RECEIVER_FOREGROUND); 4517 } 4518 intent.putExtra(Intent.EXTRA_UID, uid); 4519 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 4520 broadcastIntentLocked(null, null, intent, 4521 null, null, 0, null, null, null, OP_NONE, 4522 null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(), 4523 Binder.getCallingPid(), UserHandle.getUserId(uid)); 4524 } 4525 cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4526 private void cleanupDisabledPackageComponentsLocked( 4527 String packageName, int userId, String[] changedClasses) { 4528 4529 Set<String> disabledClasses = null; 4530 boolean packageDisabled = false; 4531 IPackageManager pm = AppGlobals.getPackageManager(); 4532 4533 if (changedClasses == null) { 4534 // Nothing changed... 4535 return; 4536 } 4537 4538 // Determine enable/disable state of the package and its components. 4539 int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4540 for (int i = changedClasses.length - 1; i >= 0; i--) { 4541 final String changedClass = changedClasses[i]; 4542 4543 if (changedClass.equals(packageName)) { 4544 try { 4545 // Entire package setting changed 4546 enabled = pm.getApplicationEnabledSetting(packageName, 4547 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4548 } catch (Exception e) { 4549 // No such package/component; probably racing with uninstall. In any 4550 // event it means we have nothing further to do here. 4551 return; 4552 } 4553 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4554 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4555 if (packageDisabled) { 4556 // Entire package is disabled. 4557 // No need to continue to check component states. 4558 disabledClasses = null; 4559 break; 4560 } 4561 } else { 4562 try { 4563 enabled = pm.getComponentEnabledSetting( 4564 new ComponentName(packageName, changedClass), 4565 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4566 } catch (Exception e) { 4567 // As above, probably racing with uninstall. 4568 return; 4569 } 4570 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4571 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) { 4572 if (disabledClasses == null) { 4573 disabledClasses = new ArraySet<>(changedClasses.length); 4574 } 4575 disabledClasses.add(changedClass); 4576 } 4577 } 4578 } 4579 4580 if (!packageDisabled && disabledClasses == null) { 4581 // Nothing to do here... 4582 return; 4583 } 4584 4585 mAtmInternal.cleanupDisabledPackageComponents( 4586 packageName, disabledClasses, userId, mBooted); 4587 4588 // Clean-up disabled services. 4589 mServices.bringDownDisabledPackageServicesLocked( 4590 packageName, disabledClasses, userId, false /* evenPersistent */, true /* doIt */); 4591 4592 // Clean-up disabled providers. 4593 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4594 mProviderMap.collectPackageProvidersLocked( 4595 packageName, disabledClasses, true, false, userId, providers); 4596 for (int i = providers.size() - 1; i >= 0; i--) { 4597 removeDyingProviderLocked(null, providers.get(i), true); 4598 } 4599 4600 // Clean-up disabled broadcast receivers. 4601 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 4602 mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4603 packageName, disabledClasses, userId, true); 4604 } 4605 4606 } 4607 clearBroadcastQueueForUserLocked(int userId)4608 final boolean clearBroadcastQueueForUserLocked(int userId) { 4609 boolean didSomething = false; 4610 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 4611 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4612 null, null, userId, true); 4613 } 4614 return didSomething; 4615 } 4616 4617 @GuardedBy("this") forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reason)4618 final boolean forceStopPackageLocked(String packageName, int appId, 4619 boolean callerWillRestart, boolean purgeCache, boolean doit, 4620 boolean evenPersistent, boolean uninstalling, int userId, String reason) { 4621 int i; 4622 4623 if (userId == UserHandle.USER_ALL && packageName == null) { 4624 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 4625 } 4626 4627 if (appId < 0 && packageName != null) { 4628 try { 4629 appId = UserHandle.getAppId(AppGlobals.getPackageManager() 4630 .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0)); 4631 } catch (RemoteException e) { 4632 } 4633 } 4634 4635 if (doit) { 4636 if (packageName != null) { 4637 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId 4638 + " user=" + userId + ": " + reason); 4639 } else { 4640 Slog.i(TAG, "Force stopping u" + userId + ": " + reason); 4641 } 4642 4643 mAppErrors.resetProcessCrashTimeLocked(packageName == null, appId, userId); 4644 } 4645 4646 boolean didSomething = mProcessList.killPackageProcessesLocked(packageName, appId, userId, 4647 ProcessList.INVALID_ADJ, callerWillRestart, true /* allowRestart */, doit, 4648 evenPersistent, true /* setRemoved */, 4649 packageName == null ? ("stop user " + userId) : ("stop " + packageName)); 4650 4651 didSomething |= 4652 mAtmInternal.onForceStopPackage(packageName, doit, evenPersistent, userId); 4653 4654 if (mServices.bringDownDisabledPackageServicesLocked( 4655 packageName, null /* filterByClasses */, userId, evenPersistent, doit)) { 4656 if (!doit) { 4657 return true; 4658 } 4659 didSomething = true; 4660 } 4661 4662 if (packageName == null) { 4663 // Remove all sticky broadcasts from this user. 4664 mStickyBroadcasts.remove(userId); 4665 } 4666 4667 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4668 if (mProviderMap.collectPackageProvidersLocked(packageName, null, doit, evenPersistent, 4669 userId, providers)) { 4670 if (!doit) { 4671 return true; 4672 } 4673 didSomething = true; 4674 } 4675 for (i = providers.size() - 1; i >= 0; i--) { 4676 removeDyingProviderLocked(null, providers.get(i), true); 4677 } 4678 4679 // Remove transient permissions granted from/to this package/user 4680 mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false); 4681 4682 if (doit) { 4683 for (i = mBroadcastQueues.length - 1; i >= 0; i--) { 4684 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4685 packageName, null, userId, doit); 4686 } 4687 } 4688 4689 if (packageName == null || uninstalling) { 4690 didSomething |= mPendingIntentController.removePendingIntentsForPackage( 4691 packageName, userId, appId, doit); 4692 } 4693 4694 if (doit) { 4695 if (purgeCache && packageName != null) { 4696 AttributeCache ac = AttributeCache.instance(); 4697 if (ac != null) { 4698 ac.removePackage(packageName); 4699 } 4700 } 4701 if (mBooted) { 4702 mAtmInternal.resumeTopActivities(true /* scheduleIdle */); 4703 } 4704 } 4705 4706 return didSomething; 4707 } 4708 4709 @GuardedBy("this") processContentProviderPublishTimedOutLocked(ProcessRecord app)4710 private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) { 4711 cleanupAppInLaunchingProvidersLocked(app, true); 4712 mProcessList.removeProcessLocked(app, false, true, "timeout publishing content providers"); 4713 } 4714 4715 @GuardedBy("this") processStartTimedOutLocked(ProcessRecord app)4716 private final void processStartTimedOutLocked(ProcessRecord app) { 4717 final int pid = app.pid; 4718 boolean gone = mPidsSelfLocked.removeIfNoThread(app); 4719 4720 if (gone) { 4721 Slog.w(TAG, "Process " + app + " failed to attach"); 4722 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId, 4723 pid, app.uid, app.processName); 4724 mProcessList.removeProcessNameLocked(app.processName, app.uid); 4725 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 4726 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 4727 // Take care of any launching providers waiting for this process. 4728 cleanupAppInLaunchingProvidersLocked(app, true); 4729 // Take care of any services that are waiting for the process. 4730 mServices.processStartTimedOutLocked(app); 4731 app.kill("start timeout", true); 4732 if (app.isolated) { 4733 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 4734 } 4735 removeLruProcessLocked(app); 4736 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4737 if (backupTarget != null && backupTarget.app.pid == pid) { 4738 Slog.w(TAG, "Unattached app died before backup, skipping"); 4739 mHandler.post(new Runnable() { 4740 @Override 4741 public void run(){ 4742 try { 4743 IBackupManager bm = IBackupManager.Stub.asInterface( 4744 ServiceManager.getService(Context.BACKUP_SERVICE)); 4745 bm.agentDisconnectedForUser(app.userId, app.info.packageName); 4746 } catch (RemoteException e) { 4747 // Can't happen; the backup manager is local 4748 } 4749 } 4750 }); 4751 } 4752 if (isPendingBroadcastProcessLocked(pid)) { 4753 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 4754 skipPendingBroadcastLocked(pid); 4755 } 4756 } else { 4757 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 4758 } 4759 } 4760 4761 @GuardedBy("this") attachApplicationLocked(IApplicationThread thread, int pid, int callingUid, long startSeq)4762 private final boolean attachApplicationLocked(IApplicationThread thread, 4763 int pid, int callingUid, long startSeq) { 4764 4765 // Find the application record that is being attached... either via 4766 // the pid if we are running in multiple processes, or just pull the 4767 // next app record if we are emulating process with anonymous threads. 4768 ProcessRecord app; 4769 long startTime = SystemClock.uptimeMillis(); 4770 long bindApplicationTimeMillis; 4771 if (pid != MY_PID && pid >= 0) { 4772 synchronized (mPidsSelfLocked) { 4773 app = mPidsSelfLocked.get(pid); 4774 } 4775 if (app != null && (app.startUid != callingUid || app.startSeq != startSeq)) { 4776 String processName = null; 4777 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4778 if (pending != null) { 4779 processName = pending.processName; 4780 } 4781 final String msg = "attachApplicationLocked process:" + processName 4782 + " startSeq:" + startSeq 4783 + " pid:" + pid 4784 + " belongs to another existing app:" + app.processName 4785 + " startSeq:" + app.startSeq; 4786 Slog.wtf(TAG, msg); 4787 // SafetyNet logging for b/131105245. 4788 EventLog.writeEvent(0x534e4554, "131105245", app.startUid, msg); 4789 // If there is already an app occupying that pid that hasn't been cleaned up 4790 cleanUpApplicationRecordLocked(app, false, false, -1, 4791 true /*replacingPid*/); 4792 mPidsSelfLocked.remove(app); 4793 app = null; 4794 } 4795 } else { 4796 app = null; 4797 } 4798 4799 // It's possible that process called attachApplication before we got a chance to 4800 // update the internal state. 4801 if (app == null && startSeq > 0) { 4802 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4803 if (pending != null && pending.startUid == callingUid && pending.startSeq == startSeq 4804 && mProcessList.handleProcessStartedLocked(pending, pid, pending 4805 .isUsingWrapper(), 4806 startSeq, true)) { 4807 app = pending; 4808 } 4809 } 4810 4811 if (app == null) { 4812 Slog.w(TAG, "No pending application record for pid " + pid 4813 + " (IApplicationThread " + thread + "); dropping process"); 4814 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); 4815 if (pid > 0 && pid != MY_PID) { 4816 killProcessQuiet(pid); 4817 //TODO: killProcessGroup(app.info.uid, pid); 4818 } else { 4819 try { 4820 thread.scheduleExit(); 4821 } catch (Exception e) { 4822 // Ignore exceptions. 4823 } 4824 } 4825 return false; 4826 } 4827 4828 // If this application record is still attached to a previous 4829 // process, clean it up now. 4830 if (app.thread != null) { 4831 handleAppDiedLocked(app, true, true); 4832 } 4833 4834 // Tell the process all about itself. 4835 4836 if (DEBUG_ALL) Slog.v( 4837 TAG, "Binding process pid " + pid + " to record " + app); 4838 4839 final String processName = app.processName; 4840 try { 4841 AppDeathRecipient adr = new AppDeathRecipient( 4842 app, pid, thread); 4843 thread.asBinder().linkToDeath(adr, 0); 4844 app.deathRecipient = adr; 4845 } catch (RemoteException e) { 4846 app.resetPackageList(mProcessStats); 4847 mProcessList.startProcessLocked(app, 4848 new HostingRecord("link fail", processName)); 4849 return false; 4850 } 4851 4852 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName); 4853 4854 app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ; 4855 app.setCurrentSchedulingGroup(app.setSchedGroup = ProcessList.SCHED_GROUP_DEFAULT); 4856 app.forcingToImportant = null; 4857 updateProcessForegroundLocked(app, false, 0, false); 4858 app.hasShownUi = false; 4859 app.setDebugging(false); 4860 app.cached = false; 4861 app.killedByAm = false; 4862 app.killed = false; 4863 4864 4865 // We carefully use the same state that PackageManager uses for 4866 // filtering, since we use this flag to decide if we need to install 4867 // providers when user is unlocked later 4868 app.unlocked = StorageManager.isUserKeyUnlocked(app.userId); 4869 4870 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4871 4872 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4873 List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null; 4874 4875 if (providers != null && checkAppInLaunchingProvidersLocked(app)) { 4876 Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG); 4877 msg.obj = app; 4878 mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT); 4879 } 4880 4881 checkTime(startTime, "attachApplicationLocked: before bindApplication"); 4882 4883 if (!normalMode) { 4884 Slog.i(TAG, "Launching preboot mode app: " + app); 4885 } 4886 4887 if (DEBUG_ALL) Slog.v( 4888 TAG, "New app record " + app 4889 + " thread=" + thread.asBinder() + " pid=" + pid); 4890 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4891 try { 4892 int testMode = ApplicationThreadConstants.DEBUG_OFF; 4893 if (mDebugApp != null && mDebugApp.equals(processName)) { 4894 testMode = mWaitForDebugger 4895 ? ApplicationThreadConstants.DEBUG_WAIT 4896 : ApplicationThreadConstants.DEBUG_ON; 4897 app.setDebugging(true); 4898 if (mDebugTransient) { 4899 mDebugApp = mOrigDebugApp; 4900 mWaitForDebugger = mOrigWaitForDebugger; 4901 } 4902 } 4903 4904 boolean enableTrackAllocation = false; 4905 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) { 4906 enableTrackAllocation = true; 4907 mTrackAllocationApp = null; 4908 } 4909 4910 // If the app is being launched for restore or full backup, set it up specially 4911 boolean isRestrictedBackupMode = false; 4912 if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) { 4913 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID 4914 && ((backupTarget.backupMode == BackupRecord.RESTORE) 4915 || (backupTarget.backupMode == BackupRecord.RESTORE_FULL) 4916 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL)); 4917 } 4918 4919 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 4920 4921 if (instr != null) { 4922 notifyPackageUse(instr.mClass.getPackageName(), 4923 PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION); 4924 } 4925 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Binding proc " 4926 + processName + " with config " 4927 + app.getWindowProcessController().getConfiguration()); 4928 ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info; 4929 app.compat = compatibilityInfoForPackage(appInfo); 4930 4931 ProfilerInfo profilerInfo = null; 4932 String preBindAgent = null; 4933 if (mProfileData.getProfileApp() != null 4934 && mProfileData.getProfileApp().equals(processName)) { 4935 mProfileData.setProfileProc(app); 4936 if (mProfileData.getProfilerInfo() != null) { 4937 // Send a profiler info object to the app if either a file is given, or 4938 // an agent should be loaded at bind-time. 4939 boolean needsInfo = mProfileData.getProfilerInfo().profileFile != null 4940 || mProfileData.getProfilerInfo().attachAgentDuringBind; 4941 profilerInfo = needsInfo 4942 ? new ProfilerInfo(mProfileData.getProfilerInfo()) : null; 4943 if (mProfileData.getProfilerInfo().agent != null) { 4944 preBindAgent = mProfileData.getProfilerInfo().agent; 4945 } 4946 } 4947 } else if (instr != null && instr.mProfileFile != null) { 4948 profilerInfo = new ProfilerInfo(instr.mProfileFile, null, 0, false, false, 4949 null, false); 4950 } 4951 if (mAppAgentMap != null && mAppAgentMap.containsKey(processName)) { 4952 // We need to do a debuggable check here. See setAgentApp for why the check is 4953 // postponed to here. 4954 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 4955 String agent = mAppAgentMap.get(processName); 4956 // Do not overwrite already requested agent. 4957 if (profilerInfo == null) { 4958 profilerInfo = new ProfilerInfo(null, null, 0, false, false, 4959 mAppAgentMap.get(processName), true); 4960 } else if (profilerInfo.agent == null) { 4961 profilerInfo = profilerInfo.setAgent(mAppAgentMap.get(processName), true); 4962 } 4963 } 4964 } 4965 4966 if (profilerInfo != null && profilerInfo.profileFd != null) { 4967 profilerInfo.profileFd = profilerInfo.profileFd.dup(); 4968 if (TextUtils.equals(mProfileData.getProfileApp(), processName) 4969 && mProfileData.getProfilerInfo() != null) { 4970 clearProfilerLocked(); 4971 } 4972 } 4973 4974 // We deprecated Build.SERIAL and it is not accessible to 4975 // Instant Apps and target APIs higher than O MR1. Since access to the serial 4976 // is now behind a permission we push down the value. 4977 final String buildSerial = (!appInfo.isInstantApp() 4978 && appInfo.targetSdkVersion < Build.VERSION_CODES.P) 4979 ? sTheRealBuildSerial : Build.UNKNOWN; 4980 4981 // Check if this is a secondary process that should be incorporated into some 4982 // currently active instrumentation. (Note we do this AFTER all of the profiling 4983 // stuff above because profiling can currently happen only in the primary 4984 // instrumentation process.) 4985 if (mActiveInstrumentation.size() > 0 && instr == null) { 4986 for (int i = mActiveInstrumentation.size() - 1; 4987 i >= 0 && app.getActiveInstrumentation() == null; i--) { 4988 ActiveInstrumentation aInstr = mActiveInstrumentation.get(i); 4989 if (!aInstr.mFinished && aInstr.mTargetInfo.uid == app.uid) { 4990 if (aInstr.mTargetProcesses.length == 0) { 4991 // This is the wildcard mode, where every process brought up for 4992 // the target instrumentation should be included. 4993 if (aInstr.mTargetInfo.packageName.equals(app.info.packageName)) { 4994 app.setActiveInstrumentation(aInstr); 4995 aInstr.mRunningProcesses.add(app); 4996 } 4997 } else { 4998 for (String proc : aInstr.mTargetProcesses) { 4999 if (proc.equals(app.processName)) { 5000 app.setActiveInstrumentation(aInstr); 5001 aInstr.mRunningProcesses.add(app); 5002 break; 5003 } 5004 } 5005 } 5006 } 5007 } 5008 } 5009 5010 // If we were asked to attach an agent on startup, do so now, before we're binding 5011 // application code. 5012 if (preBindAgent != null) { 5013 thread.attachAgent(preBindAgent); 5014 } 5015 5016 5017 // Figure out whether the app needs to run in autofill compat mode. 5018 AutofillOptions autofillOptions = null; 5019 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 5020 final AutofillManagerInternal afm = LocalServices.getService( 5021 AutofillManagerInternal.class); 5022 if (afm != null) { 5023 autofillOptions = afm.getAutofillOptions( 5024 app.info.packageName, app.info.longVersionCode, app.userId); 5025 } 5026 } 5027 ContentCaptureOptions contentCaptureOptions = null; 5028 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 5029 final ContentCaptureManagerInternal ccm = 5030 LocalServices.getService(ContentCaptureManagerInternal.class); 5031 if (ccm != null) { 5032 contentCaptureOptions = ccm.getOptionsForPackage(app.userId, 5033 app.info.packageName); 5034 } 5035 } 5036 5037 checkTime(startTime, "attachApplicationLocked: immediately before bindApplication"); 5038 bindApplicationTimeMillis = SystemClock.elapsedRealtime(); 5039 mAtmInternal.preBindApplication(app.getWindowProcessController()); 5040 final ActiveInstrumentation instr2 = app.getActiveInstrumentation(); 5041 if (app.isolatedEntryPoint != null) { 5042 // This is an isolated process which should just call an entry point instead of 5043 // being bound to an application. 5044 thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs); 5045 } else if (instr2 != null) { 5046 thread.bindApplication(processName, appInfo, providers, 5047 instr2.mClass, 5048 profilerInfo, instr2.mArguments, 5049 instr2.mWatcher, 5050 instr2.mUiAutomationConnection, testMode, 5051 mBinderTransactionTrackingEnabled, enableTrackAllocation, 5052 isRestrictedBackupMode || !normalMode, app.isPersistent(), 5053 new Configuration(app.getWindowProcessController().getConfiguration()), 5054 app.compat, getCommonServicesLocked(app.isolated), 5055 mCoreSettingsObserver.getCoreSettingsLocked(), 5056 buildSerial, autofillOptions, contentCaptureOptions); 5057 } else { 5058 thread.bindApplication(processName, appInfo, providers, null, profilerInfo, 5059 null, null, null, testMode, 5060 mBinderTransactionTrackingEnabled, enableTrackAllocation, 5061 isRestrictedBackupMode || !normalMode, app.isPersistent(), 5062 new Configuration(app.getWindowProcessController().getConfiguration()), 5063 app.compat, getCommonServicesLocked(app.isolated), 5064 mCoreSettingsObserver.getCoreSettingsLocked(), 5065 buildSerial, autofillOptions, contentCaptureOptions); 5066 } 5067 if (profilerInfo != null) { 5068 profilerInfo.closeFd(); 5069 profilerInfo = null; 5070 } 5071 5072 // Make app active after binding application or client may be running requests (e.g 5073 // starting activities) before it is ready. 5074 app.makeActive(thread, mProcessStats); 5075 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication"); 5076 mProcessList.updateLruProcessLocked(app, false, null); 5077 checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked"); 5078 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); 5079 } catch (Exception e) { 5080 // todo: Yikes! What should we do? For now we will try to 5081 // start another process, but that could easily get us in 5082 // an infinite loop of restarting processes... 5083 Slog.wtf(TAG, "Exception thrown during bind of " + app, e); 5084 5085 app.resetPackageList(mProcessStats); 5086 app.unlinkDeathRecipient(); 5087 mProcessList.startProcessLocked(app, new HostingRecord("bind-fail", processName)); 5088 return false; 5089 } 5090 5091 // Remove this record from the list of starting applications. 5092 mPersistentStartingProcesses.remove(app); 5093 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, 5094 "Attach application locked removing on hold: " + app); 5095 mProcessesOnHold.remove(app); 5096 5097 boolean badApp = false; 5098 boolean didSomething = false; 5099 5100 // See if the top visible activity is waiting to run in this process... 5101 if (normalMode) { 5102 try { 5103 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); 5104 } catch (Exception e) { 5105 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); 5106 badApp = true; 5107 } 5108 } 5109 5110 // Find any services that should be running in this process... 5111 if (!badApp) { 5112 try { 5113 didSomething |= mServices.attachApplicationLocked(app, processName); 5114 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked"); 5115 } catch (Exception e) { 5116 Slog.wtf(TAG, "Exception thrown starting services in " + app, e); 5117 badApp = true; 5118 } 5119 } 5120 5121 // Check if a next-broadcast receiver is in this process... 5122 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 5123 try { 5124 didSomething |= sendPendingBroadcastsLocked(app); 5125 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked"); 5126 } catch (Exception e) { 5127 // If the app died trying to launch the receiver we declare it 'bad' 5128 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e); 5129 badApp = true; 5130 } 5131 } 5132 5133 // Check whether the next backup agent is in this process... 5134 if (!badApp && backupTarget != null && backupTarget.app == app) { 5135 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, 5136 "New app is backup target, launching agent for " + app); 5137 notifyPackageUse(backupTarget.appInfo.packageName, 5138 PackageManager.NOTIFY_PACKAGE_USE_BACKUP); 5139 try { 5140 thread.scheduleCreateBackupAgent(backupTarget.appInfo, 5141 compatibilityInfoForPackage(backupTarget.appInfo), 5142 backupTarget.backupMode, backupTarget.userId); 5143 } catch (Exception e) { 5144 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e); 5145 badApp = true; 5146 } 5147 } 5148 5149 if (badApp) { 5150 app.kill("error during init", true); 5151 handleAppDiedLocked(app, false, true); 5152 return false; 5153 } 5154 5155 if (!didSomething) { 5156 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN); 5157 checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked"); 5158 } 5159 5160 StatsLog.write( 5161 StatsLog.PROCESS_START_TIME, 5162 app.info.uid, 5163 app.pid, 5164 app.info.packageName, 5165 StatsLog.PROCESS_START_TIME__TYPE__COLD, 5166 app.startTime, 5167 (int) (bindApplicationTimeMillis - app.startTime), 5168 (int) (SystemClock.elapsedRealtime() - app.startTime), 5169 app.hostingRecord.getType(), 5170 (app.hostingRecord.getName() != null ? app.hostingRecord.getName() : "")); 5171 return true; 5172 } 5173 5174 @Override attachApplication(IApplicationThread thread, long startSeq)5175 public final void attachApplication(IApplicationThread thread, long startSeq) { 5176 synchronized (this) { 5177 int callingPid = Binder.getCallingPid(); 5178 final int callingUid = Binder.getCallingUid(); 5179 final long origId = Binder.clearCallingIdentity(); 5180 attachApplicationLocked(thread, callingPid, callingUid, startSeq); 5181 Binder.restoreCallingIdentity(origId); 5182 } 5183 } 5184 5185 @Override showBootMessage(final CharSequence msg, final boolean always)5186 public void showBootMessage(final CharSequence msg, final boolean always) { 5187 if (Binder.getCallingUid() != myUid()) { 5188 throw new SecurityException(); 5189 } 5190 mWindowManager.showBootMessage(msg, always); 5191 } 5192 finishBooting()5193 final void finishBooting() { 5194 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting"); 5195 5196 synchronized (this) { 5197 if (!mBootAnimationComplete) { 5198 mCallFinishBooting = true; 5199 return; 5200 } 5201 mCallFinishBooting = false; 5202 } 5203 5204 ArraySet<String> completedIsas = new ArraySet<String>(); 5205 for (String abi : Build.SUPPORTED_ABIS) { 5206 ZYGOTE_PROCESS.establishZygoteConnectionForAbi(abi); 5207 final String instructionSet = VMRuntime.getInstructionSet(abi); 5208 if (!completedIsas.contains(instructionSet)) { 5209 try { 5210 mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi)); 5211 } catch (InstallerException e) { 5212 if (!VMRuntime.didPruneDalvikCache()) { 5213 // This is technically not the right filter, as different zygotes may 5214 // have made different pruning decisions. But the log is best effort, 5215 // anyways. 5216 Slog.w(TAG, "Unable to mark boot complete for abi: " + abi + " (" + 5217 e.getMessage() +")"); 5218 } 5219 } 5220 completedIsas.add(instructionSet); 5221 } 5222 } 5223 5224 IntentFilter pkgFilter = new IntentFilter(); 5225 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 5226 pkgFilter.addDataScheme("package"); 5227 mContext.registerReceiver(new BroadcastReceiver() { 5228 @Override 5229 public void onReceive(Context context, Intent intent) { 5230 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 5231 if (pkgs != null) { 5232 for (String pkg : pkgs) { 5233 synchronized (ActivityManagerService.this) { 5234 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 5235 0, "query restart")) { 5236 setResultCode(Activity.RESULT_OK); 5237 return; 5238 } 5239 } 5240 } 5241 } 5242 } 5243 }, pkgFilter); 5244 5245 IntentFilter dumpheapFilter = new IntentFilter(); 5246 dumpheapFilter.addAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP); 5247 mContext.registerReceiver(new BroadcastReceiver() { 5248 @Override 5249 public void onReceive(Context context, Intent intent) { 5250 final long delay = intent.getBooleanExtra( 5251 DumpHeapActivity.EXTRA_DELAY_DELETE, false) ? 5 * 60 * 1000 : 0; 5252 mHandler.sendEmptyMessageDelayed(DELETE_DUMPHEAP_MSG, delay); 5253 } 5254 }, dumpheapFilter); 5255 5256 // Inform checkpointing systems of success 5257 try { 5258 IStorageManager storageManager = PackageHelper.getStorageManager(); 5259 storageManager.commitChanges(); 5260 } catch (Exception e) { 5261 PowerManager pm = (PowerManager) 5262 mInjector.getContext().getSystemService(Context.POWER_SERVICE); 5263 pm.reboot("Checkpoint commit failed"); 5264 } 5265 5266 // Let system services know. 5267 mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED); 5268 5269 synchronized (this) { 5270 // Ensure that any processes we had put on hold are now started 5271 // up. 5272 final int NP = mProcessesOnHold.size(); 5273 if (NP > 0) { 5274 ArrayList<ProcessRecord> procs = 5275 new ArrayList<ProcessRecord>(mProcessesOnHold); 5276 for (int ip=0; ip<NP; ip++) { 5277 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "Starting process on hold: " 5278 + procs.get(ip)); 5279 mProcessList.startProcessLocked(procs.get(ip), new HostingRecord("on-hold")); 5280 } 5281 } 5282 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 5283 return; 5284 } 5285 // Start looking for apps that are abusing wake locks. 5286 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 5287 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 5288 // Tell anyone interested that we are done booting! 5289 SystemProperties.set("sys.boot_completed", "1"); 5290 5291 // And trigger dev.bootcomplete if we are not showing encryption progress 5292 if (!"trigger_restart_min_framework".equals(VoldProperties.decrypt().orElse("")) 5293 || "".equals(VoldProperties.encrypt_progress().orElse(""))) { 5294 SystemProperties.set("dev.bootcomplete", "1"); 5295 } 5296 mUserController.sendBootCompleted( 5297 new IIntentReceiver.Stub() { 5298 @Override 5299 public void performReceive(Intent intent, int resultCode, 5300 String data, Bundle extras, boolean ordered, 5301 boolean sticky, int sendingUser) { 5302 synchronized (ActivityManagerService.this) { 5303 mOomAdjuster.mAppCompact.compactAllSystem(); 5304 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false); 5305 } 5306 } 5307 }); 5308 mUserController.scheduleStartProfiles(); 5309 } 5310 5311 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 5312 } 5313 5314 @Override bootAnimationComplete()5315 public void bootAnimationComplete() { 5316 final boolean callFinishBooting; 5317 synchronized (this) { 5318 callFinishBooting = mCallFinishBooting; 5319 mBootAnimationComplete = true; 5320 } 5321 if (callFinishBooting) { 5322 finishBooting(); 5323 } 5324 } 5325 ensureBootCompleted()5326 final void ensureBootCompleted() { 5327 boolean booting; 5328 boolean enableScreen; 5329 synchronized (this) { 5330 booting = mBooting; 5331 mBooting = false; 5332 enableScreen = !mBooted; 5333 mBooted = true; 5334 } 5335 5336 if (booting) { 5337 finishBooting(); 5338 } 5339 5340 if (enableScreen) { 5341 mAtmInternal.enableScreenAfterBoot(mBooted); 5342 } 5343 } 5344 5345 @Override getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5346 public IIntentSender getIntentSender(int type, 5347 String packageName, IBinder token, String resultWho, 5348 int requestCode, Intent[] intents, String[] resolvedTypes, 5349 int flags, Bundle bOptions, int userId) { 5350 5351 // NOTE: The service lock isn't held in this method because nothing in the method requires 5352 // the service lock to be held. 5353 5354 enforceNotIsolatedCaller("getIntentSender"); 5355 // Refuse possible leaked file descriptors 5356 if (intents != null) { 5357 if (intents.length < 1) { 5358 throw new IllegalArgumentException("Intents array length must be >= 1"); 5359 } 5360 for (int i=0; i<intents.length; i++) { 5361 Intent intent = intents[i]; 5362 if (intent != null) { 5363 if (intent.hasFileDescriptors()) { 5364 throw new IllegalArgumentException("File descriptors passed in Intent"); 5365 } 5366 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 5367 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 5368 throw new IllegalArgumentException( 5369 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 5370 } 5371 intents[i] = new Intent(intent); 5372 } 5373 } 5374 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 5375 throw new IllegalArgumentException( 5376 "Intent array length does not match resolvedTypes length"); 5377 } 5378 } 5379 if (bOptions != null) { 5380 if (bOptions.hasFileDescriptors()) { 5381 throw new IllegalArgumentException("File descriptors passed in options"); 5382 } 5383 } 5384 5385 int callingUid = Binder.getCallingUid(); 5386 int origUserId = userId; 5387 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 5388 type == ActivityManager.INTENT_SENDER_BROADCAST, 5389 ALLOW_NON_FULL, "getIntentSender", null); 5390 if (origUserId == UserHandle.USER_CURRENT) { 5391 // We don't want to evaluate this until the pending intent is 5392 // actually executed. However, we do want to always do the 5393 // security checking for it above. 5394 userId = UserHandle.USER_CURRENT; 5395 } 5396 try { 5397 if (callingUid != 0 && callingUid != SYSTEM_UID) { 5398 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName, 5399 MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callingUid)); 5400 if (!UserHandle.isSameApp(callingUid, uid)) { 5401 String msg = "Permission Denial: getIntentSender() from pid=" 5402 + Binder.getCallingPid() 5403 + ", uid=" + Binder.getCallingUid() 5404 + ", (need uid=" + uid + ")" 5405 + " is not allowed to send as package " + packageName; 5406 Slog.w(TAG, msg); 5407 throw new SecurityException(msg); 5408 } 5409 } 5410 5411 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 5412 return mAtmInternal.getIntentSender(type, packageName, callingUid, userId, 5413 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions); 5414 } 5415 return mPendingIntentController.getIntentSender(type, packageName, callingUid, 5416 userId, token, resultWho, requestCode, intents, resolvedTypes, flags, 5417 bOptions); 5418 } catch (RemoteException e) { 5419 throw new SecurityException(e); 5420 } 5421 } 5422 5423 @Override sendIntentSender(IIntentSender target, IBinder whitelistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5424 public int sendIntentSender(IIntentSender target, IBinder whitelistToken, int code, 5425 Intent intent, String resolvedType, 5426 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 5427 if (target instanceof PendingIntentRecord) { 5428 return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType, 5429 whitelistToken, finishedReceiver, requiredPermission, options); 5430 } else { 5431 if (intent == null) { 5432 // Weird case: someone has given us their own custom IIntentSender, and now 5433 // they have someone else trying to send to it but of course this isn't 5434 // really a PendingIntent, so there is no base Intent, and the caller isn't 5435 // supplying an Intent... but we never want to dispatch a null Intent to 5436 // a receiver, so um... let's make something up. 5437 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call"); 5438 intent = new Intent(Intent.ACTION_MAIN); 5439 } 5440 try { 5441 target.send(code, intent, resolvedType, whitelistToken, null, 5442 requiredPermission, options); 5443 } catch (RemoteException e) { 5444 } 5445 // Platform code can rely on getting a result back when the send is done, but if 5446 // this intent sender is from outside of the system we can't rely on it doing that. 5447 // So instead we don't give it the result receiver, and instead just directly 5448 // report the finish immediately. 5449 if (finishedReceiver != null) { 5450 try { 5451 finishedReceiver.performReceive(intent, 0, 5452 null, null, false, false, UserHandle.getCallingUserId()); 5453 } catch (RemoteException e) { 5454 } 5455 } 5456 return 0; 5457 } 5458 } 5459 5460 @Override cancelIntentSender(IIntentSender sender)5461 public void cancelIntentSender(IIntentSender sender) { 5462 mPendingIntentController.cancelIntentSender(sender); 5463 } 5464 5465 @Override getPackageForIntentSender(IIntentSender pendingResult)5466 public String getPackageForIntentSender(IIntentSender pendingResult) { 5467 if (!(pendingResult instanceof PendingIntentRecord)) { 5468 return null; 5469 } 5470 try { 5471 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5472 return res.key.packageName; 5473 } catch (ClassCastException e) { 5474 } 5475 return null; 5476 } 5477 5478 @Override registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5479 public void registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver) { 5480 mPendingIntentController.registerIntentSenderCancelListener(sender, receiver); 5481 } 5482 5483 @Override unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5484 public void unregisterIntentSenderCancelListener(IIntentSender sender, 5485 IResultReceiver receiver) { 5486 mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver); 5487 } 5488 5489 @Override getUidForIntentSender(IIntentSender sender)5490 public int getUidForIntentSender(IIntentSender sender) { 5491 if (sender instanceof PendingIntentRecord) { 5492 try { 5493 PendingIntentRecord res = (PendingIntentRecord)sender; 5494 return res.uid; 5495 } catch (ClassCastException e) { 5496 } 5497 } 5498 return -1; 5499 } 5500 5501 @Override isIntentSenderTargetedToPackage(IIntentSender pendingResult)5502 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 5503 if (!(pendingResult instanceof PendingIntentRecord)) { 5504 return false; 5505 } 5506 try { 5507 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5508 if (res.key.allIntents == null) { 5509 return false; 5510 } 5511 for (int i=0; i<res.key.allIntents.length; i++) { 5512 Intent intent = res.key.allIntents[i]; 5513 if (intent.getPackage() != null && intent.getComponent() != null) { 5514 return false; 5515 } 5516 } 5517 return true; 5518 } catch (ClassCastException e) { 5519 } 5520 return false; 5521 } 5522 5523 @Override isIntentSenderAnActivity(IIntentSender pendingResult)5524 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 5525 if (!(pendingResult instanceof PendingIntentRecord)) { 5526 return false; 5527 } 5528 try { 5529 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5530 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 5531 return true; 5532 } 5533 return false; 5534 } catch (ClassCastException e) { 5535 } 5536 return false; 5537 } 5538 5539 @Override isIntentSenderAForegroundService(IIntentSender pendingResult)5540 public boolean isIntentSenderAForegroundService(IIntentSender pendingResult) { 5541 if (pendingResult instanceof PendingIntentRecord) { 5542 final PendingIntentRecord res = (PendingIntentRecord) pendingResult; 5543 return res.key.type == ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE; 5544 } 5545 return false; 5546 } 5547 5548 @Override isIntentSenderABroadcast(IIntentSender pendingResult)5549 public boolean isIntentSenderABroadcast(IIntentSender pendingResult) { 5550 if (pendingResult instanceof PendingIntentRecord) { 5551 final PendingIntentRecord res = (PendingIntentRecord) pendingResult; 5552 return res.key.type == ActivityManager.INTENT_SENDER_BROADCAST; 5553 } 5554 return false; 5555 } 5556 5557 @Override getIntentForIntentSender(IIntentSender pendingResult)5558 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 5559 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5560 "getIntentForIntentSender()"); 5561 if (!(pendingResult instanceof PendingIntentRecord)) { 5562 return null; 5563 } 5564 try { 5565 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5566 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 5567 } catch (ClassCastException e) { 5568 } 5569 return null; 5570 } 5571 5572 @Override getTagForIntentSender(IIntentSender pendingResult, String prefix)5573 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) { 5574 if (!(pendingResult instanceof PendingIntentRecord)) { 5575 return null; 5576 } 5577 try { 5578 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5579 synchronized (this) { 5580 return getTagForIntentSenderLocked(res, prefix); 5581 } 5582 } catch (ClassCastException e) { 5583 } 5584 return null; 5585 } 5586 getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5587 String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) { 5588 final Intent intent = res.key.requestIntent; 5589 if (intent != null) { 5590 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null 5591 || res.lastTagPrefix.equals(prefix))) { 5592 return res.lastTag; 5593 } 5594 res.lastTagPrefix = prefix; 5595 final StringBuilder sb = new StringBuilder(128); 5596 if (prefix != null) { 5597 sb.append(prefix); 5598 } 5599 if (intent.getAction() != null) { 5600 sb.append(intent.getAction()); 5601 } else if (intent.getComponent() != null) { 5602 intent.getComponent().appendShortString(sb); 5603 } else { 5604 sb.append("?"); 5605 } 5606 return res.lastTag = sb.toString(); 5607 } 5608 return null; 5609 } 5610 5611 @Override setProcessLimit(int max)5612 public void setProcessLimit(int max) { 5613 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5614 "setProcessLimit()"); 5615 synchronized (this) { 5616 mConstants.setOverrideMaxCachedProcesses(max); 5617 } 5618 trimApplications(OomAdjuster.OOM_ADJ_REASON_PROCESS_END); 5619 } 5620 5621 @Override getProcessLimit()5622 public int getProcessLimit() { 5623 synchronized (this) { 5624 return mConstants.getOverrideMaxCachedProcesses(); 5625 } 5626 } 5627 importanceTokenDied(ImportanceToken token)5628 void importanceTokenDied(ImportanceToken token) { 5629 synchronized (ActivityManagerService.this) { 5630 synchronized (mPidsSelfLocked) { 5631 ImportanceToken cur 5632 = mImportantProcesses.get(token.pid); 5633 if (cur != token) { 5634 return; 5635 } 5636 mImportantProcesses.remove(token.pid); 5637 ProcessRecord pr = mPidsSelfLocked.get(token.pid); 5638 if (pr == null) { 5639 return; 5640 } 5641 pr.forcingToImportant = null; 5642 updateProcessForegroundLocked(pr, false, 0, false); 5643 } 5644 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 5645 } 5646 } 5647 5648 @Override setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5649 public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) { 5650 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5651 "setProcessImportant()"); 5652 synchronized(this) { 5653 boolean changed = false; 5654 5655 synchronized (mPidsSelfLocked) { 5656 ProcessRecord pr = mPidsSelfLocked.get(pid); 5657 if (pr == null && isForeground) { 5658 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 5659 return; 5660 } 5661 ImportanceToken oldToken = mImportantProcesses.get(pid); 5662 if (oldToken != null) { 5663 oldToken.token.unlinkToDeath(oldToken, 0); 5664 mImportantProcesses.remove(pid); 5665 if (pr != null) { 5666 pr.forcingToImportant = null; 5667 } 5668 changed = true; 5669 } 5670 if (isForeground && token != null) { 5671 ImportanceToken newToken = new ImportanceToken(pid, token, reason) { 5672 @Override 5673 public void binderDied() { 5674 importanceTokenDied(this); 5675 } 5676 }; 5677 try { 5678 token.linkToDeath(newToken, 0); 5679 mImportantProcesses.put(pid, newToken); 5680 pr.forcingToImportant = newToken; 5681 changed = true; 5682 } catch (RemoteException e) { 5683 // If the process died while doing this, we will later 5684 // do the cleanup with the process death link. 5685 } 5686 } 5687 } 5688 5689 if (changed) { 5690 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 5691 } 5692 } 5693 } 5694 isAppForeground(int uid)5695 private boolean isAppForeground(int uid) { 5696 synchronized (this) { 5697 UidRecord uidRec = mProcessList.mActiveUids.get(uid); 5698 if (uidRec == null || uidRec.idle) { 5699 return false; 5700 } 5701 return uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 5702 } 5703 } 5704 isAppBad(ApplicationInfo info)5705 private boolean isAppBad(ApplicationInfo info) { 5706 synchronized (this) { 5707 return mAppErrors.isBadProcessLocked(info); 5708 } 5709 } 5710 5711 // NOTE: this is an internal method used by the OnShellCommand implementation only and should 5712 // be guarded by permission checking. getUidState(int uid)5713 int getUidState(int uid) { 5714 synchronized (this) { 5715 return mProcessList.getUidProcStateLocked(uid); 5716 } 5717 } 5718 5719 // ========================================================= 5720 // PROCESS INFO 5721 // ========================================================= 5722 5723 static class ProcessInfoService extends IProcessInfoService.Stub { 5724 final ActivityManagerService mActivityManagerService; ProcessInfoService(ActivityManagerService activityManagerService)5725 ProcessInfoService(ActivityManagerService activityManagerService) { 5726 mActivityManagerService = activityManagerService; 5727 } 5728 5729 @Override getProcessStatesFromPids( int[] pids, int[] states)5730 public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) { 5731 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 5732 /*in*/ pids, /*out*/ states, null); 5733 } 5734 5735 @Override getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5736 public void getProcessStatesAndOomScoresFromPids( 5737 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 5738 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 5739 /*in*/ pids, /*out*/ states, /*out*/ scores); 5740 } 5741 } 5742 5743 /** 5744 * For each PID in the given input array, write the current process state 5745 * for that process into the states array, or -1 to indicate that no 5746 * process with the given PID exists. If scores array is provided, write 5747 * the oom score for the process into the scores array, with INVALID_ADJ 5748 * indicating the PID doesn't exist. 5749 */ getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5750 public void getProcessStatesAndOomScoresForPIDs( 5751 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 5752 if (scores != null) { 5753 enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE, 5754 "getProcessStatesAndOomScoresForPIDs()"); 5755 } 5756 5757 if (pids == null) { 5758 throw new NullPointerException("pids"); 5759 } else if (states == null) { 5760 throw new NullPointerException("states"); 5761 } else if (pids.length != states.length) { 5762 throw new IllegalArgumentException("pids and states arrays have different lengths!"); 5763 } else if (scores != null && pids.length != scores.length) { 5764 throw new IllegalArgumentException("pids and scores arrays have different lengths!"); 5765 } 5766 5767 synchronized (mPidsSelfLocked) { 5768 for (int i = 0; i < pids.length; i++) { 5769 ProcessRecord pr = mPidsSelfLocked.get(pids[i]); 5770 states[i] = (pr == null) ? PROCESS_STATE_NONEXISTENT : pr.getCurProcState(); 5771 if (scores != null) { 5772 scores[i] = (pr == null) ? ProcessList.INVALID_ADJ : pr.curAdj; 5773 } 5774 } 5775 } 5776 } 5777 5778 // ========================================================= 5779 // PERMISSIONS 5780 // ========================================================= 5781 5782 static class PermissionController extends IPermissionController.Stub { 5783 ActivityManagerService mActivityManagerService; PermissionController(ActivityManagerService activityManagerService)5784 PermissionController(ActivityManagerService activityManagerService) { 5785 mActivityManagerService = activityManagerService; 5786 } 5787 5788 @Override checkPermission(String permission, int pid, int uid)5789 public boolean checkPermission(String permission, int pid, int uid) { 5790 return mActivityManagerService.checkPermission(permission, pid, 5791 uid) == PackageManager.PERMISSION_GRANTED; 5792 } 5793 5794 @Override noteOp(String op, int uid, String packageName)5795 public int noteOp(String op, int uid, String packageName) { 5796 return mActivityManagerService.mAppOpsService 5797 .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName); 5798 } 5799 5800 @Override getPackagesForUid(int uid)5801 public String[] getPackagesForUid(int uid) { 5802 return mActivityManagerService.mContext.getPackageManager() 5803 .getPackagesForUid(uid); 5804 } 5805 5806 @Override isRuntimePermission(String permission)5807 public boolean isRuntimePermission(String permission) { 5808 try { 5809 PermissionInfo info = mActivityManagerService.mContext.getPackageManager() 5810 .getPermissionInfo(permission, 0); 5811 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 5812 == PermissionInfo.PROTECTION_DANGEROUS; 5813 } catch (NameNotFoundException nnfe) { 5814 Slog.e(TAG, "No such permission: "+ permission, nnfe); 5815 } 5816 return false; 5817 } 5818 5819 @Override getPackageUid(String packageName, int flags)5820 public int getPackageUid(String packageName, int flags) { 5821 try { 5822 return mActivityManagerService.mContext.getPackageManager() 5823 .getPackageUid(packageName, flags); 5824 } catch (NameNotFoundException nnfe) { 5825 return -1; 5826 } 5827 } 5828 } 5829 5830 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 5831 @Override checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5832 public int checkComponentPermission(String permission, int pid, int uid, 5833 int owningUid, boolean exported) { 5834 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 5835 owningUid, exported); 5836 } 5837 5838 @Override getAMSLock()5839 public Object getAMSLock() { 5840 return ActivityManagerService.this; 5841 } 5842 } 5843 checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5844 public static int checkComponentPermission(String permission, int pid, int uid, 5845 int owningUid, boolean exported) { 5846 if (pid == MY_PID) { 5847 return PackageManager.PERMISSION_GRANTED; 5848 } 5849 return ActivityManager.checkComponentPermission(permission, uid, 5850 owningUid, exported); 5851 } 5852 5853 /** 5854 * As the only public entry point for permissions checking, this method 5855 * can enforce the semantic that requesting a check on a null global 5856 * permission is automatically denied. (Internally a null permission 5857 * string is used when calling {@link #checkComponentPermission} in cases 5858 * when only uid-based security is needed.) 5859 * 5860 * This can be called with or without the global lock held. 5861 */ 5862 @Override checkPermission(String permission, int pid, int uid)5863 public int checkPermission(String permission, int pid, int uid) { 5864 if (permission == null) { 5865 return PackageManager.PERMISSION_DENIED; 5866 } 5867 return checkComponentPermission(permission, pid, uid, -1, true); 5868 } 5869 5870 @Override checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken)5871 public int checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken) { 5872 if (permission == null) { 5873 return PackageManager.PERMISSION_DENIED; 5874 } 5875 5876 // We might be performing an operation on behalf of an indirect binder 5877 // invocation, e.g. via {@link #openContentUri}. Check and adjust the 5878 // client identity accordingly before proceeding. 5879 Identity tlsIdentity = sCallerIdentity.get(); 5880 if (tlsIdentity != null && tlsIdentity.token == callerToken) { 5881 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {" 5882 + tlsIdentity.pid + "," + tlsIdentity.uid + "}"); 5883 uid = tlsIdentity.uid; 5884 pid = tlsIdentity.pid; 5885 } 5886 5887 return checkComponentPermission(permission, pid, uid, -1, true); 5888 } 5889 5890 /** 5891 * Binder IPC calls go through the public entry point. 5892 * This can be called with or without the global lock held. 5893 */ checkCallingPermission(String permission)5894 int checkCallingPermission(String permission) { 5895 return checkPermission(permission, 5896 Binder.getCallingPid(), 5897 Binder.getCallingUid()); 5898 } 5899 5900 /** 5901 * This can be called with or without the global lock held. 5902 */ enforceCallingPermission(String permission, String func)5903 void enforceCallingPermission(String permission, String func) { 5904 if (checkCallingPermission(permission) 5905 == PackageManager.PERMISSION_GRANTED) { 5906 return; 5907 } 5908 5909 String msg = "Permission Denial: " + func + " from pid=" 5910 + Binder.getCallingPid() 5911 + ", uid=" + Binder.getCallingUid() 5912 + " requires " + permission; 5913 Slog.w(TAG, msg); 5914 throw new SecurityException(msg); 5915 } 5916 5917 /** 5918 * This can be called with or without the global lock held. 5919 */ enforcePermission(String permission, int pid, int uid, String func)5920 void enforcePermission(String permission, int pid, int uid, String func) { 5921 if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) { 5922 return; 5923 } 5924 5925 String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid 5926 + " requires " + permission; 5927 Slog.w(TAG, msg); 5928 throw new SecurityException(msg); 5929 } 5930 isAppStartModeDisabled(int uid, String packageName)5931 public boolean isAppStartModeDisabled(int uid, String packageName) { 5932 synchronized (this) { 5933 return getAppStartModeLocked(uid, packageName, 0, -1, false, true, false) 5934 == ActivityManager.APP_START_MODE_DISABLED; 5935 } 5936 } 5937 5938 // Unified app-op and target sdk check appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk)5939 int appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) { 5940 // Apps that target O+ are always subject to background check 5941 if (packageTargetSdk >= Build.VERSION_CODES.O) { 5942 if (DEBUG_BACKGROUND_CHECK) { 5943 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted"); 5944 } 5945 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 5946 } 5947 // ...and legacy apps get an AppOp check 5948 int appop = mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND, 5949 uid, packageName); 5950 if (DEBUG_BACKGROUND_CHECK) { 5951 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop); 5952 } 5953 switch (appop) { 5954 case AppOpsManager.MODE_ALLOWED: 5955 // If force-background-check is enabled, restrict all apps that aren't whitelisted. 5956 if (mForceBackgroundCheck && 5957 !UserHandle.isCore(uid) && 5958 !isOnDeviceIdleWhitelistLocked(uid, /*allowExceptIdleToo=*/ true)) { 5959 if (DEBUG_BACKGROUND_CHECK) { 5960 Slog.i(TAG, "Force background check: " + 5961 uid + "/" + packageName + " restricted"); 5962 } 5963 return ActivityManager.APP_START_MODE_DELAYED; 5964 } 5965 return ActivityManager.APP_START_MODE_NORMAL; 5966 case AppOpsManager.MODE_IGNORED: 5967 return ActivityManager.APP_START_MODE_DELAYED; 5968 default: 5969 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 5970 } 5971 } 5972 5973 // Service launch is available to apps with run-in-background exemptions but 5974 // some other background operations are not. If we're doing a check 5975 // of service-launch policy, allow those callers to proceed unrestricted. appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk)5976 int appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) { 5977 // Persistent app? 5978 if (mPackageManagerInt.isPackagePersistent(packageName)) { 5979 if (DEBUG_BACKGROUND_CHECK) { 5980 Slog.i(TAG, "App " + uid + "/" + packageName 5981 + " is persistent; not restricted in background"); 5982 } 5983 return ActivityManager.APP_START_MODE_NORMAL; 5984 } 5985 5986 // Non-persistent but background whitelisted? 5987 if (uidOnBackgroundWhitelist(uid)) { 5988 if (DEBUG_BACKGROUND_CHECK) { 5989 Slog.i(TAG, "App " + uid + "/" + packageName 5990 + " on background whitelist; not restricted in background"); 5991 } 5992 return ActivityManager.APP_START_MODE_NORMAL; 5993 } 5994 5995 // Is this app on the battery whitelist? 5996 if (isOnDeviceIdleWhitelistLocked(uid, /*allowExceptIdleToo=*/ false)) { 5997 if (DEBUG_BACKGROUND_CHECK) { 5998 Slog.i(TAG, "App " + uid + "/" + packageName 5999 + " on idle whitelist; not restricted in background"); 6000 } 6001 return ActivityManager.APP_START_MODE_NORMAL; 6002 } 6003 6004 // None of the service-policy criteria apply, so we apply the common criteria 6005 return appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk); 6006 } 6007 getAppStartModeLocked(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6008 int getAppStartModeLocked(int uid, String packageName, int packageTargetSdk, 6009 int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) { 6010 UidRecord uidRec = mProcessList.getUidRecordLocked(uid); 6011 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg=" 6012 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle=" 6013 + (uidRec != null ? uidRec.idle : false)); 6014 if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.idle) { 6015 boolean ephemeral; 6016 if (uidRec == null) { 6017 ephemeral = getPackageManagerInternalLocked().isPackageEphemeral( 6018 UserHandle.getUserId(uid), packageName); 6019 } else { 6020 ephemeral = uidRec.ephemeral; 6021 } 6022 6023 if (ephemeral) { 6024 // We are hard-core about ephemeral apps not running in the background. 6025 return ActivityManager.APP_START_MODE_DISABLED; 6026 } else { 6027 if (disabledOnly) { 6028 // The caller is only interested in whether app starts are completely 6029 // disabled for the given package (that is, it is an instant app). So 6030 // we don't need to go further, which is all just seeing if we should 6031 // apply a "delayed" mode for a regular app. 6032 return ActivityManager.APP_START_MODE_NORMAL; 6033 } 6034 final int startMode = (alwaysRestrict) 6035 ? appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk) 6036 : appServicesRestrictedInBackgroundLocked(uid, packageName, 6037 packageTargetSdk); 6038 if (DEBUG_BACKGROUND_CHECK) { 6039 Slog.d(TAG, "checkAllowBackground: uid=" + uid 6040 + " pkg=" + packageName + " startMode=" + startMode 6041 + " onwhitelist=" + isOnDeviceIdleWhitelistLocked(uid, false) 6042 + " onwhitelist(ei)=" + isOnDeviceIdleWhitelistLocked(uid, true)); 6043 } 6044 if (startMode == ActivityManager.APP_START_MODE_DELAYED) { 6045 // This is an old app that has been forced into a "compatible as possible" 6046 // mode of background check. To increase compatibility, we will allow other 6047 // foreground apps to cause its services to start. 6048 if (callingPid >= 0) { 6049 ProcessRecord proc; 6050 synchronized (mPidsSelfLocked) { 6051 proc = mPidsSelfLocked.get(callingPid); 6052 } 6053 if (proc != null && 6054 !ActivityManager.isProcStateBackground(proc.getCurProcState())) { 6055 // Whoever is instigating this is in the foreground, so we will allow it 6056 // to go through. 6057 return ActivityManager.APP_START_MODE_NORMAL; 6058 } 6059 } 6060 } 6061 return startMode; 6062 } 6063 } 6064 return ActivityManager.APP_START_MODE_NORMAL; 6065 } 6066 6067 /** 6068 * @return whether a UID is in the system, user or temp doze whitelist. 6069 */ isOnDeviceIdleWhitelistLocked(int uid, boolean allowExceptIdleToo)6070 boolean isOnDeviceIdleWhitelistLocked(int uid, boolean allowExceptIdleToo) { 6071 final int appId = UserHandle.getAppId(uid); 6072 6073 final int[] whitelist = allowExceptIdleToo 6074 ? mDeviceIdleExceptIdleWhitelist 6075 : mDeviceIdleWhitelist; 6076 6077 return Arrays.binarySearch(whitelist, appId) >= 0 6078 || Arrays.binarySearch(mDeviceIdleTempWhitelist, appId) >= 0 6079 || mPendingTempWhitelist.indexOfKey(uid) >= 0; 6080 } 6081 6082 /** 6083 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on 6084 * the whitelist 6085 */ getPendingTempWhitelistTagForUidLocked(int uid)6086 String getPendingTempWhitelistTagForUidLocked(int uid) { 6087 final PendingTempWhitelist ptw = mPendingTempWhitelist.get(uid); 6088 return ptw != null ? ptw.tag : null; 6089 } 6090 getProviderInfoLocked(String authority, int userHandle, int pmFlags)6091 private ProviderInfo getProviderInfoLocked(String authority, int userHandle, int pmFlags) { 6092 ProviderInfo pi = null; 6093 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle); 6094 if (cpr != null) { 6095 pi = cpr.info; 6096 } else { 6097 try { 6098 pi = AppGlobals.getPackageManager().resolveContentProvider( 6099 authority, PackageManager.GET_URI_PERMISSION_PATTERNS | pmFlags, 6100 userHandle); 6101 } catch (RemoteException ex) { 6102 } 6103 } 6104 return pi; 6105 } 6106 6107 @VisibleForTesting grantEphemeralAccessLocked(int userId, Intent intent, int targetAppId, int ephemeralAppId)6108 public void grantEphemeralAccessLocked(int userId, Intent intent, 6109 int targetAppId, int ephemeralAppId) { 6110 getPackageManagerInternalLocked(). 6111 grantEphemeralAccess(userId, intent, targetAppId, ephemeralAppId); 6112 } 6113 6114 /** 6115 * @param uri This uri must NOT contain an embedded userId. 6116 * @param userId The userId in which the uri is to be resolved. 6117 */ 6118 @Override checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6119 public int checkUriPermission(Uri uri, int pid, int uid, 6120 final int modeFlags, int userId, IBinder callerToken) { 6121 enforceNotIsolatedCaller("checkUriPermission"); 6122 6123 // Another redirected-binder-call permissions check as in 6124 // {@link checkPermissionWithToken}. 6125 Identity tlsIdentity = sCallerIdentity.get(); 6126 if (tlsIdentity != null && tlsIdentity.token == callerToken) { 6127 uid = tlsIdentity.uid; 6128 pid = tlsIdentity.pid; 6129 } 6130 6131 // Our own process gets to do everything. 6132 if (pid == MY_PID) { 6133 return PackageManager.PERMISSION_GRANTED; 6134 } 6135 return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, false), uid, modeFlags) 6136 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED; 6137 } 6138 6139 /** 6140 * @param uri This uri must NOT contain an embedded userId. 6141 * @param userId The userId in which the uri is to be resolved. 6142 */ 6143 @Override grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6144 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 6145 final int modeFlags, int userId) { 6146 enforceNotIsolatedCaller("grantUriPermission"); 6147 GrantUri grantUri = new GrantUri(userId, uri, false); 6148 synchronized(this) { 6149 final ProcessRecord r = getRecordForAppLocked(caller); 6150 if (r == null) { 6151 throw new SecurityException("Unable to find app for caller " 6152 + caller 6153 + " when granting permission to uri " + grantUri); 6154 } 6155 if (targetPkg == null) { 6156 throw new IllegalArgumentException("null target"); 6157 } 6158 if (grantUri == null) { 6159 throw new IllegalArgumentException("null uri"); 6160 } 6161 6162 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 6163 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 6164 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 6165 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 6166 6167 mUgmInternal.grantUriPermission(r.uid, targetPkg, grantUri, modeFlags, null, 6168 UserHandle.getUserId(r.uid)); 6169 } 6170 } 6171 6172 /** 6173 * @param uri This uri must NOT contain an embedded userId. 6174 * @param userId The userId in which the uri is to be resolved. 6175 */ 6176 @Override revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6177 public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, 6178 final int modeFlags, int userId) { 6179 enforceNotIsolatedCaller("revokeUriPermission"); 6180 synchronized(this) { 6181 final ProcessRecord r = getRecordForAppLocked(caller); 6182 if (r == null) { 6183 throw new SecurityException("Unable to find app for caller " 6184 + caller 6185 + " when revoking permission to uri " + uri); 6186 } 6187 if (uri == null) { 6188 Slog.w(TAG, "revokeUriPermission: null uri"); 6189 return; 6190 } 6191 6192 if (!Intent.isAccessUriMode(modeFlags)) { 6193 return; 6194 } 6195 6196 final String authority = uri.getAuthority(); 6197 final ProviderInfo pi = getProviderInfoLocked(authority, userId, 6198 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 6199 if (pi == null) { 6200 Slog.w(TAG, "No content provider found for permission revoke: " 6201 + uri.toSafeString()); 6202 return; 6203 } 6204 6205 mUgmInternal.revokeUriPermission(targetPackage, r.uid, new GrantUri(userId, uri, false), 6206 modeFlags); 6207 } 6208 } 6209 6210 @Override showWaitingForDebugger(IApplicationThread who, boolean waiting)6211 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 6212 synchronized (this) { 6213 ProcessRecord app = 6214 who != null ? getRecordForAppLocked(who) : null; 6215 if (app == null) return; 6216 6217 Message msg = Message.obtain(); 6218 msg.what = WAIT_FOR_DEBUGGER_UI_MSG; 6219 msg.obj = app; 6220 msg.arg1 = waiting ? 1 : 0; 6221 mUiHandler.sendMessage(msg); 6222 } 6223 } 6224 6225 @Override getMemoryInfo(ActivityManager.MemoryInfo outInfo)6226 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 6227 mProcessList.getMemoryInfo(outInfo); 6228 } 6229 6230 // ========================================================= 6231 // TASK MANAGEMENT 6232 // ========================================================= 6233 6234 @Override getTasks(int maxNum)6235 public List<RunningTaskInfo> getTasks(int maxNum) { 6236 return mActivityTaskManager.getTasks(maxNum); 6237 } 6238 6239 @Override getFilteredTasks(int maxNum, @ActivityType int ignoreActivityType, @WindowingMode int ignoreWindowingMode)6240 public List<RunningTaskInfo> getFilteredTasks(int maxNum, @ActivityType int ignoreActivityType, 6241 @WindowingMode int ignoreWindowingMode) { 6242 return mActivityTaskManager.getFilteredTasks( 6243 maxNum, ignoreActivityType, ignoreWindowingMode); 6244 } 6245 6246 @Override cancelTaskWindowTransition(int taskId)6247 public void cancelTaskWindowTransition(int taskId) { 6248 mActivityTaskManager.cancelTaskWindowTransition(taskId); 6249 } 6250 6251 @Override setTaskResizeable(int taskId, int resizeableMode)6252 public void setTaskResizeable(int taskId, int resizeableMode) { 6253 mActivityTaskManager.setTaskResizeable(taskId, resizeableMode); 6254 } 6255 6256 @Override getTaskSnapshot(int taskId, boolean reducedResolution)6257 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) { 6258 return mActivityTaskManager.getTaskSnapshot(taskId, reducedResolution); 6259 } 6260 6261 @Override resizeTask(int taskId, Rect bounds, int resizeMode)6262 public void resizeTask(int taskId, Rect bounds, int resizeMode) { 6263 mActivityTaskManager.resizeTask(taskId, bounds, resizeMode); 6264 } 6265 6266 @Override getTaskBounds(int taskId)6267 public Rect getTaskBounds(int taskId) { 6268 return mActivityTaskManager.getTaskBounds(taskId); 6269 } 6270 6271 @Override removeStack(int stackId)6272 public void removeStack(int stackId) { 6273 mActivityTaskManager.removeStack(stackId); 6274 } 6275 6276 @Override removeTask(int taskId)6277 public boolean removeTask(int taskId) { 6278 return mActivityTaskManager.removeTask(taskId); 6279 } 6280 6281 @Override moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6282 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, 6283 int flags, Bundle bOptions) { 6284 mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions); 6285 } 6286 6287 /** 6288 * Attempts to move a task backwards in z-order (the order of activities within the task is 6289 * unchanged). 6290 * 6291 * There are several possible results of this call: 6292 * - if the task is locked, then we will show the lock toast 6293 * - if there is a task behind the provided task, then that task is made visible and resumed as 6294 * this task is moved to the back 6295 * - otherwise, if there are no other tasks in the stack: 6296 * - if this task is in the pinned stack, then we remove the stack completely, which will 6297 * have the effect of moving the task to the top or bottom of the fullscreen stack 6298 * (depending on whether it is visible) 6299 * - otherwise, we simply return home and hide this task 6300 * 6301 * @param token A reference to the activity we wish to move 6302 * @param nonRoot If false then this only works if the activity is the root 6303 * of a task; if true it will work for any activity in a task. 6304 * @return Returns true if the move completed, false if not. 6305 */ 6306 @Override moveActivityTaskToBack(IBinder token, boolean nonRoot)6307 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 6308 return mActivityTaskManager.moveActivityTaskToBack(token, nonRoot); 6309 } 6310 6311 @Override moveTaskToStack(int taskId, int stackId, boolean toTop)6312 public void moveTaskToStack(int taskId, int stackId, boolean toTop) { 6313 mActivityTaskManager.moveTaskToStack(taskId, stackId, toTop); 6314 } 6315 6316 @Override resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode, boolean preserveWindows, boolean animate, int animationDuration)6317 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode, 6318 boolean preserveWindows, boolean animate, int animationDuration) { 6319 mActivityTaskManager.resizeStack(stackId, destBounds, allowResizeInDockedMode, 6320 preserveWindows, animate, animationDuration); 6321 } 6322 6323 @Override getRecentTasks(int maxNum, int flags, int userId)6324 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, 6325 int userId) { 6326 return mActivityTaskManager.getRecentTasks(maxNum, flags, userId); 6327 } 6328 6329 /** 6330 * Moves the top activity in the input stackId to the pinned stack. 6331 * 6332 * @param stackId Id of stack to move the top activity to pinned stack. 6333 * @param bounds Bounds to use for pinned stack. 6334 * 6335 * @return True if the top activity of the input stack was successfully moved to the pinned 6336 * stack. 6337 */ 6338 @Override moveTopActivityToPinnedStack(int stackId, Rect bounds)6339 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) { 6340 return mActivityTaskManager.moveTopActivityToPinnedStack(stackId, bounds); 6341 } 6342 6343 @Override resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds, Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds)6344 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds, 6345 Rect tempDockedTaskInsetBounds, 6346 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) { 6347 mActivityTaskManager.resizeDockedStack(dockedBounds, tempDockedTaskBounds, 6348 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds); 6349 } 6350 6351 @Override positionTaskInStack(int taskId, int stackId, int position)6352 public void positionTaskInStack(int taskId, int stackId, int position) { 6353 mActivityTaskManager.positionTaskInStack(taskId, stackId, position); 6354 } 6355 6356 @Override getAllStackInfos()6357 public List<StackInfo> getAllStackInfos() { 6358 return mActivityTaskManager.getAllStackInfos(); 6359 } 6360 6361 @Override getTaskForActivity(IBinder token, boolean onlyRoot)6362 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 6363 return mActivityTaskManager.getTaskForActivity(token, onlyRoot); 6364 } 6365 6366 @Override updateDeviceOwner(String packageName)6367 public void updateDeviceOwner(String packageName) { 6368 final int callingUid = Binder.getCallingUid(); 6369 if (callingUid != 0 && callingUid != SYSTEM_UID) { 6370 throw new SecurityException("updateDeviceOwner called from non-system process"); 6371 } 6372 synchronized (this) { 6373 mDeviceOwnerName = packageName; 6374 } 6375 } 6376 6377 @Override updateLockTaskPackages(int userId, String[] packages)6378 public void updateLockTaskPackages(int userId, String[] packages) { 6379 mActivityTaskManager.updateLockTaskPackages(userId, packages); 6380 } 6381 6382 @Override isInLockTaskMode()6383 public boolean isInLockTaskMode() { 6384 return mActivityTaskManager.isInLockTaskMode(); 6385 } 6386 6387 @Override getLockTaskModeState()6388 public int getLockTaskModeState() { 6389 return mActivityTaskManager.getLockTaskModeState(); 6390 } 6391 6392 @Override startSystemLockTaskMode(int taskId)6393 public void startSystemLockTaskMode(int taskId) throws RemoteException { 6394 mActivityTaskManager.startSystemLockTaskMode(taskId); 6395 } 6396 6397 // ========================================================= 6398 // CONTENT PROVIDERS 6399 // ========================================================= 6400 generateApplicationProvidersLocked(ProcessRecord app)6401 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) { 6402 List<ProviderInfo> providers = null; 6403 try { 6404 providers = AppGlobals.getPackageManager() 6405 .queryContentProviders(app.processName, app.uid, 6406 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS 6407 | MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null) 6408 .getList(); 6409 } catch (RemoteException ex) { 6410 } 6411 if (DEBUG_MU) Slog.v(TAG_MU, 6412 "generateApplicationProvidersLocked, app.info.uid = " + app.uid); 6413 int userId = app.userId; 6414 if (providers != null) { 6415 int N = providers.size(); 6416 app.pubProviders.ensureCapacity(N + app.pubProviders.size()); 6417 for (int i=0; i<N; i++) { 6418 // TODO: keep logic in sync with installEncryptionUnawareProviders 6419 ProviderInfo cpi = 6420 (ProviderInfo)providers.get(i); 6421 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 6422 cpi.name, cpi.flags); 6423 if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_SYSTEM) { 6424 // This is a singleton provider, but a user besides the 6425 // default user is asking to initialize a process it runs 6426 // in... well, no, it doesn't actually run in this process, 6427 // it runs in the process of the default user. Get rid of it. 6428 providers.remove(i); 6429 N--; 6430 i--; 6431 continue; 6432 } 6433 6434 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 6435 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId); 6436 if (cpr == null) { 6437 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton); 6438 mProviderMap.putProviderByClass(comp, cpr); 6439 } 6440 if (DEBUG_MU) Slog.v(TAG_MU, 6441 "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid); 6442 app.pubProviders.put(cpi.name, cpr); 6443 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) { 6444 // Don't add this if it is a platform component that is marked 6445 // to run in multiple processes, because this is actually 6446 // part of the framework so doesn't make sense to track as a 6447 // separate apk in the process. 6448 app.addPackage(cpi.applicationInfo.packageName, 6449 cpi.applicationInfo.longVersionCode, mProcessStats); 6450 } 6451 notifyPackageUse(cpi.applicationInfo.packageName, 6452 PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER); 6453 } 6454 } 6455 return providers; 6456 } 6457 6458 /** 6459 * Check if the calling UID has a possible chance at accessing the provider 6460 * at the given authority and user. 6461 */ checkContentProviderAccess(String authority, int userId)6462 public String checkContentProviderAccess(String authority, int userId) { 6463 if (userId == UserHandle.USER_ALL) { 6464 mContext.enforceCallingOrSelfPermission( 6465 Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG); 6466 userId = UserHandle.getCallingUserId(); 6467 } 6468 6469 ProviderInfo cpi = null; 6470 try { 6471 cpi = AppGlobals.getPackageManager().resolveContentProvider(authority, 6472 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS 6473 | PackageManager.MATCH_DISABLED_COMPONENTS 6474 | PackageManager.MATCH_DIRECT_BOOT_AWARE 6475 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 6476 userId); 6477 } catch (RemoteException ignored) { 6478 } 6479 if (cpi == null) { 6480 return "Failed to find provider " + authority + " for user " + userId 6481 + "; expected to find a valid ContentProvider for this authority"; 6482 } 6483 6484 ProcessRecord r = null; 6485 synchronized (mPidsSelfLocked) { 6486 r = mPidsSelfLocked.get(Binder.getCallingPid()); 6487 } 6488 if (r == null) { 6489 return "Failed to find PID " + Binder.getCallingPid(); 6490 } 6491 6492 synchronized (this) { 6493 return checkContentProviderPermissionLocked(cpi, r, userId, true); 6494 } 6495 } 6496 6497 /** 6498 * Check if {@link ProcessRecord} has a possible chance at accessing the 6499 * given {@link ProviderInfo}. Final permission checking is always done 6500 * in {@link ContentProvider}. 6501 */ checkContentProviderPermissionLocked( ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser)6502 private final String checkContentProviderPermissionLocked( 6503 ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) { 6504 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid(); 6505 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid(); 6506 boolean checkedGrants = false; 6507 if (checkUser) { 6508 // Looking for cross-user grants before enforcing the typical cross-users permissions 6509 int tmpTargetUserId = mUserController.unsafeConvertIncomingUser(userId); 6510 if (tmpTargetUserId != UserHandle.getUserId(callingUid)) { 6511 if (mUgmInternal.checkAuthorityGrants( 6512 callingUid, cpi, tmpTargetUserId, checkUser)) { 6513 return null; 6514 } 6515 checkedGrants = true; 6516 } 6517 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false, 6518 ALLOW_NON_FULL, "checkContentProviderPermissionLocked " + cpi.authority, null); 6519 if (userId != tmpTargetUserId) { 6520 // When we actually went to determine the final targer user ID, this ended 6521 // up different than our initial check for the authority. This is because 6522 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to 6523 // SELF. So we need to re-check the grants again. 6524 checkedGrants = false; 6525 } 6526 } 6527 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid, 6528 cpi.applicationInfo.uid, cpi.exported) 6529 == PackageManager.PERMISSION_GRANTED) { 6530 return null; 6531 } 6532 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid, 6533 cpi.applicationInfo.uid, cpi.exported) 6534 == PackageManager.PERMISSION_GRANTED) { 6535 return null; 6536 } 6537 6538 PathPermission[] pps = cpi.pathPermissions; 6539 if (pps != null) { 6540 int i = pps.length; 6541 while (i > 0) { 6542 i--; 6543 PathPermission pp = pps[i]; 6544 String pprperm = pp.getReadPermission(); 6545 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid, 6546 cpi.applicationInfo.uid, cpi.exported) 6547 == PackageManager.PERMISSION_GRANTED) { 6548 return null; 6549 } 6550 String ppwperm = pp.getWritePermission(); 6551 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid, 6552 cpi.applicationInfo.uid, cpi.exported) 6553 == PackageManager.PERMISSION_GRANTED) { 6554 return null; 6555 } 6556 } 6557 } 6558 if (!checkedGrants 6559 && mUgmInternal.checkAuthorityGrants(callingUid, cpi, userId, checkUser)) { 6560 return null; 6561 } 6562 6563 final String suffix; 6564 if (!cpi.exported) { 6565 suffix = " that is not exported from UID " + cpi.applicationInfo.uid; 6566 } else if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(cpi.readPermission)) { 6567 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs"; 6568 } else { 6569 suffix = " requires " + cpi.readPermission + " or " + cpi.writePermission; 6570 } 6571 final String msg = "Permission Denial: opening provider " + cpi.name 6572 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 6573 + ", uid=" + callingUid + ")" + suffix; 6574 Slog.w(TAG, msg); 6575 return msg; 6576 } 6577 incProviderCountLocked(ProcessRecord r, final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid, String callingPackage, String callingTag, boolean stable)6578 ContentProviderConnection incProviderCountLocked(ProcessRecord r, 6579 final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid, 6580 String callingPackage, String callingTag, boolean stable) { 6581 if (r != null) { 6582 for (int i=0; i<r.conProviders.size(); i++) { 6583 ContentProviderConnection conn = r.conProviders.get(i); 6584 if (conn.provider == cpr) { 6585 if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER, 6586 "Adding provider requested by " 6587 + r.processName + " from process " 6588 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 6589 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 6590 if (stable) { 6591 conn.stableCount++; 6592 conn.numStableIncs++; 6593 } else { 6594 conn.unstableCount++; 6595 conn.numUnstableIncs++; 6596 } 6597 return conn; 6598 } 6599 } 6600 ContentProviderConnection conn = new ContentProviderConnection(cpr, r, callingPackage); 6601 conn.startAssociationIfNeeded(); 6602 if (stable) { 6603 conn.stableCount = 1; 6604 conn.numStableIncs = 1; 6605 } else { 6606 conn.unstableCount = 1; 6607 conn.numUnstableIncs = 1; 6608 } 6609 cpr.connections.add(conn); 6610 r.conProviders.add(conn); 6611 startAssociationLocked(r.uid, r.processName, r.getCurProcState(), 6612 cpr.uid, cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName); 6613 return conn; 6614 } 6615 cpr.addExternalProcessHandleLocked(externalProcessToken, callingUid, callingTag); 6616 return null; 6617 } 6618 decProviderCountLocked(ContentProviderConnection conn, ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable)6619 boolean decProviderCountLocked(ContentProviderConnection conn, 6620 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 6621 if (conn != null) { 6622 cpr = conn.provider; 6623 if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER, 6624 "Removing provider requested by " 6625 + conn.client.processName + " from process " 6626 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 6627 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 6628 if (stable) { 6629 conn.stableCount--; 6630 } else { 6631 conn.unstableCount--; 6632 } 6633 if (conn.stableCount == 0 && conn.unstableCount == 0) { 6634 conn.stopAssociation(); 6635 cpr.connections.remove(conn); 6636 conn.client.conProviders.remove(conn); 6637 if (conn.client.setProcState < PROCESS_STATE_LAST_ACTIVITY) { 6638 // The client is more important than last activity -- note the time this 6639 // is happening, so we keep the old provider process around a bit as last 6640 // activity to avoid thrashing it. 6641 if (cpr.proc != null) { 6642 cpr.proc.lastProviderTime = SystemClock.uptimeMillis(); 6643 } 6644 } 6645 stopAssociationLocked(conn.client.uid, conn.client.processName, cpr.uid, 6646 cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName); 6647 return true; 6648 } 6649 return false; 6650 } 6651 cpr.removeExternalProcessHandleLocked(externalProcessToken); 6652 return false; 6653 } 6654 checkTime(long startTime, String where)6655 void checkTime(long startTime, String where) { 6656 long now = SystemClock.uptimeMillis(); 6657 if ((now-startTime) > 50) { 6658 // If we are taking more than 50ms, log about it. 6659 Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where); 6660 } 6661 } 6662 6663 private static final int[] PROCESS_STATE_STATS_FORMAT = new int[] { 6664 PROC_SPACE_TERM, 6665 PROC_SPACE_TERM|PROC_PARENS, 6666 PROC_SPACE_TERM|PROC_CHAR|PROC_OUT_LONG, // 3: process state 6667 }; 6668 6669 private final long[] mProcessStateStatsLongs = new long[1]; 6670 isProcessAliveLocked(ProcessRecord proc)6671 private boolean isProcessAliveLocked(ProcessRecord proc) { 6672 if (proc.pid <= 0) { 6673 if (DEBUG_OOM_ADJ) Slog.d(TAG, "Process hasn't started yet: " + proc); 6674 return false; 6675 } 6676 if (proc.procStatFile == null) { 6677 proc.procStatFile = "/proc/" + proc.pid + "/stat"; 6678 } 6679 mProcessStateStatsLongs[0] = 0; 6680 if (!readProcFile(proc.procStatFile, PROCESS_STATE_STATS_FORMAT, null, 6681 mProcessStateStatsLongs, null)) { 6682 if (DEBUG_OOM_ADJ) Slog.d(TAG, "UNABLE TO RETRIEVE STATE FOR " + proc.procStatFile); 6683 return false; 6684 } 6685 final long state = mProcessStateStatsLongs[0]; 6686 if (DEBUG_OOM_ADJ) Slog.d(TAG, "RETRIEVED STATE FOR " + proc.procStatFile + ": " 6687 + (char)state); 6688 return state != 'Z' && state != 'X' && state != 'x' && state != 'K'; 6689 } 6690 checkContentProviderAssociation(ProcessRecord callingApp, int callingUid, ProviderInfo cpi)6691 private String checkContentProviderAssociation(ProcessRecord callingApp, int callingUid, 6692 ProviderInfo cpi) { 6693 if (callingApp == null) { 6694 return validateAssociationAllowedLocked(cpi.packageName, cpi.applicationInfo.uid, 6695 null, callingUid) ? null : "<null>"; 6696 } 6697 for (int i = callingApp.pkgList.size() - 1; i >= 0; i--) { 6698 if (!validateAssociationAllowedLocked(callingApp.pkgList.keyAt(i), callingApp.uid, 6699 cpi.packageName, cpi.applicationInfo.uid)) { 6700 return cpi.packageName; 6701 } 6702 } 6703 return null; 6704 } 6705 getContentProviderImpl(IApplicationThread caller, String name, IBinder token, int callingUid, String callingPackage, String callingTag, boolean stable, int userId)6706 private ContentProviderHolder getContentProviderImpl(IApplicationThread caller, 6707 String name, IBinder token, int callingUid, String callingPackage, String callingTag, 6708 boolean stable, int userId) { 6709 ContentProviderRecord cpr; 6710 ContentProviderConnection conn = null; 6711 ProviderInfo cpi = null; 6712 boolean providerRunning = false; 6713 6714 synchronized(this) { 6715 long startTime = SystemClock.uptimeMillis(); 6716 6717 ProcessRecord r = null; 6718 if (caller != null) { 6719 r = getRecordForAppLocked(caller); 6720 if (r == null) { 6721 throw new SecurityException( 6722 "Unable to find app for caller " + caller 6723 + " (pid=" + Binder.getCallingPid() 6724 + ") when getting content provider " + name); 6725 } 6726 } 6727 6728 boolean checkCrossUser = true; 6729 6730 checkTime(startTime, "getContentProviderImpl: getProviderByName"); 6731 6732 // First check if this content provider has been published... 6733 cpr = mProviderMap.getProviderByName(name, userId); 6734 // If that didn't work, check if it exists for user 0 and then 6735 // verify that it's a singleton provider before using it. 6736 if (cpr == null && userId != UserHandle.USER_SYSTEM) { 6737 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_SYSTEM); 6738 if (cpr != null) { 6739 cpi = cpr.info; 6740 if (isSingleton(cpi.processName, cpi.applicationInfo, 6741 cpi.name, cpi.flags) 6742 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) { 6743 userId = UserHandle.USER_SYSTEM; 6744 checkCrossUser = false; 6745 } else { 6746 cpr = null; 6747 cpi = null; 6748 } 6749 } 6750 } 6751 6752 if (cpr != null && cpr.proc != null) { 6753 providerRunning = !cpr.proc.killed; 6754 6755 // Note if killedByAm is also set, this means the provider process has just been 6756 // killed by AM (in ProcessRecord.kill()), but appDiedLocked() hasn't been called 6757 // yet. So we need to call appDiedLocked() here and let it clean up. 6758 // (See the commit message on I2c4ba1e87c2d47f2013befff10c49b3dc337a9a7 to see 6759 // how to test this case.) 6760 if (cpr.proc.killed && cpr.proc.killedByAm) { 6761 checkTime(startTime, "getContentProviderImpl: before appDied (killedByAm)"); 6762 final long iden = Binder.clearCallingIdentity(); 6763 try { 6764 appDiedLocked(cpr.proc); 6765 } finally { 6766 Binder.restoreCallingIdentity(iden); 6767 } 6768 checkTime(startTime, "getContentProviderImpl: after appDied (killedByAm)"); 6769 } 6770 } 6771 6772 if (providerRunning) { 6773 cpi = cpr.info; 6774 String msg; 6775 6776 if (r != null && cpr.canRunHere(r)) { 6777 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) { 6778 throw new SecurityException("Content provider lookup " 6779 + cpr.name.flattenToShortString() 6780 + " failed: association not allowed with package " + msg); 6781 } 6782 checkTime(startTime, 6783 "getContentProviderImpl: before checkContentProviderPermission"); 6784 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser)) 6785 != null) { 6786 throw new SecurityException(msg); 6787 } 6788 checkTime(startTime, 6789 "getContentProviderImpl: after checkContentProviderPermission"); 6790 6791 // This provider has been published or is in the process 6792 // of being published... but it is also allowed to run 6793 // in the caller's process, so don't make a connection 6794 // and just let the caller instantiate its own instance. 6795 ContentProviderHolder holder = cpr.newHolder(null); 6796 // don't give caller the provider object, it needs 6797 // to make its own. 6798 holder.provider = null; 6799 return holder; 6800 } 6801 6802 // Don't expose providers between normal apps and instant apps 6803 try { 6804 if (AppGlobals.getPackageManager() 6805 .resolveContentProvider(name, 0 /*flags*/, userId) == null) { 6806 return null; 6807 } 6808 } catch (RemoteException e) { 6809 } 6810 6811 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) { 6812 throw new SecurityException("Content provider lookup " 6813 + cpr.name.flattenToShortString() 6814 + " failed: association not allowed with package " + msg); 6815 } 6816 checkTime(startTime, 6817 "getContentProviderImpl: before checkContentProviderPermission"); 6818 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser)) 6819 != null) { 6820 throw new SecurityException(msg); 6821 } 6822 checkTime(startTime, 6823 "getContentProviderImpl: after checkContentProviderPermission"); 6824 6825 final long origId = Binder.clearCallingIdentity(); 6826 6827 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked"); 6828 6829 // In this case the provider instance already exists, so we can 6830 // return it right away. 6831 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag, 6832 stable); 6833 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) { 6834 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_LOW_APP_ADJ) { 6835 // If this is a perceptible app accessing the provider, 6836 // make sure to count it as being accessed and thus 6837 // back up on the LRU list. This is good because 6838 // content providers are often expensive to start. 6839 checkTime(startTime, "getContentProviderImpl: before updateLruProcess"); 6840 mProcessList.updateLruProcessLocked(cpr.proc, false, null); 6841 checkTime(startTime, "getContentProviderImpl: after updateLruProcess"); 6842 } 6843 } 6844 6845 checkTime(startTime, "getContentProviderImpl: before updateOomAdj"); 6846 final int verifiedAdj = cpr.proc.verifiedAdj; 6847 boolean success = updateOomAdjLocked(cpr.proc, true, 6848 OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER); 6849 // XXX things have changed so updateOomAdjLocked doesn't actually tell us 6850 // if the process has been successfully adjusted. So to reduce races with 6851 // it, we will check whether the process still exists. Note that this doesn't 6852 // completely get rid of races with LMK killing the process, but should make 6853 // them much smaller. 6854 if (success && verifiedAdj != cpr.proc.setAdj && !isProcessAliveLocked(cpr.proc)) { 6855 success = false; 6856 } 6857 maybeUpdateProviderUsageStatsLocked(r, cpr.info.packageName, name); 6858 checkTime(startTime, "getContentProviderImpl: after updateOomAdj"); 6859 if (DEBUG_PROVIDER) Slog.i(TAG_PROVIDER, "Adjust success: " + success); 6860 // NOTE: there is still a race here where a signal could be 6861 // pending on the process even though we managed to update its 6862 // adj level. Not sure what to do about this, but at least 6863 // the race is now smaller. 6864 if (!success) { 6865 // Uh oh... it looks like the provider's process 6866 // has been killed on us. We need to wait for a new 6867 // process to be started, and make sure its death 6868 // doesn't kill our process. 6869 Slog.i(TAG, "Existing provider " + cpr.name.flattenToShortString() 6870 + " is crashing; detaching " + r); 6871 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable); 6872 checkTime(startTime, "getContentProviderImpl: before appDied"); 6873 appDiedLocked(cpr.proc); 6874 checkTime(startTime, "getContentProviderImpl: after appDied"); 6875 if (!lastRef) { 6876 // This wasn't the last ref our process had on 6877 // the provider... we have now been killed, bail. 6878 return null; 6879 } 6880 providerRunning = false; 6881 conn = null; 6882 } else { 6883 cpr.proc.verifiedAdj = cpr.proc.setAdj; 6884 } 6885 6886 Binder.restoreCallingIdentity(origId); 6887 } 6888 6889 if (!providerRunning) { 6890 try { 6891 checkTime(startTime, "getContentProviderImpl: before resolveContentProvider"); 6892 cpi = AppGlobals.getPackageManager(). 6893 resolveContentProvider(name, 6894 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId); 6895 checkTime(startTime, "getContentProviderImpl: after resolveContentProvider"); 6896 } catch (RemoteException ex) { 6897 } 6898 if (cpi == null) { 6899 return null; 6900 } 6901 // If the provider is a singleton AND 6902 // (it's a call within the same user || the provider is a 6903 // privileged app) 6904 // Then allow connecting to the singleton provider 6905 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 6906 cpi.name, cpi.flags) 6907 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid); 6908 if (singleton) { 6909 userId = UserHandle.USER_SYSTEM; 6910 } 6911 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId); 6912 checkTime(startTime, "getContentProviderImpl: got app info for user"); 6913 6914 String msg; 6915 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) { 6916 throw new SecurityException("Content provider lookup " + name 6917 + " failed: association not allowed with package " + msg); 6918 } 6919 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 6920 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton)) 6921 != null) { 6922 throw new SecurityException(msg); 6923 } 6924 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 6925 6926 if (!mProcessesReady 6927 && !cpi.processName.equals("system")) { 6928 // If this content provider does not run in the system 6929 // process, and the system is not yet ready to run other 6930 // processes, then fail fast instead of hanging. 6931 throw new IllegalArgumentException( 6932 "Attempt to launch content provider before system ready"); 6933 } 6934 6935 // If system providers are not installed yet we aggressively crash to avoid 6936 // creating multiple instance of these providers and then bad things happen! 6937 if (!mSystemProvidersInstalled && cpi.applicationInfo.isSystemApp() 6938 && "system".equals(cpi.processName)) { 6939 throw new IllegalStateException("Cannot access system provider: '" 6940 + cpi.authority + "' before system providers are installed!"); 6941 } 6942 6943 // Make sure that the user who owns this provider is running. If not, 6944 // we don't want to allow it to run. 6945 if (!mUserController.isUserRunning(userId, 0)) { 6946 Slog.w(TAG, "Unable to launch app " 6947 + cpi.applicationInfo.packageName + "/" 6948 + cpi.applicationInfo.uid + " for provider " 6949 + name + ": user " + userId + " is stopped"); 6950 return null; 6951 } 6952 6953 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 6954 checkTime(startTime, "getContentProviderImpl: before getProviderByClass"); 6955 cpr = mProviderMap.getProviderByClass(comp, userId); 6956 checkTime(startTime, "getContentProviderImpl: after getProviderByClass"); 6957 final boolean firstClass = cpr == null; 6958 if (firstClass) { 6959 final long ident = Binder.clearCallingIdentity(); 6960 6961 // If permissions need a review before any of the app components can run, 6962 // we return no provider and launch a review activity if the calling app 6963 // is in the foreground. 6964 if (!requestTargetProviderPermissionsReviewIfNeededLocked(cpi, r, userId)) { 6965 return null; 6966 } 6967 6968 try { 6969 checkTime(startTime, "getContentProviderImpl: before getApplicationInfo"); 6970 ApplicationInfo ai = 6971 AppGlobals.getPackageManager(). 6972 getApplicationInfo( 6973 cpi.applicationInfo.packageName, 6974 STOCK_PM_FLAGS, userId); 6975 checkTime(startTime, "getContentProviderImpl: after getApplicationInfo"); 6976 if (ai == null) { 6977 Slog.w(TAG, "No package info for content provider " 6978 + cpi.name); 6979 return null; 6980 } 6981 ai = getAppInfoForUser(ai, userId); 6982 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton); 6983 } catch (RemoteException ex) { 6984 // pm is in same process, this will never happen. 6985 } finally { 6986 Binder.restoreCallingIdentity(ident); 6987 } 6988 } 6989 6990 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord"); 6991 6992 if (r != null && cpr.canRunHere(r)) { 6993 // If this is a multiprocess provider, then just return its 6994 // info and allow the caller to instantiate it. Only do 6995 // this if the provider is the same user as the caller's 6996 // process, or can run as root (so can be in any process). 6997 return cpr.newHolder(null); 6998 } 6999 7000 if (DEBUG_PROVIDER) Slog.w(TAG_PROVIDER, "LAUNCHING REMOTE PROVIDER (myuid " 7001 + (r != null ? r.uid : null) + " pruid " + cpr.appInfo.uid + "): " 7002 + cpr.info.name + " callers=" + Debug.getCallers(6)); 7003 7004 // This is single process, and our app is now connecting to it. 7005 // See if we are already in the process of launching this 7006 // provider. 7007 final int N = mLaunchingProviders.size(); 7008 int i; 7009 for (i = 0; i < N; i++) { 7010 if (mLaunchingProviders.get(i) == cpr) { 7011 break; 7012 } 7013 } 7014 7015 // If the provider is not already being launched, then get it 7016 // started. 7017 if (i >= N) { 7018 final long origId = Binder.clearCallingIdentity(); 7019 7020 try { 7021 // Content provider is now in use, its package can't be stopped. 7022 try { 7023 checkTime(startTime, "getContentProviderImpl: before set stopped state"); 7024 AppGlobals.getPackageManager().setPackageStoppedState( 7025 cpr.appInfo.packageName, false, userId); 7026 checkTime(startTime, "getContentProviderImpl: after set stopped state"); 7027 } catch (RemoteException e) { 7028 } catch (IllegalArgumentException e) { 7029 Slog.w(TAG, "Failed trying to unstop package " 7030 + cpr.appInfo.packageName + ": " + e); 7031 } 7032 7033 // Use existing process if already started 7034 checkTime(startTime, "getContentProviderImpl: looking for process record"); 7035 ProcessRecord proc = getProcessRecordLocked( 7036 cpi.processName, cpr.appInfo.uid, false); 7037 if (proc != null && proc.thread != null && !proc.killed) { 7038 if (DEBUG_PROVIDER) Slog.d(TAG_PROVIDER, 7039 "Installing in existing process " + proc); 7040 if (!proc.pubProviders.containsKey(cpi.name)) { 7041 checkTime(startTime, "getContentProviderImpl: scheduling install"); 7042 proc.pubProviders.put(cpi.name, cpr); 7043 try { 7044 proc.thread.scheduleInstallProvider(cpi); 7045 } catch (RemoteException e) { 7046 } 7047 } 7048 } else { 7049 checkTime(startTime, "getContentProviderImpl: before start process"); 7050 proc = startProcessLocked(cpi.processName, 7051 cpr.appInfo, false, 0, 7052 new HostingRecord("content provider", 7053 new ComponentName(cpi.applicationInfo.packageName, 7054 cpi.name)), false, false, false); 7055 checkTime(startTime, "getContentProviderImpl: after start process"); 7056 if (proc == null) { 7057 Slog.w(TAG, "Unable to launch app " 7058 + cpi.applicationInfo.packageName + "/" 7059 + cpi.applicationInfo.uid + " for provider " 7060 + name + ": process is bad"); 7061 return null; 7062 } 7063 } 7064 cpr.launchingApp = proc; 7065 mLaunchingProviders.add(cpr); 7066 } finally { 7067 Binder.restoreCallingIdentity(origId); 7068 } 7069 } 7070 7071 checkTime(startTime, "getContentProviderImpl: updating data structures"); 7072 7073 // Make sure the provider is published (the same provider class 7074 // may be published under multiple names). 7075 if (firstClass) { 7076 mProviderMap.putProviderByClass(comp, cpr); 7077 } 7078 7079 mProviderMap.putProviderByName(name, cpr); 7080 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag, 7081 stable); 7082 if (conn != null) { 7083 conn.waiting = true; 7084 } 7085 } 7086 checkTime(startTime, "getContentProviderImpl: done!"); 7087 7088 grantEphemeralAccessLocked(userId, null /*intent*/, 7089 UserHandle.getAppId(cpi.applicationInfo.uid), 7090 UserHandle.getAppId(Binder.getCallingUid())); 7091 } 7092 7093 // Wait for the provider to be published... 7094 final long timeout = SystemClock.uptimeMillis() + CONTENT_PROVIDER_WAIT_TIMEOUT; 7095 boolean timedOut = false; 7096 synchronized (cpr) { 7097 while (cpr.provider == null) { 7098 if (cpr.launchingApp == null) { 7099 Slog.w(TAG, "Unable to launch app " 7100 + cpi.applicationInfo.packageName + "/" 7101 + cpi.applicationInfo.uid + " for provider " 7102 + name + ": launching app became null"); 7103 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS, 7104 UserHandle.getUserId(cpi.applicationInfo.uid), 7105 cpi.applicationInfo.packageName, 7106 cpi.applicationInfo.uid, name); 7107 return null; 7108 } 7109 try { 7110 final long wait = Math.max(0L, timeout - SystemClock.uptimeMillis()); 7111 if (DEBUG_MU) Slog.v(TAG_MU, 7112 "Waiting to start provider " + cpr 7113 + " launchingApp=" + cpr.launchingApp + " for " + wait + " ms"); 7114 if (conn != null) { 7115 conn.waiting = true; 7116 } 7117 cpr.wait(wait); 7118 if (cpr.provider == null) { 7119 timedOut = true; 7120 break; 7121 } 7122 } catch (InterruptedException ex) { 7123 } finally { 7124 if (conn != null) { 7125 conn.waiting = false; 7126 } 7127 } 7128 } 7129 } 7130 if (timedOut) { 7131 // Note we do it afer releasing the lock. 7132 String callerName = "unknown"; 7133 synchronized (this) { 7134 final ProcessRecord record = mProcessList.getLRURecordForAppLocked(caller); 7135 if (record != null) { 7136 callerName = record.processName; 7137 } 7138 } 7139 7140 Slog.wtf(TAG, "Timeout waiting for provider " 7141 + cpi.applicationInfo.packageName + "/" 7142 + cpi.applicationInfo.uid + " for provider " 7143 + name 7144 + " providerRunning=" + providerRunning 7145 + " caller=" + callerName + "/" + Binder.getCallingUid()); 7146 return null; 7147 } 7148 7149 return cpr.newHolder(conn); 7150 } 7151 7152 private static final class StartActivityRunnable implements Runnable { 7153 private final Context mContext; 7154 private final Intent mIntent; 7155 private final UserHandle mUserHandle; 7156 StartActivityRunnable(Context context, Intent intent, UserHandle userHandle)7157 StartActivityRunnable(Context context, Intent intent, UserHandle userHandle) { 7158 this.mContext = context; 7159 this.mIntent = intent; 7160 this.mUserHandle = userHandle; 7161 } 7162 7163 @Override run()7164 public void run() { 7165 mContext.startActivityAsUser(mIntent, mUserHandle); 7166 } 7167 } 7168 requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi, ProcessRecord r, final int userId)7169 private boolean requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi, 7170 ProcessRecord r, final int userId) { 7171 if (getPackageManagerInternalLocked().isPermissionsReviewRequired( 7172 cpi.packageName, userId)) { 7173 7174 final boolean callerForeground = r == null || r.setSchedGroup 7175 != ProcessList.SCHED_GROUP_BACKGROUND; 7176 7177 // Show a permission review UI only for starting from a foreground app 7178 if (!callerForeground) { 7179 Slog.w(TAG, "u" + userId + " Instantiating a provider in package" 7180 + cpi.packageName + " requires a permissions review"); 7181 return false; 7182 } 7183 7184 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); 7185 intent.addFlags(FLAG_ACTIVITY_NEW_TASK 7186 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 7187 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, cpi.packageName); 7188 7189 if (DEBUG_PERMISSIONS_REVIEW) { 7190 Slog.i(TAG, "u" + userId + " Launching permission review " 7191 + "for package " + cpi.packageName); 7192 } 7193 7194 final UserHandle userHandle = new UserHandle(userId); 7195 mHandler.post(new StartActivityRunnable(mContext, intent, userHandle)); 7196 7197 return false; 7198 } 7199 7200 return true; 7201 } 7202 7203 /** 7204 * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The 7205 * PackageManager could be unavailable at construction time and therefore needs to be accessed 7206 * on demand. 7207 */ 7208 @VisibleForTesting getPackageManager()7209 public IPackageManager getPackageManager() { 7210 return AppGlobals.getPackageManager(); 7211 } 7212 7213 @VisibleForTesting getPackageManagerInternalLocked()7214 public PackageManagerInternal getPackageManagerInternalLocked() { 7215 if (mPackageManagerInt == null) { 7216 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class); 7217 } 7218 return mPackageManagerInt; 7219 } 7220 7221 @Override getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)7222 public final ContentProviderHolder getContentProvider( 7223 IApplicationThread caller, String callingPackage, String name, int userId, 7224 boolean stable) { 7225 enforceNotIsolatedCaller("getContentProvider"); 7226 if (caller == null) { 7227 String msg = "null IApplicationThread when getting content provider " 7228 + name; 7229 Slog.w(TAG, msg); 7230 throw new SecurityException(msg); 7231 } 7232 // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal 7233 // with cross-user grant. 7234 final int callingUid = Binder.getCallingUid(); 7235 if (callingPackage != null && mAppOpsService.checkPackage(callingUid, callingPackage) 7236 != AppOpsManager.MODE_ALLOWED) { 7237 throw new SecurityException("Given calling package " + callingPackage 7238 + " does not match caller's uid " + callingUid); 7239 } 7240 return getContentProviderImpl(caller, name, null, callingUid, callingPackage, 7241 null, stable, userId); 7242 } 7243 getContentProviderExternal( String name, int userId, IBinder token, String tag)7244 public ContentProviderHolder getContentProviderExternal( 7245 String name, int userId, IBinder token, String tag) { 7246 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 7247 "Do not have permission in call getContentProviderExternal()"); 7248 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 7249 userId, false, ALLOW_FULL_ONLY, "getContentProvider", null); 7250 return getContentProviderExternalUnchecked(name, token, Binder.getCallingUid(), 7251 tag != null ? tag : "*external*", userId); 7252 } 7253 getContentProviderExternalUnchecked(String name, IBinder token, int callingUid, String callingTag, int userId)7254 private ContentProviderHolder getContentProviderExternalUnchecked(String name, 7255 IBinder token, int callingUid, String callingTag, int userId) { 7256 return getContentProviderImpl(null, name, token, callingUid, null, callingTag, 7257 true, userId); 7258 } 7259 7260 /** 7261 * Drop a content provider from a ProcessRecord's bookkeeping 7262 */ removeContentProvider(IBinder connection, boolean stable)7263 public void removeContentProvider(IBinder connection, boolean stable) { 7264 enforceNotIsolatedCaller("removeContentProvider"); 7265 long ident = Binder.clearCallingIdentity(); 7266 try { 7267 synchronized (this) { 7268 ContentProviderConnection conn; 7269 try { 7270 conn = (ContentProviderConnection)connection; 7271 } catch (ClassCastException e) { 7272 String msg ="removeContentProvider: " + connection 7273 + " not a ContentProviderConnection"; 7274 Slog.w(TAG, msg); 7275 throw new IllegalArgumentException(msg); 7276 } 7277 if (conn == null) { 7278 throw new NullPointerException("connection is null"); 7279 } 7280 if (decProviderCountLocked(conn, null, null, stable)) { 7281 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_REMOVE_PROVIDER); 7282 } 7283 } 7284 } finally { 7285 Binder.restoreCallingIdentity(ident); 7286 } 7287 } 7288 7289 /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */ 7290 @Deprecated 7291 @Override removeContentProviderExternal(String name, IBinder token)7292 public void removeContentProviderExternal(String name, IBinder token) { 7293 removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId()); 7294 } 7295 7296 @Override removeContentProviderExternalAsUser(String name, IBinder token, int userId)7297 public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) { 7298 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 7299 "Do not have permission in call removeContentProviderExternal()"); 7300 long ident = Binder.clearCallingIdentity(); 7301 try { 7302 removeContentProviderExternalUnchecked(name, token, userId); 7303 } finally { 7304 Binder.restoreCallingIdentity(ident); 7305 } 7306 } 7307 removeContentProviderExternalUnchecked(String name, IBinder token, int userId)7308 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) { 7309 synchronized (this) { 7310 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId); 7311 if(cpr == null) { 7312 //remove from mProvidersByClass 7313 if(DEBUG_ALL) Slog.v(TAG, name+" content provider not found in providers list"); 7314 return; 7315 } 7316 7317 //update content provider record entry info 7318 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name); 7319 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId); 7320 if (localCpr.hasExternalProcessHandles()) { 7321 if (localCpr.removeExternalProcessHandleLocked(token)) { 7322 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_REMOVE_PROVIDER); 7323 } else { 7324 Slog.e(TAG, "Attmpt to remove content provider " + localCpr 7325 + " with no external reference for token: " 7326 + token + "."); 7327 } 7328 } else { 7329 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr 7330 + " with no external references."); 7331 } 7332 } 7333 } 7334 publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)7335 public final void publishContentProviders(IApplicationThread caller, 7336 List<ContentProviderHolder> providers) { 7337 if (providers == null) { 7338 return; 7339 } 7340 7341 enforceNotIsolatedCaller("publishContentProviders"); 7342 synchronized (this) { 7343 final ProcessRecord r = getRecordForAppLocked(caller); 7344 if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid); 7345 if (r == null) { 7346 throw new SecurityException( 7347 "Unable to find app for caller " + caller 7348 + " (pid=" + Binder.getCallingPid() 7349 + ") when publishing content providers"); 7350 } 7351 7352 final long origId = Binder.clearCallingIdentity(); 7353 7354 final int N = providers.size(); 7355 for (int i = 0; i < N; i++) { 7356 ContentProviderHolder src = providers.get(i); 7357 if (src == null || src.info == null || src.provider == null) { 7358 continue; 7359 } 7360 ContentProviderRecord dst = r.pubProviders.get(src.info.name); 7361 if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid); 7362 if (dst != null) { 7363 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name); 7364 mProviderMap.putProviderByClass(comp, dst); 7365 String names[] = dst.info.authority.split(";"); 7366 for (int j = 0; j < names.length; j++) { 7367 mProviderMap.putProviderByName(names[j], dst); 7368 } 7369 7370 int launchingCount = mLaunchingProviders.size(); 7371 int j; 7372 boolean wasInLaunchingProviders = false; 7373 for (j = 0; j < launchingCount; j++) { 7374 if (mLaunchingProviders.get(j) == dst) { 7375 mLaunchingProviders.remove(j); 7376 wasInLaunchingProviders = true; 7377 j--; 7378 launchingCount--; 7379 } 7380 } 7381 if (wasInLaunchingProviders) { 7382 mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r); 7383 } 7384 // Make sure the package is associated with the process. 7385 // XXX We shouldn't need to do this, since we have added the package 7386 // when we generated the providers in generateApplicationProvidersLocked(). 7387 // But for some reason in some cases we get here with the package no longer 7388 // added... for now just patch it in to make things happy. 7389 r.addPackage(dst.info.applicationInfo.packageName, 7390 dst.info.applicationInfo.longVersionCode, mProcessStats); 7391 synchronized (dst) { 7392 dst.provider = src.provider; 7393 dst.setProcess(r); 7394 dst.notifyAll(); 7395 } 7396 updateOomAdjLocked(r, true, OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER); 7397 maybeUpdateProviderUsageStatsLocked(r, src.info.packageName, 7398 src.info.authority); 7399 } 7400 } 7401 7402 Binder.restoreCallingIdentity(origId); 7403 } 7404 } 7405 refContentProvider(IBinder connection, int stable, int unstable)7406 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 7407 ContentProviderConnection conn; 7408 try { 7409 conn = (ContentProviderConnection)connection; 7410 } catch (ClassCastException e) { 7411 String msg ="refContentProvider: " + connection 7412 + " not a ContentProviderConnection"; 7413 Slog.w(TAG, msg); 7414 throw new IllegalArgumentException(msg); 7415 } 7416 if (conn == null) { 7417 throw new NullPointerException("connection is null"); 7418 } 7419 7420 synchronized (this) { 7421 if (stable > 0) { 7422 conn.numStableIncs += stable; 7423 } 7424 stable = conn.stableCount + stable; 7425 if (stable < 0) { 7426 throw new IllegalStateException("stableCount < 0: " + stable); 7427 } 7428 7429 if (unstable > 0) { 7430 conn.numUnstableIncs += unstable; 7431 } 7432 unstable = conn.unstableCount + unstable; 7433 if (unstable < 0) { 7434 throw new IllegalStateException("unstableCount < 0: " + unstable); 7435 } 7436 7437 if ((stable+unstable) <= 0) { 7438 throw new IllegalStateException("ref counts can't go to zero here: stable=" 7439 + stable + " unstable=" + unstable); 7440 } 7441 conn.stableCount = stable; 7442 conn.unstableCount = unstable; 7443 return !conn.dead; 7444 } 7445 } 7446 unstableProviderDied(IBinder connection)7447 public void unstableProviderDied(IBinder connection) { 7448 ContentProviderConnection conn; 7449 try { 7450 conn = (ContentProviderConnection)connection; 7451 } catch (ClassCastException e) { 7452 String msg ="refContentProvider: " + connection 7453 + " not a ContentProviderConnection"; 7454 Slog.w(TAG, msg); 7455 throw new IllegalArgumentException(msg); 7456 } 7457 if (conn == null) { 7458 throw new NullPointerException("connection is null"); 7459 } 7460 7461 // Safely retrieve the content provider associated with the connection. 7462 IContentProvider provider; 7463 synchronized (this) { 7464 provider = conn.provider.provider; 7465 } 7466 7467 if (provider == null) { 7468 // Um, yeah, we're way ahead of you. 7469 return; 7470 } 7471 7472 // Make sure the caller is being honest with us. 7473 if (provider.asBinder().pingBinder()) { 7474 // Er, no, still looks good to us. 7475 synchronized (this) { 7476 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid() 7477 + " says " + conn + " died, but we don't agree"); 7478 return; 7479 } 7480 } 7481 7482 // Well look at that! It's dead! 7483 synchronized (this) { 7484 if (conn.provider.provider != provider) { 7485 // But something changed... good enough. 7486 return; 7487 } 7488 7489 ProcessRecord proc = conn.provider.proc; 7490 if (proc == null || proc.thread == null) { 7491 // Seems like the process is already cleaned up. 7492 return; 7493 } 7494 7495 // As far as we're concerned, this is just like receiving a 7496 // death notification... just a bit prematurely. 7497 reportUidInfoMessageLocked(TAG, 7498 "Process " + proc.processName + " (pid " + proc.pid 7499 + ") early provider death", 7500 proc.info.uid); 7501 final long ident = Binder.clearCallingIdentity(); 7502 try { 7503 appDiedLocked(proc); 7504 } finally { 7505 Binder.restoreCallingIdentity(ident); 7506 } 7507 } 7508 } 7509 7510 @Override appNotRespondingViaProvider(IBinder connection)7511 public void appNotRespondingViaProvider(IBinder connection) { 7512 enforceCallingPermission(REMOVE_TASKS, "appNotRespondingViaProvider()"); 7513 7514 final ContentProviderConnection conn = (ContentProviderConnection) connection; 7515 if (conn == null) { 7516 Slog.w(TAG, "ContentProviderConnection is null"); 7517 return; 7518 } 7519 7520 final ProcessRecord host = conn.provider.proc; 7521 if (host == null) { 7522 Slog.w(TAG, "Failed to find hosting ProcessRecord"); 7523 return; 7524 } 7525 7526 mHandler.post(new Runnable() { 7527 @Override 7528 public void run() { 7529 host.appNotResponding( 7530 null, null, null, null, false, "ContentProvider not responding"); 7531 } 7532 }); 7533 } 7534 installSystemProviders()7535 public final void installSystemProviders() { 7536 List<ProviderInfo> providers; 7537 synchronized (this) { 7538 ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID); 7539 providers = generateApplicationProvidersLocked(app); 7540 if (providers != null) { 7541 for (int i=providers.size()-1; i>=0; i--) { 7542 ProviderInfo pi = (ProviderInfo)providers.get(i); 7543 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7544 Slog.w(TAG, "Not installing system proc provider " + pi.name 7545 + ": not system .apk"); 7546 providers.remove(i); 7547 } 7548 } 7549 } 7550 } 7551 if (providers != null) { 7552 mSystemThread.installSystemProviders(providers); 7553 } 7554 7555 synchronized (this) { 7556 mSystemProvidersInstalled = true; 7557 } 7558 mConstants.start(mContext.getContentResolver()); 7559 mCoreSettingsObserver = new CoreSettingsObserver(this); 7560 mActivityTaskManager.installSystemProviders(); 7561 mDevelopmentSettingsObserver = new DevelopmentSettingsObserver(); 7562 SettingsToPropertiesMapper.start(mContext.getContentResolver()); 7563 mOomAdjuster.initSettings(); 7564 7565 // Now that the settings provider is published we can consider sending 7566 // in a rescue party. 7567 RescueParty.onSettingsProviderPublished(mContext); 7568 7569 //mUsageStatsService.monitorPackages(); 7570 } 7571 startPersistentApps(int matchFlags)7572 void startPersistentApps(int matchFlags) { 7573 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return; 7574 7575 synchronized (this) { 7576 try { 7577 final List<ApplicationInfo> apps = AppGlobals.getPackageManager() 7578 .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList(); 7579 for (ApplicationInfo app : apps) { 7580 if (!"android".equals(app.packageName)) { 7581 addAppLocked(app, null, false, null /* ABI override */); 7582 } 7583 } 7584 } catch (RemoteException ex) { 7585 } 7586 } 7587 } 7588 7589 /** 7590 * When a user is unlocked, we need to install encryption-unaware providers 7591 * belonging to any running apps. 7592 */ installEncryptionUnawareProviders(int userId)7593 void installEncryptionUnawareProviders(int userId) { 7594 // We're only interested in providers that are encryption unaware, and 7595 // we don't care about uninstalled apps, since there's no way they're 7596 // running at this point. 7597 final int matchFlags = GET_PROVIDERS | MATCH_DIRECT_BOOT_UNAWARE; 7598 7599 synchronized (this) { 7600 final int NP = mProcessList.mProcessNames.getMap().size(); 7601 for (int ip = 0; ip < NP; ip++) { 7602 final SparseArray<ProcessRecord> apps = mProcessList.mProcessNames.getMap().valueAt 7603 (ip); 7604 final int NA = apps.size(); 7605 for (int ia = 0; ia < NA; ia++) { 7606 final ProcessRecord app = apps.valueAt(ia); 7607 if (app.userId != userId || app.thread == null || app.unlocked) continue; 7608 7609 final int NG = app.pkgList.size(); 7610 for (int ig = 0; ig < NG; ig++) { 7611 try { 7612 final String pkgName = app.pkgList.keyAt(ig); 7613 final PackageInfo pkgInfo = AppGlobals.getPackageManager() 7614 .getPackageInfo(pkgName, matchFlags, userId); 7615 if (pkgInfo != null && !ArrayUtils.isEmpty(pkgInfo.providers)) { 7616 for (ProviderInfo pi : pkgInfo.providers) { 7617 // TODO: keep in sync with generateApplicationProvidersLocked 7618 final boolean processMatch = Objects.equals(pi.processName, 7619 app.processName) || pi.multiprocess; 7620 final boolean userMatch = isSingleton(pi.processName, 7621 pi.applicationInfo, pi.name, pi.flags) 7622 ? (app.userId == UserHandle.USER_SYSTEM) : true; 7623 if (processMatch && userMatch) { 7624 Log.v(TAG, "Installing " + pi); 7625 app.thread.scheduleInstallProvider(pi); 7626 } else { 7627 Log.v(TAG, "Skipping " + pi); 7628 } 7629 } 7630 } 7631 } catch (RemoteException ignored) { 7632 } 7633 } 7634 } 7635 } 7636 } 7637 } 7638 7639 /** 7640 * Allows apps to retrieve the MIME type of a URI. 7641 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 7642 * users, then it does not need permission to access the ContentProvider. 7643 * Either, it needs cross-user uri grants. 7644 * 7645 * CTS tests for this functionality can be run with "runtest cts-appsecurity". 7646 * 7647 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/ 7648 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java 7649 */ getProviderMimeType(Uri uri, int userId)7650 public String getProviderMimeType(Uri uri, int userId) { 7651 enforceNotIsolatedCaller("getProviderMimeType"); 7652 final String name = uri.getAuthority(); 7653 int callingUid = Binder.getCallingUid(); 7654 int callingPid = Binder.getCallingPid(); 7655 long ident = 0; 7656 boolean clearedIdentity = false; 7657 userId = mUserController.unsafeConvertIncomingUser(userId); 7658 if (canClearIdentity(callingPid, callingUid, userId)) { 7659 clearedIdentity = true; 7660 ident = Binder.clearCallingIdentity(); 7661 } 7662 ContentProviderHolder holder = null; 7663 try { 7664 holder = getContentProviderExternalUnchecked(name, null, callingUid, 7665 "*getmimetype*", userId); 7666 if (holder != null) { 7667 return holder.provider.getType(uri); 7668 } 7669 } catch (RemoteException e) { 7670 Log.w(TAG, "Content provider dead retrieving " + uri, e); 7671 return null; 7672 } catch (Exception e) { 7673 Log.w(TAG, "Exception while determining type of " + uri, e); 7674 return null; 7675 } finally { 7676 // We need to clear the identity to call removeContentProviderExternalUnchecked 7677 if (!clearedIdentity) { 7678 ident = Binder.clearCallingIdentity(); 7679 } 7680 try { 7681 if (holder != null) { 7682 removeContentProviderExternalUnchecked(name, null, userId); 7683 } 7684 } finally { 7685 Binder.restoreCallingIdentity(ident); 7686 } 7687 } 7688 7689 return null; 7690 } 7691 canClearIdentity(int callingPid, int callingUid, int userId)7692 private boolean canClearIdentity(int callingPid, int callingUid, int userId) { 7693 if (UserHandle.getUserId(callingUid) == userId) { 7694 return true; 7695 } 7696 if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 7697 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED 7698 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 7699 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 7700 return true; 7701 } 7702 return false; 7703 } 7704 7705 // ========================================================= 7706 // GLOBAL MANAGEMENT 7707 // ========================================================= 7708 uidOnBackgroundWhitelist(final int uid)7709 private boolean uidOnBackgroundWhitelist(final int uid) { 7710 final int appId = UserHandle.getAppId(uid); 7711 final int[] whitelist = mBackgroundAppIdWhitelist; 7712 final int N = whitelist.length; 7713 for (int i = 0; i < N; i++) { 7714 if (appId == whitelist[i]) { 7715 return true; 7716 } 7717 } 7718 return false; 7719 } 7720 7721 @Override isBackgroundRestricted(String packageName)7722 public boolean isBackgroundRestricted(String packageName) { 7723 final int callingUid = Binder.getCallingUid(); 7724 final IPackageManager pm = AppGlobals.getPackageManager(); 7725 try { 7726 final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 7727 UserHandle.getUserId(callingUid)); 7728 if (packageUid != callingUid) { 7729 throw new IllegalArgumentException("Uid " + callingUid 7730 + " cannot query restriction state for package " + packageName); 7731 } 7732 } catch (RemoteException exc) { 7733 // Ignore. 7734 } 7735 return isBackgroundRestrictedNoCheck(callingUid, packageName); 7736 } 7737 isBackgroundRestrictedNoCheck(final int uid, final String packageName)7738 boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) { 7739 final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, 7740 uid, packageName); 7741 return mode != AppOpsManager.MODE_ALLOWED; 7742 } 7743 7744 @Override backgroundWhitelistUid(final int uid)7745 public void backgroundWhitelistUid(final int uid) { 7746 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 7747 throw new SecurityException("Only the OS may call backgroundWhitelistUid()"); 7748 } 7749 7750 if (DEBUG_BACKGROUND_CHECK) { 7751 Slog.i(TAG, "Adding uid " + uid + " to bg uid whitelist"); 7752 } 7753 synchronized (this) { 7754 final int N = mBackgroundAppIdWhitelist.length; 7755 int[] newList = new int[N+1]; 7756 System.arraycopy(mBackgroundAppIdWhitelist, 0, newList, 0, N); 7757 newList[N] = UserHandle.getAppId(uid); 7758 mBackgroundAppIdWhitelist = newList; 7759 } 7760 } 7761 7762 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride)7763 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 7764 String abiOverride) { 7765 return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */, 7766 false /* mountExtStorageFull */, abiOverride); 7767 } 7768 7769 // TODO: Move to ProcessList? 7770 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride)7771 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 7772 boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride) { 7773 ProcessRecord app; 7774 if (!isolated) { 7775 app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName, 7776 info.uid, true); 7777 } else { 7778 app = null; 7779 } 7780 7781 if (app == null) { 7782 app = mProcessList.newProcessRecordLocked(info, customProcess, isolated, 0, 7783 new HostingRecord("added application", 7784 customProcess != null ? customProcess : info.processName)); 7785 mProcessList.updateLruProcessLocked(app, false, null); 7786 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN); 7787 } 7788 7789 // This package really, really can not be stopped. 7790 try { 7791 AppGlobals.getPackageManager().setPackageStoppedState( 7792 info.packageName, false, UserHandle.getUserId(app.uid)); 7793 } catch (RemoteException e) { 7794 } catch (IllegalArgumentException e) { 7795 Slog.w(TAG, "Failed trying to unstop package " 7796 + info.packageName + ": " + e); 7797 } 7798 7799 if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 7800 app.setPersistent(true); 7801 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ; 7802 } 7803 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) { 7804 mPersistentStartingProcesses.add(app); 7805 mProcessList.startProcessLocked(app, new HostingRecord("added application", 7806 customProcess != null ? customProcess : app.processName), 7807 disableHiddenApiChecks, mountExtStorageFull, abiOverride); 7808 } 7809 7810 return app; 7811 } 7812 unhandledBack()7813 public void unhandledBack() { 7814 mActivityTaskManager.unhandledBack(); 7815 } 7816 openContentUri(String uriString)7817 public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException { 7818 enforceNotIsolatedCaller("openContentUri"); 7819 final int userId = UserHandle.getCallingUserId(); 7820 final Uri uri = Uri.parse(uriString); 7821 String name = uri.getAuthority(); 7822 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, 7823 Binder.getCallingUid(), "*opencontent*", userId); 7824 ParcelFileDescriptor pfd = null; 7825 if (cph != null) { 7826 // We record the binder invoker's uid in thread-local storage before 7827 // going to the content provider to open the file. Later, in the code 7828 // that handles all permissions checks, we look for this uid and use 7829 // that rather than the Activity Manager's own uid. The effect is that 7830 // we do the check against the caller's permissions even though it looks 7831 // to the content provider like the Activity Manager itself is making 7832 // the request. 7833 Binder token = new Binder(); 7834 sCallerIdentity.set(new Identity( 7835 token, Binder.getCallingPid(), Binder.getCallingUid())); 7836 try { 7837 pfd = cph.provider.openFile(null, uri, "r", null, token); 7838 } catch (FileNotFoundException e) { 7839 // do nothing; pfd will be returned null 7840 } finally { 7841 // Ensure that whatever happens, we clean up the identity state 7842 sCallerIdentity.remove(); 7843 // Ensure we're done with the provider. 7844 removeContentProviderExternalUnchecked(name, null, userId); 7845 } 7846 } else { 7847 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 7848 } 7849 return pfd; 7850 } 7851 reportGlobalUsageEventLocked(int event)7852 void reportGlobalUsageEventLocked(int event) { 7853 mUsageStatsService.reportEvent("android", mUserController.getCurrentUserId(), event); 7854 int[] profiles = mUserController.getCurrentProfileIds(); 7855 if (profiles != null) { 7856 for (int i = profiles.length - 1; i >= 0; i--) { 7857 mUsageStatsService.reportEvent((String)null, profiles[i], event); 7858 } 7859 } 7860 } 7861 reportCurWakefulnessUsageEventLocked()7862 void reportCurWakefulnessUsageEventLocked() { 7863 reportGlobalUsageEventLocked(mWakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE 7864 ? UsageEvents.Event.SCREEN_INTERACTIVE 7865 : UsageEvents.Event.SCREEN_NON_INTERACTIVE); 7866 } 7867 onWakefulnessChanged(int wakefulness)7868 void onWakefulnessChanged(int wakefulness) { 7869 synchronized(this) { 7870 boolean wasAwake = mWakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE; 7871 boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE; 7872 mWakefulness = wakefulness; 7873 7874 if (wasAwake != isAwake) { 7875 // Also update state in a special way for running foreground services UI. 7876 mServices.updateScreenStateLocked(isAwake); 7877 reportCurWakefulnessUsageEventLocked(); 7878 mActivityTaskManager.onScreenAwakeChanged(isAwake); 7879 mOomAdjProfiler.onWakefulnessChanged(wakefulness); 7880 } 7881 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 7882 } 7883 } 7884 7885 @Override notifyCleartextNetwork(int uid, byte[] firstPacket)7886 public void notifyCleartextNetwork(int uid, byte[] firstPacket) { 7887 mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget(); 7888 } 7889 7890 @Override shutdown(int timeout)7891 public boolean shutdown(int timeout) { 7892 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 7893 != PackageManager.PERMISSION_GRANTED) { 7894 throw new SecurityException("Requires permission " 7895 + android.Manifest.permission.SHUTDOWN); 7896 } 7897 7898 final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout); 7899 7900 mAppOpsService.shutdown(); 7901 if (mUsageStatsService != null) { 7902 mUsageStatsService.prepareShutdown(); 7903 } 7904 mBatteryStatsService.shutdown(); 7905 synchronized (this) { 7906 mProcessStats.shutdownLocked(); 7907 } 7908 7909 return timedout; 7910 } 7911 7912 @Override notifyLockedProfile(@serIdInt int userId)7913 public void notifyLockedProfile(@UserIdInt int userId) { 7914 mAtmInternal.notifyLockedProfile(userId, mUserController.getCurrentUserId()); 7915 } 7916 7917 @Override startConfirmDeviceCredentialIntent(Intent intent, Bundle options)7918 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) { 7919 mAtmInternal.startConfirmDeviceCredentialIntent(intent, options); 7920 } 7921 7922 @Override stopAppSwitches()7923 public void stopAppSwitches() { 7924 mActivityTaskManager.stopAppSwitches(); 7925 } 7926 7927 @Override resumeAppSwitches()7928 public void resumeAppSwitches() { 7929 mActivityTaskManager.resumeAppSwitches(); 7930 } 7931 setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)7932 public void setDebugApp(String packageName, boolean waitForDebugger, 7933 boolean persistent) { 7934 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 7935 "setDebugApp()"); 7936 7937 long ident = Binder.clearCallingIdentity(); 7938 try { 7939 // Note that this is not really thread safe if there are multiple 7940 // callers into it at the same time, but that's not a situation we 7941 // care about. 7942 if (persistent) { 7943 final ContentResolver resolver = mContext.getContentResolver(); 7944 Settings.Global.putString( 7945 resolver, Settings.Global.DEBUG_APP, 7946 packageName); 7947 Settings.Global.putInt( 7948 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 7949 waitForDebugger ? 1 : 0); 7950 } 7951 7952 synchronized (this) { 7953 if (!persistent) { 7954 mOrigDebugApp = mDebugApp; 7955 mOrigWaitForDebugger = mWaitForDebugger; 7956 } 7957 mDebugApp = packageName; 7958 mWaitForDebugger = waitForDebugger; 7959 mDebugTransient = !persistent; 7960 if (packageName != null) { 7961 forceStopPackageLocked(packageName, -1, false, false, true, true, 7962 false, UserHandle.USER_ALL, "set debug app"); 7963 } 7964 } 7965 } finally { 7966 Binder.restoreCallingIdentity(ident); 7967 } 7968 } 7969 7970 /** 7971 * Set or remove an agent to be run whenever an app with the given process name starts. 7972 * 7973 * This method will not check whether the given process name matches a debuggable app. That 7974 * would require scanning all current packages, and a rescan when new packages are installed 7975 * or updated. 7976 * 7977 * Instead, do the check when an application is started and matched to a stored agent. 7978 * 7979 * @param packageName the process name of the app. 7980 * @param agent the agent string to be used, or null to remove any previously set agent. 7981 */ 7982 @Override setAgentApp(@onNull String packageName, @Nullable String agent)7983 public void setAgentApp(@NonNull String packageName, @Nullable String agent) { 7984 synchronized (this) { 7985 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 7986 // its own permission. 7987 if (checkCallingPermission( 7988 android.Manifest.permission.SET_ACTIVITY_WATCHER) != 7989 PackageManager.PERMISSION_GRANTED) { 7990 throw new SecurityException( 7991 "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7992 } 7993 7994 if (agent == null) { 7995 if (mAppAgentMap != null) { 7996 mAppAgentMap.remove(packageName); 7997 if (mAppAgentMap.isEmpty()) { 7998 mAppAgentMap = null; 7999 } 8000 } 8001 } else { 8002 if (mAppAgentMap == null) { 8003 mAppAgentMap = new HashMap<>(); 8004 } 8005 if (mAppAgentMap.size() >= 100) { 8006 // Limit the size of the map, to avoid OOMEs. 8007 Slog.e(TAG, "App agent map has too many entries, cannot add " + packageName 8008 + "/" + agent); 8009 return; 8010 } 8011 mAppAgentMap.put(packageName, agent); 8012 } 8013 } 8014 } 8015 setTrackAllocationApp(ApplicationInfo app, String processName)8016 void setTrackAllocationApp(ApplicationInfo app, String processName) { 8017 synchronized (this) { 8018 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 8019 if (!isDebuggable) { 8020 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 8021 throw new SecurityException("Process not debuggable: " + app.packageName); 8022 } 8023 } 8024 8025 mTrackAllocationApp = processName; 8026 } 8027 } 8028 setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo)8029 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) { 8030 synchronized (this) { 8031 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 8032 if (!isDebuggable) { 8033 if (!app.isProfileableByShell()) { 8034 throw new SecurityException("Process not debuggable, " 8035 + "and not profileable by shell: " + app.packageName); 8036 } 8037 } 8038 mProfileData.setProfileApp(processName); 8039 8040 if (mProfileData.getProfilerInfo() != null) { 8041 if (mProfileData.getProfilerInfo().profileFd != null) { 8042 try { 8043 mProfileData.getProfilerInfo().profileFd.close(); 8044 } catch (IOException e) { 8045 } 8046 } 8047 } 8048 mProfileData.setProfilerInfo(new ProfilerInfo(profilerInfo)); 8049 mProfileType = 0; 8050 } 8051 } 8052 setNativeDebuggingAppLocked(ApplicationInfo app, String processName)8053 void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) { 8054 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 8055 if (!isDebuggable) { 8056 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 8057 throw new SecurityException("Process not debuggable: " + app.packageName); 8058 } 8059 } 8060 mNativeDebuggingApp = processName; 8061 } 8062 8063 @Override setAlwaysFinish(boolean enabled)8064 public void setAlwaysFinish(boolean enabled) { 8065 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 8066 "setAlwaysFinish()"); 8067 8068 long ident = Binder.clearCallingIdentity(); 8069 try { 8070 Settings.Global.putInt( 8071 mContext.getContentResolver(), 8072 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 8073 8074 synchronized (this) { 8075 mAlwaysFinishActivities = enabled; 8076 } 8077 } finally { 8078 Binder.restoreCallingIdentity(ident); 8079 } 8080 } 8081 8082 @Override setActivityController(IActivityController controller, boolean imAMonkey)8083 public void setActivityController(IActivityController controller, boolean imAMonkey) { 8084 mActivityTaskManager.setActivityController(controller, imAMonkey); 8085 } 8086 8087 @Override setUserIsMonkey(boolean userIsMonkey)8088 public void setUserIsMonkey(boolean userIsMonkey) { 8089 synchronized (this) { 8090 synchronized (mPidsSelfLocked) { 8091 final int callingPid = Binder.getCallingPid(); 8092 ProcessRecord proc = mPidsSelfLocked.get(callingPid); 8093 if (proc == null) { 8094 throw new SecurityException("Unknown process: " + callingPid); 8095 } 8096 if (proc.getActiveInstrumentation() == null 8097 || proc.getActiveInstrumentation().mUiAutomationConnection == null) { 8098 throw new SecurityException("Only an instrumentation process " 8099 + "with a UiAutomation can call setUserIsMonkey"); 8100 } 8101 } 8102 mUserIsMonkey = userIsMonkey; 8103 } 8104 } 8105 8106 @Override isUserAMonkey()8107 public boolean isUserAMonkey() { 8108 synchronized (this) { 8109 // If there is a controller also implies the user is a monkey. 8110 return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey(); 8111 } 8112 } 8113 8114 @Override requestSystemServerHeapDump()8115 public void requestSystemServerHeapDump() { 8116 if (!Build.IS_DEBUGGABLE) { 8117 Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build"); 8118 return; 8119 } 8120 if (Binder.getCallingUid() != SYSTEM_UID) { 8121 // This also intentionally excludes secondary profiles from calling this. 8122 throw new SecurityException( 8123 "Only the system process is allowed to request a system heap dump"); 8124 } 8125 ProcessRecord pr; 8126 synchronized (mPidsSelfLocked) { 8127 pr = mPidsSelfLocked.get(myPid()); 8128 } 8129 if (pr == null) { 8130 Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid()); 8131 return; 8132 } 8133 synchronized (this) { 8134 startHeapDumpLocked(pr, true); 8135 } 8136 } 8137 8138 /** 8139 * @deprecated This method is only used by a few internal components and it will soon be 8140 * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps). 8141 * No new code should be calling it. 8142 */ 8143 @Deprecated 8144 @Override requestBugReport(int bugreportType)8145 public void requestBugReport(int bugreportType) { 8146 String extraOptions = null; 8147 switch (bugreportType) { 8148 case ActivityManager.BUGREPORT_OPTION_FULL: 8149 extraOptions = "bugreportfull"; 8150 break; 8151 case ActivityManager.BUGREPORT_OPTION_INTERACTIVE: 8152 extraOptions = "bugreportplus"; 8153 break; 8154 case ActivityManager.BUGREPORT_OPTION_REMOTE: 8155 extraOptions = "bugreportremote"; 8156 break; 8157 case ActivityManager.BUGREPORT_OPTION_WEAR: 8158 extraOptions = "bugreportwear"; 8159 break; 8160 case ActivityManager.BUGREPORT_OPTION_TELEPHONY: 8161 extraOptions = "bugreporttelephony"; 8162 break; 8163 case ActivityManager.BUGREPORT_OPTION_WIFI: 8164 extraOptions = "bugreportwifi"; 8165 break; 8166 default: 8167 throw new IllegalArgumentException("Provided bugreport type is not correct, value: " 8168 + bugreportType); 8169 } 8170 // Always log caller, even if it does not have permission to dump. 8171 String type = extraOptions == null ? "bugreport" : extraOptions; 8172 Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid()); 8173 8174 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 8175 if (extraOptions != null) { 8176 SystemProperties.set("dumpstate.options", extraOptions); 8177 } 8178 SystemProperties.set("ctl.start", "bugreport"); 8179 } 8180 8181 /** 8182 * @deprecated This method is only used by a few internal components and it will soon be 8183 * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps). 8184 * No new code should be calling it. 8185 */ 8186 @Deprecated requestBugReportWithDescription(String shareTitle, String shareDescription, int bugreportType)8187 private void requestBugReportWithDescription(String shareTitle, String shareDescription, 8188 int bugreportType) { 8189 if (!TextUtils.isEmpty(shareTitle)) { 8190 if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) { 8191 String errorStr = "shareTitle should be less than " + 8192 MAX_BUGREPORT_TITLE_SIZE + " characters"; 8193 throw new IllegalArgumentException(errorStr); 8194 } else { 8195 if (!TextUtils.isEmpty(shareDescription)) { 8196 int length; 8197 try { 8198 length = shareDescription.getBytes("UTF-8").length; 8199 } catch (UnsupportedEncodingException e) { 8200 String errorStr = "shareDescription: UnsupportedEncodingException"; 8201 throw new IllegalArgumentException(errorStr); 8202 } 8203 if (length > SystemProperties.PROP_VALUE_MAX) { 8204 String errorStr = "shareTitle should be less than " + 8205 SystemProperties.PROP_VALUE_MAX + " bytes"; 8206 throw new IllegalArgumentException(errorStr); 8207 } else { 8208 SystemProperties.set("dumpstate.options.description", shareDescription); 8209 } 8210 } 8211 SystemProperties.set("dumpstate.options.title", shareTitle); 8212 } 8213 } 8214 8215 Slog.d(TAG, "Bugreport notification title " + shareTitle 8216 + " description " + shareDescription); 8217 requestBugReport(bugreportType); 8218 } 8219 8220 /** 8221 * @deprecated This method is only used by a few internal components and it will soon be 8222 * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps). 8223 * No new code should be calling it. 8224 */ 8225 @Deprecated 8226 @Override requestTelephonyBugReport(String shareTitle, String shareDescription)8227 public void requestTelephonyBugReport(String shareTitle, String shareDescription) { 8228 requestBugReportWithDescription(shareTitle, shareDescription, 8229 ActivityManager.BUGREPORT_OPTION_TELEPHONY); 8230 } 8231 8232 /** 8233 * @deprecated This method is only used by a few internal components and it will soon be 8234 * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps). 8235 * No new code should be calling it. 8236 */ 8237 @Deprecated 8238 @Override requestWifiBugReport(String shareTitle, String shareDescription)8239 public void requestWifiBugReport(String shareTitle, String shareDescription) { 8240 requestBugReportWithDescription(shareTitle, shareDescription, 8241 ActivityManager.BUGREPORT_OPTION_WIFI); 8242 } 8243 registerProcessObserver(IProcessObserver observer)8244 public void registerProcessObserver(IProcessObserver observer) { 8245 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 8246 "registerProcessObserver()"); 8247 synchronized (this) { 8248 mProcessObservers.register(observer); 8249 } 8250 } 8251 8252 @Override unregisterProcessObserver(IProcessObserver observer)8253 public void unregisterProcessObserver(IProcessObserver observer) { 8254 synchronized (this) { 8255 mProcessObservers.unregister(observer); 8256 } 8257 } 8258 8259 @Override getUidProcessState(int uid, String callingPackage)8260 public int getUidProcessState(int uid, String callingPackage) { 8261 if (!hasUsageStatsPermission(callingPackage)) { 8262 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8263 "getUidProcessState"); 8264 } 8265 8266 synchronized (this) { 8267 return mProcessList.getUidProcStateLocked(uid); 8268 } 8269 } 8270 8271 @Override registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)8272 public void registerUidObserver(IUidObserver observer, int which, int cutpoint, 8273 String callingPackage) { 8274 if (!hasUsageStatsPermission(callingPackage)) { 8275 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8276 "registerUidObserver"); 8277 } 8278 synchronized (this) { 8279 mUidObservers.register(observer, new UidObserverRegistration(Binder.getCallingUid(), 8280 callingPackage, which, cutpoint)); 8281 } 8282 } 8283 8284 @Override unregisterUidObserver(IUidObserver observer)8285 public void unregisterUidObserver(IUidObserver observer) { 8286 synchronized (this) { 8287 mUidObservers.unregister(observer); 8288 } 8289 } 8290 8291 @Override isUidActive(int uid, String callingPackage)8292 public boolean isUidActive(int uid, String callingPackage) { 8293 if (!hasUsageStatsPermission(callingPackage)) { 8294 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8295 "isUidActive"); 8296 } 8297 synchronized (this) { 8298 return isUidActiveLocked(uid); 8299 } 8300 } 8301 isUidActiveLocked(int uid)8302 boolean isUidActiveLocked(int uid) { 8303 final UidRecord uidRecord = mProcessList.getUidRecordLocked(uid); 8304 return uidRecord != null && !uidRecord.setIdle; 8305 } 8306 8307 @Override setPersistentVrThread(int tid)8308 public void setPersistentVrThread(int tid) { 8309 mActivityTaskManager.setPersistentVrThread(tid); 8310 } 8311 8312 /** 8313 * Schedule the given thread a normal scheduling priority. 8314 * 8315 * @param tid the tid of the thread to adjust the scheduling of. 8316 * @param suppressLogs {@code true} if any error logging should be disabled. 8317 * 8318 * @return {@code true} if this succeeded. 8319 */ scheduleAsRegularPriority(int tid, boolean suppressLogs)8320 public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) { 8321 try { 8322 Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0); 8323 return true; 8324 } catch (IllegalArgumentException e) { 8325 if (!suppressLogs) { 8326 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 8327 } 8328 } catch (SecurityException e) { 8329 if (!suppressLogs) { 8330 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 8331 } 8332 } 8333 return false; 8334 } 8335 8336 /** 8337 * Schedule the given thread an FIFO scheduling priority. 8338 * 8339 * @param tid the tid of the thread to adjust the scheduling of. 8340 * @param suppressLogs {@code true} if any error logging should be disabled. 8341 * 8342 * @return {@code true} if this succeeded. 8343 */ scheduleAsFifoPriority(int tid, boolean suppressLogs)8344 public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) { 8345 try { 8346 Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1); 8347 return true; 8348 } catch (IllegalArgumentException e) { 8349 if (!suppressLogs) { 8350 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 8351 } 8352 } catch (SecurityException e) { 8353 if (!suppressLogs) { 8354 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 8355 } 8356 } 8357 return false; 8358 } 8359 8360 @Override setRenderThread(int tid)8361 public void setRenderThread(int tid) { 8362 synchronized (this) { 8363 ProcessRecord proc; 8364 int pid = Binder.getCallingPid(); 8365 if (pid == Process.myPid()) { 8366 demoteSystemServerRenderThread(tid); 8367 return; 8368 } 8369 synchronized (mPidsSelfLocked) { 8370 proc = mPidsSelfLocked.get(pid); 8371 if (proc != null && proc.renderThreadTid == 0 && tid > 0) { 8372 // ensure the tid belongs to the process 8373 if (!isThreadInProcess(pid, tid)) { 8374 throw new IllegalArgumentException( 8375 "Render thread does not belong to process"); 8376 } 8377 proc.renderThreadTid = tid; 8378 if (DEBUG_OOM_ADJ) { 8379 Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid); 8380 } 8381 // promote to FIFO now 8382 if (proc.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) { 8383 if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band"); 8384 if (mUseFifoUiScheduling) { 8385 setThreadScheduler(proc.renderThreadTid, 8386 SCHED_FIFO | SCHED_RESET_ON_FORK, 1); 8387 } else { 8388 setThreadPriority(proc.renderThreadTid, TOP_APP_PRIORITY_BOOST); 8389 } 8390 } 8391 } else { 8392 if (DEBUG_OOM_ADJ) { 8393 Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " + 8394 "PID: " + pid + ", TID: " + tid + " FIFO: " + 8395 mUseFifoUiScheduling); 8396 } 8397 } 8398 } 8399 } 8400 } 8401 8402 /** 8403 * We only use RenderThread in system_server to store task snapshots to the disk, which should 8404 * happen in the background. Thus, demote render thread from system_server to a lower priority. 8405 * 8406 * @param tid the tid of the RenderThread 8407 */ demoteSystemServerRenderThread(int tid)8408 private void demoteSystemServerRenderThread(int tid) { 8409 setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND); 8410 } 8411 8412 @Override isVrModePackageEnabled(ComponentName packageName)8413 public boolean isVrModePackageEnabled(ComponentName packageName) { 8414 mActivityTaskManager.enforceSystemHasVrFeature(); 8415 8416 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); 8417 8418 return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) == 8419 VrManagerInternal.NO_ERROR; 8420 } 8421 isTopActivityImmersive()8422 public boolean isTopActivityImmersive() { 8423 return mActivityTaskManager.isTopActivityImmersive(); 8424 } 8425 8426 @Override isTopOfTask(IBinder token)8427 public boolean isTopOfTask(IBinder token) { 8428 return mActivityTaskManager.isTopOfTask(token); 8429 } 8430 8431 @Override setHasTopUi(boolean hasTopUi)8432 public void setHasTopUi(boolean hasTopUi) throws RemoteException { 8433 if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) { 8434 String msg = "Permission Denial: setHasTopUi() from pid=" 8435 + Binder.getCallingPid() 8436 + ", uid=" + Binder.getCallingUid() 8437 + " requires " + permission.INTERNAL_SYSTEM_WINDOW; 8438 Slog.w(TAG, msg); 8439 throw new SecurityException(msg); 8440 } 8441 final int pid = Binder.getCallingPid(); 8442 final long origId = Binder.clearCallingIdentity(); 8443 try { 8444 synchronized (this) { 8445 boolean changed = false; 8446 ProcessRecord pr; 8447 synchronized (mPidsSelfLocked) { 8448 pr = mPidsSelfLocked.get(pid); 8449 if (pr == null) { 8450 Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid); 8451 return; 8452 } 8453 if (pr.hasTopUi() != hasTopUi) { 8454 if (DEBUG_OOM_ADJ) { 8455 Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid); 8456 } 8457 pr.setHasTopUi(hasTopUi); 8458 changed = true; 8459 } 8460 } 8461 if (changed) { 8462 updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 8463 } 8464 } 8465 } finally { 8466 Binder.restoreCallingIdentity(origId); 8467 } 8468 } 8469 setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation)8470 void setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation) { 8471 if (pid == Process.myPid()) { 8472 Slog.wtf(TAG, "system can't run remote animation"); 8473 return; 8474 } 8475 synchronized (ActivityManagerService.this) { 8476 final ProcessRecord pr; 8477 synchronized (mPidsSelfLocked) { 8478 pr = mPidsSelfLocked.get(pid); 8479 if (pr == null) { 8480 Slog.w(TAG, "setRunningRemoteAnimation called on unknown pid: " + pid); 8481 return; 8482 } 8483 } 8484 if (pr.runningRemoteAnimation == runningRemoteAnimation) { 8485 return; 8486 } 8487 pr.runningRemoteAnimation = runningRemoteAnimation; 8488 if (DEBUG_OOM_ADJ) { 8489 Slog.i(TAG, "Setting runningRemoteAnimation=" + pr.runningRemoteAnimation 8490 + " for pid=" + pid); 8491 } 8492 updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 8493 } 8494 } 8495 enterSafeMode()8496 public final void enterSafeMode() { 8497 synchronized(this) { 8498 // It only makes sense to do this before the system is ready 8499 // and started launching other packages. 8500 if (!mSystemReady) { 8501 try { 8502 AppGlobals.getPackageManager().enterSafeMode(); 8503 } catch (RemoteException e) { 8504 } 8505 } 8506 8507 mSafeMode = true; 8508 } 8509 } 8510 showSafeModeOverlay()8511 public final void showSafeModeOverlay() { 8512 View v = LayoutInflater.from(mContext).inflate( 8513 com.android.internal.R.layout.safe_mode, null); 8514 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 8515 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 8516 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 8517 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 8518 lp.gravity = Gravity.BOTTOM | Gravity.START; 8519 lp.format = v.getBackground().getOpacity(); 8520 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 8521 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 8522 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; 8523 ((WindowManager)mContext.getSystemService( 8524 Context.WINDOW_SERVICE)).addView(v, lp); 8525 } 8526 8527 @Override noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)8528 public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, 8529 String sourcePkg, String tag) { 8530 if (workSource != null && workSource.isEmpty()) { 8531 workSource = null; 8532 } 8533 8534 if (sourceUid <= 0 && workSource == null) { 8535 // Try and derive a UID to attribute things to based on the caller. 8536 if (sender != null) { 8537 if (!(sender instanceof PendingIntentRecord)) { 8538 return; 8539 } 8540 8541 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8542 final int callerUid = Binder.getCallingUid(); 8543 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8544 } else { 8545 // TODO(narayan): Should we throw an exception in this case ? It means that we 8546 // haven't been able to derive a UID to attribute things to. 8547 return; 8548 } 8549 } 8550 8551 int standbyBucket = 0; 8552 8553 mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag); 8554 if (workSource != null) { 8555 String workSourcePackage = workSource.getName(0); 8556 int workSourceUid = workSource.getAttributionUid(); 8557 if (workSourcePackage == null) { 8558 workSourcePackage = sourcePkg; 8559 workSourceUid = sourceUid; 8560 } 8561 8562 if (mUsageStatsService != null) { 8563 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage, 8564 UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime()); 8565 } 8566 8567 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag, sourcePkg, 8568 standbyBucket); 8569 if (DEBUG_POWER) { 8570 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 8571 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 8572 + standbyBucket + " wsName=" + workSourcePackage + ")]"); 8573 } 8574 } else { 8575 if (mUsageStatsService != null) { 8576 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg, 8577 UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime()); 8578 } 8579 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, sourceUid, null, tag, 8580 sourcePkg, standbyBucket); 8581 if (DEBUG_POWER) { 8582 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 8583 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 8584 + standbyBucket + "]"); 8585 } 8586 } 8587 8588 } 8589 8590 @Override noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8591 public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, 8592 String tag) { 8593 if (workSource != null && workSource.isEmpty()) { 8594 workSource = null; 8595 } 8596 8597 if (sourceUid <= 0 && workSource == null) { 8598 // Try and derive a UID to attribute things to based on the caller. 8599 if (sender != null) { 8600 if (!(sender instanceof PendingIntentRecord)) { 8601 return; 8602 } 8603 8604 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8605 final int callerUid = Binder.getCallingUid(); 8606 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8607 } else { 8608 // TODO(narayan): Should we throw an exception in this case ? It means that we 8609 // haven't been able to derive a UID to attribute things to. 8610 return; 8611 } 8612 } 8613 8614 if (DEBUG_POWER) { 8615 Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource + 8616 ", tag=" + tag + "]"); 8617 } 8618 8619 mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid); 8620 } 8621 8622 @Override noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8623 public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, 8624 String tag) { 8625 if (workSource != null && workSource.isEmpty()) { 8626 workSource = null; 8627 } 8628 8629 if (sourceUid <= 0 && workSource == null) { 8630 // Try and derive a UID to attribute things to based on the caller. 8631 if (sender != null) { 8632 if (!(sender instanceof PendingIntentRecord)) { 8633 return; 8634 } 8635 8636 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8637 final int callerUid = Binder.getCallingUid(); 8638 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8639 } else { 8640 // TODO(narayan): Should we throw an exception in this case ? It means that we 8641 // haven't been able to derive a UID to attribute things to. 8642 return; 8643 } 8644 } 8645 8646 if (DEBUG_POWER) { 8647 Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource + 8648 ", tag=" + tag + "]"); 8649 } 8650 8651 mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid); 8652 } 8653 killPids(int[] pids, String pReason, boolean secure)8654 public boolean killPids(int[] pids, String pReason, boolean secure) { 8655 if (Binder.getCallingUid() != SYSTEM_UID) { 8656 throw new SecurityException("killPids only available to the system"); 8657 } 8658 String reason = (pReason == null) ? "Unknown" : pReason; 8659 // XXX Note: don't acquire main activity lock here, because the window 8660 // manager calls in with its locks held. 8661 8662 boolean killed = false; 8663 synchronized (mPidsSelfLocked) { 8664 int worstType = 0; 8665 for (int i=0; i<pids.length; i++) { 8666 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 8667 if (proc != null) { 8668 int type = proc.setAdj; 8669 if (type > worstType) { 8670 worstType = type; 8671 } 8672 } 8673 } 8674 8675 // If the worst oom_adj is somewhere in the cached proc LRU range, 8676 // then constrain it so we will kill all cached procs. 8677 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 8678 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 8679 worstType = ProcessList.CACHED_APP_MIN_ADJ; 8680 } 8681 8682 // If this is not a secure call, don't let it kill processes that 8683 // are important. 8684 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 8685 worstType = ProcessList.SERVICE_ADJ; 8686 } 8687 8688 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 8689 for (int i=0; i<pids.length; i++) { 8690 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 8691 if (proc == null) { 8692 continue; 8693 } 8694 int adj = proc.setAdj; 8695 if (adj >= worstType && !proc.killedByAm) { 8696 proc.kill(reason, true); 8697 killed = true; 8698 } 8699 } 8700 } 8701 return killed; 8702 } 8703 8704 @Override killUid(int appId, int userId, String reason)8705 public void killUid(int appId, int userId, String reason) { 8706 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 8707 synchronized (this) { 8708 final long identity = Binder.clearCallingIdentity(); 8709 try { 8710 mProcessList.killPackageProcessesLocked(null /* packageName */, appId, userId, 8711 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 8712 true /* callerWillRestart */, true /* doit */, true /* evenPersistent */, 8713 false /* setRemoved */, reason != null ? reason : "kill uid"); 8714 } finally { 8715 Binder.restoreCallingIdentity(identity); 8716 } 8717 } 8718 } 8719 8720 @Override killProcessesBelowForeground(String reason)8721 public boolean killProcessesBelowForeground(String reason) { 8722 if (Binder.getCallingUid() != SYSTEM_UID) { 8723 throw new SecurityException("killProcessesBelowForeground() only available to system"); 8724 } 8725 8726 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 8727 } 8728 killProcessesBelowAdj(int belowAdj, String reason)8729 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 8730 if (Binder.getCallingUid() != SYSTEM_UID) { 8731 throw new SecurityException("killProcessesBelowAdj() only available to system"); 8732 } 8733 8734 boolean killed = false; 8735 synchronized (mPidsSelfLocked) { 8736 final int size = mPidsSelfLocked.size(); 8737 for (int i = 0; i < size; i++) { 8738 final int pid = mPidsSelfLocked.keyAt(i); 8739 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 8740 if (proc == null) continue; 8741 8742 final int adj = proc.setAdj; 8743 if (adj > belowAdj && !proc.killedByAm) { 8744 proc.kill(reason, true); 8745 killed = true; 8746 } 8747 } 8748 } 8749 return killed; 8750 } 8751 8752 @Override hang(final IBinder who, boolean allowRestart)8753 public void hang(final IBinder who, boolean allowRestart) { 8754 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8755 != PackageManager.PERMISSION_GRANTED) { 8756 throw new SecurityException("Requires permission " 8757 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8758 } 8759 8760 final IBinder.DeathRecipient death = new DeathRecipient() { 8761 @Override 8762 public void binderDied() { 8763 synchronized (this) { 8764 notifyAll(); 8765 } 8766 } 8767 }; 8768 8769 try { 8770 who.linkToDeath(death, 0); 8771 } catch (RemoteException e) { 8772 Slog.w(TAG, "hang: given caller IBinder is already dead."); 8773 return; 8774 } 8775 8776 synchronized (this) { 8777 Watchdog.getInstance().setAllowRestart(allowRestart); 8778 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 8779 synchronized (death) { 8780 while (who.isBinderAlive()) { 8781 try { 8782 death.wait(); 8783 } catch (InterruptedException e) { 8784 } 8785 } 8786 } 8787 Watchdog.getInstance().setAllowRestart(true); 8788 } 8789 } 8790 8791 @Override restart()8792 public void restart() { 8793 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8794 != PackageManager.PERMISSION_GRANTED) { 8795 throw new SecurityException("Requires permission " 8796 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8797 } 8798 8799 Log.i(TAG, "Sending shutdown broadcast..."); 8800 8801 BroadcastReceiver br = new BroadcastReceiver() { 8802 @Override public void onReceive(Context context, Intent intent) { 8803 // Now the broadcast is done, finish up the low-level shutdown. 8804 Log.i(TAG, "Shutting down activity manager..."); 8805 shutdown(10000); 8806 Log.i(TAG, "Shutdown complete, restarting!"); 8807 killProcess(myPid()); 8808 System.exit(10); 8809 } 8810 }; 8811 8812 // First send the high-level shut down broadcast. 8813 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 8814 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8815 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 8816 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 8817 mContext.sendOrderedBroadcastAsUser(intent, 8818 UserHandle.ALL, null, br, mHandler, 0, null, null); 8819 */ 8820 br.onReceive(mContext, intent); 8821 } 8822 getLowRamTimeSinceIdle(long now)8823 private long getLowRamTimeSinceIdle(long now) { 8824 return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0); 8825 } 8826 8827 @Override performIdleMaintenance()8828 public void performIdleMaintenance() { 8829 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8830 != PackageManager.PERMISSION_GRANTED) { 8831 throw new SecurityException("Requires permission " 8832 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8833 } 8834 8835 synchronized (this) { 8836 final long now = SystemClock.uptimeMillis(); 8837 final long timeSinceLastIdle = now - mLastIdleTime; 8838 8839 // Compact all non-zygote processes to freshen up the page cache. 8840 mOomAdjuster.mAppCompact.compactAllSystem(); 8841 8842 final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now); 8843 mLastIdleTime = now; 8844 mLowRamTimeSinceLastIdle = 0; 8845 if (mLowRamStartTime != 0) { 8846 mLowRamStartTime = now; 8847 } 8848 8849 StringBuilder sb = new StringBuilder(128); 8850 sb.append("Idle maintenance over "); 8851 TimeUtils.formatDuration(timeSinceLastIdle, sb); 8852 sb.append(" low RAM for "); 8853 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 8854 Slog.i(TAG, sb.toString()); 8855 8856 // If at least 1/3 of our time since the last idle period has been spent 8857 // with RAM low, then we want to kill processes. 8858 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 8859 // If the processes' memory has increased by more than 1% of the total memory, 8860 // or 10 MB, whichever is greater, then the processes' are eligible to be killed. 8861 final long totalMemoryInKb = getTotalMemory() / 1000; 8862 final long memoryGrowthThreshold = 8863 Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD); 8864 8865 for (int i = mProcessList.mLruProcesses.size() - 1 ; i >= 0 ; i--) { 8866 ProcessRecord proc = mProcessList.mLruProcesses.get(i); 8867 if (proc.notCachedSinceIdle) { 8868 if (proc.setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE 8869 && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 8870 if (doKilling && proc.initialIdlePss != 0 8871 && proc.lastPss > ((proc.initialIdlePss * 3) / 2) 8872 && proc.lastPss > (proc.initialIdlePss + memoryGrowthThreshold)) { 8873 sb = new StringBuilder(128); 8874 sb.append("Kill"); 8875 sb.append(proc.processName); 8876 sb.append(" in idle maint: pss="); 8877 sb.append(proc.lastPss); 8878 sb.append(", swapPss="); 8879 sb.append(proc.lastSwapPss); 8880 sb.append(", initialPss="); 8881 sb.append(proc.initialIdlePss); 8882 sb.append(", period="); 8883 TimeUtils.formatDuration(timeSinceLastIdle, sb); 8884 sb.append(", lowRamPeriod="); 8885 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 8886 Slog.wtfQuiet(TAG, sb.toString()); 8887 proc.kill("idle maint (pss " + proc.lastPss 8888 + " from " + proc.initialIdlePss + ")", true); 8889 } 8890 } 8891 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME 8892 && proc.setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) { 8893 proc.notCachedSinceIdle = true; 8894 proc.initialIdlePss = 0; 8895 proc.nextPssTime = ProcessList.computeNextPssTime(proc.setProcState, null, 8896 mTestPssMode, mAtmInternal.isSleeping(), now); 8897 } 8898 } 8899 } 8900 } 8901 8902 @Override sendIdleJobTrigger()8903 public void sendIdleJobTrigger() { 8904 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8905 != PackageManager.PERMISSION_GRANTED) { 8906 throw new SecurityException("Requires permission " 8907 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8908 } 8909 8910 final long ident = Binder.clearCallingIdentity(); 8911 try { 8912 Intent intent = new Intent(ACTION_TRIGGER_IDLE) 8913 .setPackage("android") 8914 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 8915 broadcastIntent(null, intent, null, null, 0, null, null, null, 8916 OP_NONE, null, false, false, UserHandle.USER_ALL); 8917 } finally { 8918 Binder.restoreCallingIdentity(ident); 8919 } 8920 } 8921 retrieveSettings()8922 private void retrieveSettings() { 8923 final ContentResolver resolver = mContext.getContentResolver(); 8924 mActivityTaskManager.retrieveSettings(resolver); 8925 8926 final String debugApp = Settings.Global.getString(resolver, DEBUG_APP); 8927 final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0; 8928 final boolean alwaysFinishActivities = 8929 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0; 8930 final long waitForNetworkTimeoutMs = Settings.Global.getLong(resolver, 8931 NETWORK_ACCESS_TIMEOUT_MS, NETWORK_ACCESS_TIMEOUT_DEFAULT_MS); 8932 mHiddenApiBlacklist.registerObserver(); 8933 8934 final long pssDeferralMs = DeviceConfig.getLong(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, 8935 ACTIVITY_START_PSS_DEFER_CONFIG, 0L); 8936 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, 8937 ActivityThread.currentApplication().getMainExecutor(), 8938 mPssDelayConfigListener); 8939 8940 synchronized (this) { 8941 mDebugApp = mOrigDebugApp = debugApp; 8942 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 8943 mAlwaysFinishActivities = alwaysFinishActivities; 8944 // Load resources only after the current configuration has been set. 8945 final Resources res = mContext.getResources(); 8946 mAppErrors.loadAppsNotReportingCrashesFromConfigLocked(res.getString( 8947 com.android.internal.R.string.config_appsNotReportingCrashes)); 8948 mUserController.mUserSwitchUiEnabled = !res.getBoolean( 8949 com.android.internal.R.bool.config_customUserSwitchUi); 8950 mUserController.mMaxRunningUsers = res.getInteger( 8951 com.android.internal.R.integer.config_multiuserMaxRunningUsers); 8952 mUserController.mDelayUserDataLocking = res.getBoolean( 8953 com.android.internal.R.bool.config_multiuserDelayUserDataLocking); 8954 8955 mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs; 8956 mPssDeferralTime = pssDeferralMs; 8957 } 8958 } 8959 systemReady(final Runnable goingCallback, TimingsTraceLog traceLog)8960 public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) { 8961 traceLog.traceBegin("PhaseActivityManagerReady"); 8962 synchronized(this) { 8963 if (mSystemReady) { 8964 // If we're done calling all the receivers, run the next "boot phase" passed in 8965 // by the SystemServer 8966 if (goingCallback != null) { 8967 goingCallback.run(); 8968 } 8969 return; 8970 } 8971 8972 mLocalDeviceIdleController 8973 = LocalServices.getService(DeviceIdleController.LocalService.class); 8974 mActivityTaskManager.onSystemReady(); 8975 // Make sure we have the current profile info, since it is needed for security checks. 8976 mUserController.onSystemReady(); 8977 mAppOpsService.systemReady(); 8978 mSystemReady = true; 8979 } 8980 8981 try { 8982 sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface( 8983 ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE)) 8984 .getSerial(); 8985 } catch (RemoteException e) {} 8986 8987 ArrayList<ProcessRecord> procsToKill = null; 8988 synchronized(mPidsSelfLocked) { 8989 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 8990 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 8991 if (!isAllowedWhileBooting(proc.info)){ 8992 if (procsToKill == null) { 8993 procsToKill = new ArrayList<ProcessRecord>(); 8994 } 8995 procsToKill.add(proc); 8996 } 8997 } 8998 } 8999 9000 synchronized(this) { 9001 if (procsToKill != null) { 9002 for (int i=procsToKill.size()-1; i>=0; i--) { 9003 ProcessRecord proc = procsToKill.get(i); 9004 Slog.i(TAG, "Removing system update proc: " + proc); 9005 mProcessList.removeProcessLocked(proc, true, false, "system update done"); 9006 } 9007 } 9008 9009 // Now that we have cleaned up any update processes, we 9010 // are ready to start launching real processes and know that 9011 // we won't trample on them any more. 9012 mProcessesReady = true; 9013 } 9014 9015 Slog.i(TAG, "System now ready"); 9016 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, SystemClock.uptimeMillis()); 9017 9018 mAtmInternal.updateTopComponentForFactoryTest(); 9019 mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver); 9020 9021 watchDeviceProvisioning(mContext); 9022 9023 retrieveSettings(); 9024 mUgmInternal.onSystemReady(); 9025 9026 final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class); 9027 if (pmi != null) { 9028 pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK, 9029 state -> updateForceBackgroundCheck(state.batterySaverEnabled)); 9030 updateForceBackgroundCheck( 9031 pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled); 9032 } else { 9033 Slog.wtf(TAG, "PowerManagerInternal not found."); 9034 } 9035 9036 if (goingCallback != null) goingCallback.run(); 9037 // Check the current user here as a user can be started inside goingCallback.run() from 9038 // other system services. 9039 final int currentUserId = mUserController.getCurrentUserId(); 9040 Slog.i(TAG, "Current user:" + currentUserId); 9041 if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) { 9042 // User other than system user has started. Make sure that system user is already 9043 // started before switching user. 9044 throw new RuntimeException("System user not started while current user is:" 9045 + currentUserId); 9046 } 9047 traceLog.traceBegin("ActivityManagerStartApps"); 9048 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 9049 Integer.toString(currentUserId), currentUserId); 9050 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 9051 Integer.toString(currentUserId), currentUserId); 9052 mSystemServiceManager.startUser(currentUserId); 9053 9054 synchronized (this) { 9055 // Only start up encryption-aware persistent apps; once user is 9056 // unlocked we'll come back around and start unaware apps 9057 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE); 9058 9059 // Start up initial activity. 9060 mBooting = true; 9061 // Enable home activity for system user, so that the system can always boot. We don't 9062 // do this when the system user is not setup since the setup wizard should be the one 9063 // to handle home activity in this case. 9064 if (UserManager.isSplitSystemUser() && 9065 Settings.Secure.getInt(mContext.getContentResolver(), 9066 Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) { 9067 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class); 9068 try { 9069 AppGlobals.getPackageManager().setComponentEnabledSetting(cName, 9070 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0, 9071 UserHandle.USER_SYSTEM); 9072 } catch (RemoteException e) { 9073 throw e.rethrowAsRuntimeException(); 9074 } 9075 } 9076 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady"); 9077 9078 mAtmInternal.showSystemReadyErrorDialogsIfNeeded(); 9079 9080 final int callingUid = Binder.getCallingUid(); 9081 final int callingPid = Binder.getCallingPid(); 9082 long ident = Binder.clearCallingIdentity(); 9083 try { 9084 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 9085 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 9086 | Intent.FLAG_RECEIVER_FOREGROUND); 9087 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); 9088 broadcastIntentLocked(null, null, intent, 9089 null, null, 0, null, null, null, OP_NONE, 9090 null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid, 9091 currentUserId); 9092 intent = new Intent(Intent.ACTION_USER_STARTING); 9093 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 9094 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); 9095 broadcastIntentLocked(null, null, intent, 9096 null, new IIntentReceiver.Stub() { 9097 @Override 9098 public void performReceive(Intent intent, int resultCode, String data, 9099 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 9100 throws RemoteException { 9101 } 9102 }, 0, null, null, 9103 new String[] {INTERACT_ACROSS_USERS}, OP_NONE, 9104 null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid, 9105 UserHandle.USER_ALL); 9106 } catch (Throwable t) { 9107 Slog.wtf(TAG, "Failed sending first user broadcasts", t); 9108 } finally { 9109 Binder.restoreCallingIdentity(ident); 9110 } 9111 mAtmInternal.resumeTopActivities(false /* scheduleIdle */); 9112 mUserController.sendUserSwitchBroadcasts(-1, currentUserId); 9113 9114 BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK, 9115 BINDER_PROXY_LOW_WATERMARK); 9116 BinderInternal.nSetBinderProxyCountEnabled(true); 9117 BinderInternal.setBinderProxyCountCallback( 9118 new BinderInternal.BinderProxyLimitListener() { 9119 @Override 9120 public void onLimitReached(int uid) { 9121 Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid " 9122 + Process.myUid()); 9123 BinderProxy.dumpProxyDebugInfo(); 9124 if (uid == Process.SYSTEM_UID) { 9125 Slog.i(TAG, "Skipping kill (uid is SYSTEM)"); 9126 } else { 9127 killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid), 9128 "Too many Binders sent to SYSTEM"); 9129 } 9130 } 9131 }, mHandler); 9132 9133 traceLog.traceEnd(); // ActivityManagerStartApps 9134 traceLog.traceEnd(); // PhaseActivityManagerReady 9135 } 9136 } 9137 watchDeviceProvisioning(Context context)9138 private void watchDeviceProvisioning(Context context) { 9139 // setting system property based on whether device is provisioned 9140 9141 if (isDeviceProvisioned(context)) { 9142 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 9143 } else { 9144 // watch for device provisioning change 9145 context.getContentResolver().registerContentObserver( 9146 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false, 9147 new ContentObserver(new Handler(Looper.getMainLooper())) { 9148 @Override 9149 public void onChange(boolean selfChange) { 9150 if (isDeviceProvisioned(context)) { 9151 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 9152 context.getContentResolver().unregisterContentObserver(this); 9153 } 9154 } 9155 }); 9156 } 9157 } 9158 isDeviceProvisioned(Context context)9159 private boolean isDeviceProvisioned(Context context) { 9160 return Settings.Global.getInt(context.getContentResolver(), 9161 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 9162 } 9163 startBroadcastObservers()9164 private void startBroadcastObservers() { 9165 for (BroadcastQueue queue : mBroadcastQueues) { 9166 queue.start(mContext.getContentResolver()); 9167 } 9168 } 9169 updateForceBackgroundCheck(boolean enabled)9170 private void updateForceBackgroundCheck(boolean enabled) { 9171 synchronized (this) { 9172 if (mForceBackgroundCheck != enabled) { 9173 mForceBackgroundCheck = enabled; 9174 9175 if (DEBUG_BACKGROUND_CHECK) { 9176 Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled")); 9177 } 9178 9179 if (mForceBackgroundCheck) { 9180 // Stop background services for idle UIDs. 9181 mProcessList.doStopUidForIdleUidsLocked(); 9182 } 9183 } 9184 } 9185 } 9186 killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog)9187 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) { 9188 synchronized (this) { 9189 mAppErrors.killAppAtUserRequestLocked(app, fromDialog); 9190 } 9191 } 9192 skipCurrentReceiverLocked(ProcessRecord app)9193 void skipCurrentReceiverLocked(ProcessRecord app) { 9194 for (BroadcastQueue queue : mBroadcastQueues) { 9195 queue.skipCurrentReceiverLocked(app); 9196 } 9197 } 9198 9199 /** 9200 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 9201 * The application process will exit immediately after this call returns. 9202 * @param app object of the crashing app, null for the system server 9203 * @param crashInfo describing the exception 9204 */ handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)9205 public void handleApplicationCrash(IBinder app, 9206 ApplicationErrorReport.ParcelableCrashInfo crashInfo) { 9207 ProcessRecord r = findAppProcess(app, "Crash"); 9208 final String processName = app == null ? "system_server" 9209 : (r == null ? "unknown" : r.processName); 9210 9211 handleApplicationCrashInner("crash", r, processName, crashInfo); 9212 } 9213 9214 /* Native crash reporting uses this inner version because it needs to be somewhat 9215 * decoupled from the AM-managed cleanup lifecycle 9216 */ handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)9217 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 9218 ApplicationErrorReport.CrashInfo crashInfo) { 9219 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(), 9220 UserHandle.getUserId(Binder.getCallingUid()), processName, 9221 r == null ? -1 : r.info.flags, 9222 crashInfo.exceptionClassName, 9223 crashInfo.exceptionMessage, 9224 crashInfo.throwFileName, 9225 crashInfo.throwLineNumber); 9226 9227 StatsLog.write(StatsLog.APP_CRASH_OCCURRED, 9228 Binder.getCallingUid(), 9229 eventType, 9230 processName, 9231 Binder.getCallingPid(), 9232 (r != null && r.info != null) ? r.info.packageName : "", 9233 (r != null && r.info != null) ? (r.info.isInstantApp() 9234 ? StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE 9235 : StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE) 9236 : StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE, 9237 r != null ? (r.isInterestingToUserLocked() 9238 ? StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND 9239 : StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND) 9240 : StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN, 9241 processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER 9242 : (r != null) ? r.getProcessClassEnum() 9243 : ServerProtoEnums.ERROR_SOURCE_UNKNOWN 9244 ); 9245 9246 final int relaunchReason = r == null ? RELAUNCH_REASON_NONE 9247 : r.getWindowProcessController().computeRelaunchReason(); 9248 final String relaunchReasonString = relaunchReasonToString(relaunchReason); 9249 if (crashInfo.crashTag == null) { 9250 crashInfo.crashTag = relaunchReasonString; 9251 } else { 9252 crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString; 9253 } 9254 9255 addErrorToDropBox( 9256 eventType, r, processName, null, null, null, null, null, null, crashInfo); 9257 9258 mAppErrors.crashApplication(r, crashInfo); 9259 } 9260 handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)9261 public void handleApplicationStrictModeViolation( 9262 IBinder app, 9263 int penaltyMask, 9264 StrictMode.ViolationInfo info) { 9265 // We're okay if the ProcessRecord is missing; it probably means that 9266 // we're reporting a violation from the system process itself. 9267 final ProcessRecord r = findAppProcess(app, "StrictMode"); 9268 9269 if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) { 9270 Integer stackFingerprint = info.hashCode(); 9271 boolean logIt = true; 9272 synchronized (mAlreadyLoggedViolatedStacks) { 9273 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 9274 logIt = false; 9275 // TODO: sub-sample into EventLog for these, with 9276 // the info.durationMillis? Then we'd get 9277 // the relative pain numbers, without logging all 9278 // the stack traces repeatedly. We'd want to do 9279 // likewise in the client code, which also does 9280 // dup suppression, before the Binder call. 9281 } else { 9282 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 9283 mAlreadyLoggedViolatedStacks.clear(); 9284 } 9285 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 9286 } 9287 } 9288 if (logIt) { 9289 logStrictModeViolationToDropBox(r, info); 9290 } 9291 } 9292 9293 if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) { 9294 AppErrorResult result = new AppErrorResult(); 9295 synchronized (this) { 9296 final long origId = Binder.clearCallingIdentity(); 9297 9298 Message msg = Message.obtain(); 9299 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG; 9300 HashMap<String, Object> data = new HashMap<String, Object>(); 9301 data.put("result", result); 9302 data.put("app", r); 9303 data.put("info", info); 9304 msg.obj = data; 9305 mUiHandler.sendMessage(msg); 9306 9307 Binder.restoreCallingIdentity(origId); 9308 } 9309 int res = result.get(); 9310 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 9311 } 9312 } 9313 9314 // Depending on the policy in effect, there could be a bunch of 9315 // these in quick succession so we try to batch these together to 9316 // minimize disk writes, number of dropbox entries, and maximize 9317 // compression, by having more fewer, larger records. logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)9318 private void logStrictModeViolationToDropBox( 9319 ProcessRecord process, 9320 StrictMode.ViolationInfo info) { 9321 if (info == null) { 9322 return; 9323 } 9324 final boolean isSystemApp = process == null || 9325 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 9326 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 9327 final String processName = process == null ? "unknown" : process.processName; 9328 final DropBoxManager dbox = (DropBoxManager) 9329 mContext.getSystemService(Context.DROPBOX_SERVICE); 9330 9331 // Exit early if the dropbox isn't configured to accept this report type. 9332 final String dropboxTag = processClass(process) + "_strictmode"; 9333 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 9334 9335 final StringBuilder sb = new StringBuilder(1024); 9336 synchronized (sb) { 9337 appendDropBoxProcessHeaders(process, processName, sb); 9338 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 9339 sb.append("System-App: ").append(isSystemApp).append("\n"); 9340 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 9341 if (info.violationNumThisLoop != 0) { 9342 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 9343 } 9344 if (info.numAnimationsRunning != 0) { 9345 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 9346 } 9347 if (info.broadcastIntentAction != null) { 9348 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n"); 9349 } 9350 if (info.durationMillis != -1) { 9351 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 9352 } 9353 if (info.numInstances != -1) { 9354 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 9355 } 9356 if (info.tags != null) { 9357 for (String tag : info.tags) { 9358 sb.append("Span-Tag: ").append(tag).append("\n"); 9359 } 9360 } 9361 sb.append("\n"); 9362 sb.append(info.getStackTrace()); 9363 sb.append("\n"); 9364 if (info.getViolationDetails() != null) { 9365 sb.append(info.getViolationDetails()); 9366 sb.append("\n"); 9367 } 9368 } 9369 9370 final String res = sb.toString(); 9371 IoThread.getHandler().post(() -> { 9372 dbox.addText(dropboxTag, res); 9373 }); 9374 } 9375 9376 /** 9377 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 9378 * @param app object of the crashing app, null for the system server 9379 * @param tag reported by the caller 9380 * @param system whether this wtf is coming from the system 9381 * @param crashInfo describing the context of the error 9382 * @return true if the process should exit immediately (WTF is fatal) 9383 */ handleApplicationWtf(final IBinder app, final String tag, boolean system, final ApplicationErrorReport.ParcelableCrashInfo crashInfo)9384 public boolean handleApplicationWtf(final IBinder app, final String tag, boolean system, 9385 final ApplicationErrorReport.ParcelableCrashInfo crashInfo) { 9386 final int callingUid = Binder.getCallingUid(); 9387 final int callingPid = Binder.getCallingPid(); 9388 9389 if (system) { 9390 // If this is coming from the system, we could very well have low-level 9391 // system locks held, so we want to do this all asynchronously. And we 9392 // never want this to become fatal, so there is that too. 9393 mHandler.post(new Runnable() { 9394 @Override public void run() { 9395 handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo); 9396 } 9397 }); 9398 return false; 9399 } 9400 9401 final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag, 9402 crashInfo); 9403 9404 final boolean isFatal = Build.IS_ENG || Settings.Global 9405 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0; 9406 final boolean isSystem = (r == null) || r.isPersistent(); 9407 9408 if (isFatal && !isSystem) { 9409 mAppErrors.crashApplication(r, crashInfo); 9410 return true; 9411 } else { 9412 return false; 9413 } 9414 } 9415 handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag, final ApplicationErrorReport.CrashInfo crashInfo)9416 ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag, 9417 final ApplicationErrorReport.CrashInfo crashInfo) { 9418 final ProcessRecord r = findAppProcess(app, "WTF"); 9419 final String processName = app == null ? "system_server" 9420 : (r == null ? "unknown" : r.processName); 9421 9422 EventLog.writeEvent(EventLogTags.AM_WTF, UserHandle.getUserId(callingUid), callingPid, 9423 processName, r == null ? -1 : r.info.flags, tag, crashInfo.exceptionMessage); 9424 9425 StatsLog.write(StatsLog.WTF_OCCURRED, callingUid, tag, processName, 9426 callingPid, (r != null) ? r.getProcessClassEnum() : 0); 9427 9428 addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo); 9429 9430 return r; 9431 } 9432 9433 /** 9434 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 9435 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 9436 */ findAppProcess(IBinder app, String reason)9437 private ProcessRecord findAppProcess(IBinder app, String reason) { 9438 if (app == null) { 9439 return null; 9440 } 9441 9442 synchronized (this) { 9443 return mProcessList.findAppProcessLocked(app, reason); 9444 } 9445 } 9446 9447 /** 9448 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 9449 * to append various headers to the dropbox log text. 9450 */ appendDropBoxProcessHeaders(ProcessRecord process, String processName, StringBuilder sb)9451 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 9452 StringBuilder sb) { 9453 // Watchdog thread ends up invoking this function (with 9454 // a null ProcessRecord) to add the stack file to dropbox. 9455 // Do not acquire a lock on this (am) in such cases, as it 9456 // could cause a potential deadlock, if and when watchdog 9457 // is invoked due to unavailability of lock on am and it 9458 // would prevent watchdog from killing system_server. 9459 if (process == null) { 9460 sb.append("Process: ").append(processName).append("\n"); 9461 return; 9462 } 9463 // Note: ProcessRecord 'process' is guarded by the service 9464 // instance. (notably process.pkgList, which could otherwise change 9465 // concurrently during execution of this method) 9466 synchronized (this) { 9467 sb.append("Process: ").append(processName).append("\n"); 9468 sb.append("PID: ").append(process.pid).append("\n"); 9469 sb.append("UID: ").append(process.uid).append("\n"); 9470 int flags = process.info.flags; 9471 IPackageManager pm = AppGlobals.getPackageManager(); 9472 sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n"); 9473 for (int ip=0; ip<process.pkgList.size(); ip++) { 9474 String pkg = process.pkgList.keyAt(ip); 9475 sb.append("Package: ").append(pkg); 9476 try { 9477 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId()); 9478 if (pi != null) { 9479 sb.append(" v").append(pi.getLongVersionCode()); 9480 if (pi.versionName != null) { 9481 sb.append(" (").append(pi.versionName).append(")"); 9482 } 9483 } 9484 } catch (RemoteException e) { 9485 Slog.e(TAG, "Error getting package info: " + pkg, e); 9486 } 9487 sb.append("\n"); 9488 } 9489 if (process.info.isInstantApp()) { 9490 sb.append("Instant-App: true\n"); 9491 } 9492 } 9493 } 9494 processClass(ProcessRecord process)9495 private static String processClass(ProcessRecord process) { 9496 if (process == null || process.pid == MY_PID) { 9497 return "system_server"; 9498 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9499 return "system_app"; 9500 } else { 9501 return "data_app"; 9502 } 9503 } 9504 9505 private volatile long mWtfClusterStart; 9506 private volatile int mWtfClusterCount; 9507 9508 /** 9509 * Write a description of an error (crash, WTF, ANR) to the drop box. 9510 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 9511 * @param process which caused the error, null means the system server 9512 * @param activityShortComponentName which triggered the error, null if unknown 9513 * @param parentShortComponentName activity related to the error, null if unknown 9514 * @param parentProcess parent process 9515 * @param subject line related to the error, null if absent 9516 * @param report in long form describing the error, null if absent 9517 * @param dataFile text file to include in the report, null if none 9518 * @param crashInfo giving an application stack trace, null if absent 9519 */ addErrorToDropBox(String eventType, ProcessRecord process, String processName, String activityShortComponentName, String parentShortComponentName, ProcessRecord parentProcess, String subject, final String report, final File dataFile, final ApplicationErrorReport.CrashInfo crashInfo)9520 public void addErrorToDropBox(String eventType, 9521 ProcessRecord process, String processName, String activityShortComponentName, 9522 String parentShortComponentName, ProcessRecord parentProcess, 9523 String subject, final String report, final File dataFile, 9524 final ApplicationErrorReport.CrashInfo crashInfo) { 9525 // NOTE -- this must never acquire the ActivityManagerService lock, 9526 // otherwise the watchdog may be prevented from resetting the system. 9527 9528 // Bail early if not published yet 9529 if (ServiceManager.getService(Context.DROPBOX_SERVICE) == null) return; 9530 final DropBoxManager dbox = mContext.getSystemService(DropBoxManager.class); 9531 9532 // Exit early if the dropbox isn't configured to accept this report type. 9533 final String dropboxTag = processClass(process) + "_" + eventType; 9534 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 9535 9536 // Rate-limit how often we're willing to do the heavy lifting below to 9537 // collect and record logs; currently 5 logs per 10 second period. 9538 final long now = SystemClock.elapsedRealtime(); 9539 if (now - mWtfClusterStart > 10 * DateUtils.SECOND_IN_MILLIS) { 9540 mWtfClusterStart = now; 9541 mWtfClusterCount = 1; 9542 } else { 9543 if (mWtfClusterCount++ >= 5) return; 9544 } 9545 9546 final StringBuilder sb = new StringBuilder(1024); 9547 appendDropBoxProcessHeaders(process, processName, sb); 9548 if (process != null) { 9549 sb.append("Foreground: ") 9550 .append(process.isInterestingToUserLocked() ? "Yes" : "No") 9551 .append("\n"); 9552 } 9553 if (activityShortComponentName != null) { 9554 sb.append("Activity: ").append(activityShortComponentName).append("\n"); 9555 } 9556 if (parentShortComponentName != null) { 9557 if (parentProcess != null && parentProcess.pid != process.pid) { 9558 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n"); 9559 } 9560 if (!parentShortComponentName.equals(activityShortComponentName)) { 9561 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n"); 9562 } 9563 } 9564 if (subject != null) { 9565 sb.append("Subject: ").append(subject).append("\n"); 9566 } 9567 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 9568 if (Debug.isDebuggerConnected()) { 9569 sb.append("Debugger: Connected\n"); 9570 } 9571 if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) { 9572 sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n"); 9573 } 9574 sb.append("\n"); 9575 9576 // Do the rest in a worker thread to avoid blocking the caller on I/O 9577 // (After this point, we shouldn't access AMS internal data structures.) 9578 Thread worker = new Thread("Error dump: " + dropboxTag) { 9579 @Override 9580 public void run() { 9581 if (report != null) { 9582 sb.append(report); 9583 } 9584 9585 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 9586 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0); 9587 int maxDataFileSize = DROPBOX_MAX_SIZE - sb.length() 9588 - lines * RESERVED_BYTES_PER_LOGCAT_LINE; 9589 9590 if (dataFile != null && maxDataFileSize > 0) { 9591 try { 9592 sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize, 9593 "\n\n[[TRUNCATED]]")); 9594 } catch (IOException e) { 9595 Slog.e(TAG, "Error reading " + dataFile, e); 9596 } 9597 } 9598 if (crashInfo != null && crashInfo.stackTrace != null) { 9599 sb.append(crashInfo.stackTrace); 9600 } 9601 9602 if (lines > 0) { 9603 sb.append("\n"); 9604 9605 // Merge several logcat streams, and take the last N lines 9606 InputStreamReader input = null; 9607 try { 9608 java.lang.Process logcat = new ProcessBuilder( 9609 "/system/bin/timeout", "-k", "15s", "10s", 9610 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system", 9611 "-b", "main", "-b", "crash", "-t", String.valueOf(lines)) 9612 .redirectErrorStream(true).start(); 9613 9614 try { logcat.getOutputStream().close(); } catch (IOException e) {} 9615 try { logcat.getErrorStream().close(); } catch (IOException e) {} 9616 input = new InputStreamReader(logcat.getInputStream()); 9617 9618 int num; 9619 char[] buf = new char[8192]; 9620 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num); 9621 } catch (IOException e) { 9622 Slog.e(TAG, "Error running logcat", e); 9623 } finally { 9624 if (input != null) try { input.close(); } catch (IOException e) {} 9625 } 9626 } 9627 9628 dbox.addText(dropboxTag, sb.toString()); 9629 } 9630 }; 9631 9632 if (process == null) { 9633 // If process is null, we are being called from some internal code 9634 // and may be about to die -- run this synchronously. 9635 final int oldMask = StrictMode.allowThreadDiskWritesMask(); 9636 try { 9637 worker.run(); 9638 } finally { 9639 StrictMode.setThreadPolicyMask(oldMask); 9640 } 9641 } else { 9642 worker.start(); 9643 } 9644 } 9645 9646 @Override getProcessesInErrorState()9647 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 9648 enforceNotIsolatedCaller("getProcessesInErrorState"); 9649 // assume our apps are happy - lazy create the list 9650 List<ActivityManager.ProcessErrorStateInfo> errList = null; 9651 9652 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 9653 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 9654 int userId = UserHandle.getUserId(Binder.getCallingUid()); 9655 9656 synchronized (this) { 9657 9658 // iterate across all processes 9659 for (int i=mProcessList.mLruProcesses.size()-1; i>=0; i--) { 9660 ProcessRecord app = mProcessList.mLruProcesses.get(i); 9661 if (!allUsers && app.userId != userId) { 9662 continue; 9663 } 9664 final boolean crashing = app.isCrashing(); 9665 final boolean notResponding = app.isNotResponding(); 9666 if ((app.thread != null) && (crashing || notResponding)) { 9667 // This one's in trouble, so we'll generate a report for it 9668 // crashes are higher priority (in case there's a crash *and* an anr) 9669 ActivityManager.ProcessErrorStateInfo report = null; 9670 if (crashing) { 9671 report = app.crashingReport; 9672 } else if (notResponding) { 9673 report = app.notRespondingReport; 9674 } 9675 9676 if (report != null) { 9677 if (errList == null) { 9678 errList = new ArrayList<>(1); 9679 } 9680 errList.add(report); 9681 } else { 9682 Slog.w(TAG, "Missing app error report, app = " + app.processName + 9683 " crashing = " + crashing + 9684 " notResponding = " + notResponding); 9685 } 9686 } 9687 } 9688 } 9689 9690 return errList; 9691 } 9692 9693 @Override getRunningAppProcesses()9694 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 9695 enforceNotIsolatedCaller("getRunningAppProcesses"); 9696 9697 final int callingUid = Binder.getCallingUid(); 9698 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 9699 9700 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 9701 callingUid) == PackageManager.PERMISSION_GRANTED; 9702 final int userId = UserHandle.getUserId(callingUid); 9703 final boolean allUids = mAtmInternal.isGetTasksAllowed( 9704 "getRunningAppProcesses", Binder.getCallingPid(), callingUid); 9705 9706 synchronized (this) { 9707 // Iterate across all processes 9708 return mProcessList.getRunningAppProcessesLocked(allUsers, userId, allUids, 9709 callingUid, clientTargetSdk); 9710 } 9711 } 9712 9713 @Override getRunningExternalApplications()9714 public List<ApplicationInfo> getRunningExternalApplications() { 9715 enforceNotIsolatedCaller("getRunningExternalApplications"); 9716 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 9717 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 9718 if (runningApps != null && runningApps.size() > 0) { 9719 Set<String> extList = new HashSet<String>(); 9720 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 9721 if (app.pkgList != null) { 9722 for (String pkg : app.pkgList) { 9723 extList.add(pkg); 9724 } 9725 } 9726 } 9727 IPackageManager pm = AppGlobals.getPackageManager(); 9728 for (String pkg : extList) { 9729 try { 9730 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 9731 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 9732 retList.add(info); 9733 } 9734 } catch (RemoteException e) { 9735 } 9736 } 9737 } 9738 return retList; 9739 } 9740 9741 @Override getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)9742 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) { 9743 if (outState == null) { 9744 throw new IllegalArgumentException("outState is null"); 9745 } 9746 enforceNotIsolatedCaller("getMyMemoryState"); 9747 9748 final int callingUid = Binder.getCallingUid(); 9749 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 9750 9751 synchronized (this) { 9752 ProcessRecord proc; 9753 synchronized (mPidsSelfLocked) { 9754 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 9755 } 9756 if (proc != null) { 9757 mProcessList.fillInProcMemInfoLocked(proc, outState, clientTargetSdk); 9758 } 9759 } 9760 } 9761 9762 @Override getMemoryTrimLevel()9763 public int getMemoryTrimLevel() { 9764 enforceNotIsolatedCaller("getMyMemoryState"); 9765 synchronized (this) { 9766 return mLastMemoryLevel; 9767 } 9768 } 9769 9770 @Override onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)9771 public void onShellCommand(FileDescriptor in, FileDescriptor out, 9772 FileDescriptor err, String[] args, ShellCallback callback, 9773 ResultReceiver resultReceiver) { 9774 (new ActivityManagerShellCommand(this, false)).exec( 9775 this, in, out, err, args, callback, resultReceiver); 9776 } 9777 9778 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)9779 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9780 PriorityDump.dump(mPriorityDumper, fd, pw, args); 9781 } 9782 dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId)9783 private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, 9784 boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, 9785 int dumpAppId) { 9786 9787 ActiveServices.ServiceDumper sdumper; 9788 9789 synchronized(this) { 9790 mConstants.dump(pw); 9791 mOomAdjuster.dumpAppCompactorSettings(pw); 9792 pw.println(); 9793 if (dumpAll) { 9794 pw.println("-------------------------------------------------------------------------------"); 9795 9796 } 9797 dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9798 pw.println(); 9799 if (dumpAll) { 9800 pw.println("-------------------------------------------------------------------------------"); 9801 9802 } 9803 mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage); 9804 pw.println(); 9805 if (dumpAll) { 9806 pw.println("-------------------------------------------------------------------------------"); 9807 } 9808 dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9809 pw.println(); 9810 if (dumpAll) { 9811 pw.println("-------------------------------------------------------------------------------"); 9812 } 9813 if (dumpAll || dumpPackage != null) { 9814 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9815 pw.println(); 9816 if (dumpAll) { 9817 pw.println("-------------------------------------------------------------------------------"); 9818 } 9819 } 9820 dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9821 pw.println(); 9822 if (dumpAll) { 9823 pw.println("-------------------------------------------------------------------------------"); 9824 } 9825 dumpPermissionsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9826 pw.println(); 9827 sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9828 if (!dumpClient) { 9829 if (dumpAll) { 9830 pw.println("-------------------------------------------------------------------------------"); 9831 } 9832 sdumper.dumpLocked(); 9833 } 9834 } 9835 // We drop the lock here because we can't call dumpWithClient() with the lock held; 9836 // if the caller wants a consistent state for the !dumpClient case, it can call this 9837 // method with the lock held. 9838 if (dumpClient) { 9839 if (dumpAll) { 9840 pw.println("-------------------------------------------------------------------------------"); 9841 } 9842 sdumper.dumpWithClient(); 9843 } 9844 if (dumpPackage == null) { 9845 // Intentionally dropping the lock for this, because dumpBinderProxies() will make many 9846 // outgoing binder calls to retrieve interface descriptors; while that is system code, 9847 // there is nothing preventing an app from overriding this implementation by talking to 9848 // the binder driver directly, and hang up system_server in the process. So, dump 9849 // without locks held, and even then only when there is an unreasonably large number of 9850 // proxies in the first place. 9851 pw.println(); 9852 if (dumpAll) { 9853 pw.println("-------------------------------------------------------------------------------"); 9854 } 9855 dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */); 9856 } 9857 synchronized(this) { 9858 pw.println(); 9859 if (dumpAll) { 9860 pw.println("-------------------------------------------------------------------------------"); 9861 } 9862 mAtmInternal.dump( 9863 DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9864 pw.println(); 9865 if (dumpAll) { 9866 pw.println("-------------------------------------------------------------------------------"); 9867 } 9868 mAtmInternal.dump( 9869 DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9870 pw.println(); 9871 if (dumpAll) { 9872 pw.println("-------------------------------------------------------------------------------"); 9873 } 9874 mAtmInternal.dump( 9875 DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9876 pw.println(); 9877 if (dumpAll) { 9878 pw.println("-------------------------------------------------------------------------------"); 9879 } 9880 mAtmInternal.dump( 9881 DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9882 // Activities section is dumped as part of the Critical priority dump. Exclude the 9883 // section if priority is Normal. 9884 if (!dumpNormalPriority) { 9885 pw.println(); 9886 if (dumpAll) { 9887 pw.println("-------------------------------------------------------------------------------"); 9888 } 9889 mAtmInternal.dump( 9890 DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9891 } 9892 if (mAssociations.size() > 0) { 9893 pw.println(); 9894 if (dumpAll) { 9895 pw.println("-------------------------------------------------------------------------------"); 9896 } 9897 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9898 } 9899 if (dumpPackage == null) { 9900 pw.println(); 9901 if (dumpAll) { 9902 pw.println("-------------------------------------------------------------------------------"); 9903 } 9904 mOomAdjProfiler.dump(pw); 9905 pw.println(); 9906 if (dumpAll) { 9907 pw.println("-------------------------------------------------------------------------------"); 9908 } 9909 dumpLmkLocked(pw); 9910 } 9911 pw.println(); 9912 if (dumpAll) { 9913 pw.println("-------------------------------------------------------------------------------"); 9914 } 9915 dumpLruLocked(pw, dumpPackage); 9916 pw.println(); 9917 if (dumpAll) { 9918 pw.println("-------------------------------------------------------------------------------"); 9919 } 9920 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId); 9921 } 9922 } 9923 9924 /** 9925 * Wrapper function to print out debug data filtered by specified arguments. 9926 */ doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)9927 private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) { 9928 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 9929 9930 boolean dumpAll = false; 9931 boolean dumpClient = false; 9932 boolean dumpCheckin = false; 9933 boolean dumpCheckinFormat = false; 9934 boolean dumpNormalPriority = false; 9935 boolean dumpVisibleStacksOnly = false; 9936 boolean dumpFocusedStackOnly = false; 9937 String dumpPackage = null; 9938 9939 int opti = 0; 9940 while (opti < args.length) { 9941 String opt = args[opti]; 9942 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 9943 break; 9944 } 9945 opti++; 9946 if ("-a".equals(opt)) { 9947 dumpAll = true; 9948 } else if ("-c".equals(opt)) { 9949 dumpClient = true; 9950 } else if ("-v".equals(opt)) { 9951 dumpVisibleStacksOnly = true; 9952 } else if ("-f".equals(opt)) { 9953 dumpFocusedStackOnly = true; 9954 } else if ("-p".equals(opt)) { 9955 if (opti < args.length) { 9956 dumpPackage = args[opti]; 9957 opti++; 9958 } else { 9959 pw.println("Error: -p option requires package argument"); 9960 return; 9961 } 9962 dumpClient = true; 9963 } else if ("--checkin".equals(opt)) { 9964 dumpCheckin = dumpCheckinFormat = true; 9965 } else if ("-C".equals(opt)) { 9966 dumpCheckinFormat = true; 9967 } else if ("--normal-priority".equals(opt)) { 9968 dumpNormalPriority = true; 9969 } else if ("-h".equals(opt)) { 9970 ActivityManagerShellCommand.dumpHelp(pw, true); 9971 return; 9972 } else { 9973 pw.println("Unknown argument: " + opt + "; use -h for help"); 9974 } 9975 } 9976 9977 long origId = Binder.clearCallingIdentity(); 9978 9979 if (useProto) { 9980 final ProtoOutputStream proto = new ProtoOutputStream(fd); 9981 String cmd = opti < args.length ? args[opti] : ""; 9982 opti++; 9983 9984 if ("activities".equals(cmd) || "a".equals(cmd)) { 9985 // output proto is ActivityManagerServiceDumpActivitiesProto 9986 mAtmInternal.writeActivitiesToProto(proto); 9987 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 9988 // output proto is ActivityManagerServiceDumpBroadcastsProto 9989 synchronized (this) { 9990 writeBroadcastsToProtoLocked(proto); 9991 } 9992 } else if ("provider".equals(cmd)) { 9993 String[] newArgs; 9994 String name; 9995 if (opti >= args.length) { 9996 name = null; 9997 newArgs = EMPTY_STRING_ARRAY; 9998 } else { 9999 name = args[opti]; 10000 opti++; 10001 newArgs = new String[args.length - opti]; 10002 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10003 args.length - opti); 10004 } 10005 if (!dumpProviderProto(fd, pw, name, newArgs)) { 10006 pw.println("No providers match: " + name); 10007 pw.println("Use -h for help."); 10008 } 10009 } else if ("service".equals(cmd)) { 10010 // output proto is ActivityManagerServiceDumpServicesProto 10011 mServices.writeToProto(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 10012 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 10013 if (opti < args.length) { 10014 dumpPackage = args[opti]; 10015 opti++; 10016 } 10017 // output proto is ProcessProto 10018 synchronized (this) { 10019 writeProcessesToProtoLocked(proto, dumpPackage); 10020 } 10021 } else { 10022 // default option, dump everything, output is ActivityManagerServiceProto 10023 synchronized (this) { 10024 long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES); 10025 mAtmInternal.writeActivitiesToProto(proto); 10026 proto.end(activityToken); 10027 10028 long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS); 10029 writeBroadcastsToProtoLocked(proto); 10030 proto.end(broadcastToken); 10031 10032 long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES); 10033 mServices.writeToProto(proto, 10034 ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 10035 proto.end(serviceToken); 10036 10037 long processToken = proto.start(ActivityManagerServiceProto.PROCESSES); 10038 writeProcessesToProtoLocked(proto, dumpPackage); 10039 proto.end(processToken); 10040 } 10041 } 10042 proto.flush(); 10043 Binder.restoreCallingIdentity(origId); 10044 return; 10045 } 10046 10047 int dumpAppId = getAppId(dumpPackage); 10048 boolean more = false; 10049 // Is the caller requesting to dump a particular piece of data? 10050 if (opti < args.length) { 10051 String cmd = args[opti]; 10052 opti++; 10053 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd) 10054 || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd) 10055 || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd) 10056 || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) { 10057 mAtmInternal.dump( 10058 cmd, fd, pw, args, opti, true /* dumpAll */, dumpClient, dumpPackage); 10059 } else if ("binder-proxies".equals(cmd)) { 10060 if (opti >= args.length) { 10061 dumpBinderProxies(pw, 0 /* minToDump */); 10062 } else { 10063 String uid = args[opti]; 10064 opti++; 10065 // Ensure Binder Proxy Count is as up to date as possible 10066 System.gc(); 10067 System.runFinalization(); 10068 System.gc(); 10069 pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid))); 10070 } 10071 } else if ("allowed-associations".equals(cmd)) { 10072 if (opti < args.length) { 10073 dumpPackage = args[opti]; 10074 opti++; 10075 } 10076 synchronized (this) { 10077 dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage); 10078 } 10079 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 10080 if (opti < args.length) { 10081 dumpPackage = args[opti]; 10082 opti++; 10083 } 10084 synchronized (this) { 10085 dumpBroadcastsLocked(fd, pw, args, opti, true, dumpPackage); 10086 } 10087 } else if ("broadcast-stats".equals(cmd)) { 10088 if (opti < args.length) { 10089 dumpPackage = args[opti]; 10090 opti++; 10091 } 10092 synchronized (this) { 10093 if (dumpCheckinFormat) { 10094 dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, 10095 dumpPackage); 10096 } else { 10097 dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage); 10098 } 10099 } 10100 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 10101 if (opti < args.length) { 10102 dumpPackage = args[opti]; 10103 opti++; 10104 } 10105 synchronized (this) { 10106 mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage); 10107 } 10108 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 10109 if (opti < args.length) { 10110 dumpPackage = args[opti]; 10111 opti++; 10112 } 10113 synchronized (this) { 10114 dumpProcessesLocked(fd, pw, args, opti, true, dumpPackage, dumpAppId); 10115 } 10116 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 10117 synchronized (this) { 10118 dumpOomLocked(fd, pw, args, opti, true); 10119 } 10120 } else if ("lmk".equals(cmd)) { 10121 synchronized (this) { 10122 dumpLmkLocked(pw); 10123 } 10124 } else if ("lru".equals(cmd)) { 10125 synchronized (this) { 10126 dumpLruLocked(pw, null); 10127 } 10128 } else if ("permissions".equals(cmd) || "perm".equals(cmd)) { 10129 synchronized (this) { 10130 dumpPermissionsLocked(fd, pw, args, opti, true, null); 10131 } 10132 } else if ("provider".equals(cmd)) { 10133 String[] newArgs; 10134 String name; 10135 if (opti >= args.length) { 10136 name = null; 10137 newArgs = EMPTY_STRING_ARRAY; 10138 } else { 10139 name = args[opti]; 10140 opti++; 10141 newArgs = new String[args.length - opti]; 10142 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti); 10143 } 10144 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 10145 pw.println("No providers match: " + name); 10146 pw.println("Use -h for help."); 10147 } 10148 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 10149 synchronized (this) { 10150 dumpProvidersLocked(fd, pw, args, opti, true, null); 10151 } 10152 } else if ("service".equals(cmd)) { 10153 String[] newArgs; 10154 String name; 10155 if (opti >= args.length) { 10156 name = null; 10157 newArgs = EMPTY_STRING_ARRAY; 10158 } else { 10159 name = args[opti]; 10160 opti++; 10161 newArgs = new String[args.length - opti]; 10162 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10163 args.length - opti); 10164 } 10165 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) { 10166 pw.println("No services match: " + name); 10167 pw.println("Use -h for help."); 10168 } 10169 } else if ("package".equals(cmd)) { 10170 String[] newArgs; 10171 if (opti >= args.length) { 10172 pw.println("package: no package name specified"); 10173 pw.println("Use -h for help."); 10174 } else { 10175 dumpPackage = args[opti]; 10176 opti++; 10177 newArgs = new String[args.length - opti]; 10178 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10179 args.length - opti); 10180 args = newArgs; 10181 opti = 0; 10182 more = true; 10183 } 10184 } else if ("associations".equals(cmd) || "as".equals(cmd)) { 10185 synchronized (this) { 10186 dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage); 10187 } 10188 } else if ("settings".equals(cmd)) { 10189 synchronized (this) { 10190 mConstants.dump(pw); 10191 mOomAdjuster.dumpAppCompactorSettings(pw); 10192 } 10193 } else if ("services".equals(cmd) || "s".equals(cmd)) { 10194 if (dumpClient) { 10195 ActiveServices.ServiceDumper dumper; 10196 synchronized (this) { 10197 dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true, 10198 dumpPackage); 10199 } 10200 dumper.dumpWithClient(); 10201 } else { 10202 synchronized (this) { 10203 mServices.newServiceDumperLocked(fd, pw, args, opti, true, 10204 dumpPackage).dumpLocked(); 10205 } 10206 } 10207 } else if ("locks".equals(cmd)) { 10208 LockGuard.dump(fd, pw, args); 10209 } else { 10210 // Dumping a single activity? 10211 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll, 10212 dumpVisibleStacksOnly, dumpFocusedStackOnly)) { 10213 ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true); 10214 int res = shell.exec(this, null, fd, null, args, null, 10215 new ResultReceiver(null)); 10216 if (res < 0) { 10217 pw.println("Bad activity command, or no activities match: " + cmd); 10218 pw.println("Use -h for help."); 10219 } 10220 } 10221 } 10222 if (!more) { 10223 Binder.restoreCallingIdentity(origId); 10224 return; 10225 } 10226 } 10227 10228 // No piece of data specified, dump everything. 10229 if (dumpCheckinFormat) { 10230 dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage); 10231 } else { 10232 if (dumpClient) { 10233 // dumpEverything() will take the lock when needed, and momentarily drop 10234 // it for dumping client state. 10235 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient, 10236 dumpNormalPriority, dumpAppId); 10237 } else { 10238 // Take the lock here, so we get a consistent state for the entire dump; 10239 // dumpEverything() will take the lock as well, but that is fine. 10240 synchronized(this) { 10241 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient, 10242 dumpNormalPriority, dumpAppId); 10243 } 10244 } 10245 } 10246 Binder.restoreCallingIdentity(origId); 10247 } 10248 dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)10249 void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 10250 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 10251 pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)"); 10252 10253 int dumpUid = 0; 10254 if (dumpPackage != null) { 10255 IPackageManager pm = AppGlobals.getPackageManager(); 10256 try { 10257 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0); 10258 } catch (RemoteException e) { 10259 } 10260 } 10261 10262 boolean printedAnything = false; 10263 10264 final long now = SystemClock.uptimeMillis(); 10265 10266 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 10267 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 10268 = mAssociations.valueAt(i1); 10269 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 10270 SparseArray<ArrayMap<String, Association>> sourceUids 10271 = targetComponents.valueAt(i2); 10272 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) { 10273 ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3); 10274 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 10275 Association ass = sourceProcesses.valueAt(i4); 10276 if (dumpPackage != null) { 10277 if (!ass.mTargetComponent.getPackageName().equals(dumpPackage) 10278 && UserHandle.getAppId(ass.mSourceUid) != dumpUid) { 10279 continue; 10280 } 10281 } 10282 printedAnything = true; 10283 pw.print(" "); 10284 pw.print(ass.mTargetProcess); 10285 pw.print("/"); 10286 UserHandle.formatUid(pw, ass.mTargetUid); 10287 pw.print(" <- "); 10288 pw.print(ass.mSourceProcess); 10289 pw.print("/"); 10290 UserHandle.formatUid(pw, ass.mSourceUid); 10291 pw.println(); 10292 pw.print(" via "); 10293 pw.print(ass.mTargetComponent.flattenToShortString()); 10294 pw.println(); 10295 pw.print(" "); 10296 long dur = ass.mTime; 10297 if (ass.mNesting > 0) { 10298 dur += now - ass.mStartTime; 10299 } 10300 TimeUtils.formatDuration(dur, pw); 10301 pw.print(" ("); 10302 pw.print(ass.mCount); 10303 pw.print(" times)"); 10304 pw.print(" "); 10305 for (int i=0; i<ass.mStateTimes.length; i++) { 10306 long amt = ass.mStateTimes[i]; 10307 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 10308 amt += now - ass.mLastStateUptime; 10309 } 10310 if (amt != 0) { 10311 pw.print(" "); 10312 pw.print(ProcessList.makeProcStateString( 10313 i + ActivityManager.MIN_PROCESS_STATE)); 10314 pw.print("="); 10315 TimeUtils.formatDuration(amt, pw); 10316 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 10317 pw.print("*"); 10318 } 10319 } 10320 } 10321 pw.println(); 10322 if (ass.mNesting > 0) { 10323 pw.print(" Currently active: "); 10324 TimeUtils.formatDuration(now - ass.mStartTime, pw); 10325 pw.println(); 10326 } 10327 } 10328 } 10329 } 10330 10331 } 10332 10333 if (!printedAnything) { 10334 pw.println(" (nothing)"); 10335 } 10336 } 10337 getAppId(String dumpPackage)10338 private int getAppId(String dumpPackage) { 10339 if (dumpPackage != null) { 10340 try { 10341 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 10342 dumpPackage, 0); 10343 return UserHandle.getAppId(info.uid); 10344 } catch (NameNotFoundException e) { 10345 e.printStackTrace(); 10346 } 10347 } 10348 return -1; 10349 } 10350 dumpUids(PrintWriter pw, String dumpPackage, int dumpAppId, ActiveUids uids, String header, boolean needSep)10351 boolean dumpUids(PrintWriter pw, String dumpPackage, int dumpAppId, ActiveUids uids, 10352 String header, boolean needSep) { 10353 boolean printed = false; 10354 for (int i=0; i<uids.size(); i++) { 10355 UidRecord uidRec = uids.valueAt(i); 10356 if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != dumpAppId) { 10357 continue; 10358 } 10359 if (!printed) { 10360 printed = true; 10361 if (needSep) { 10362 pw.println(); 10363 } 10364 pw.print(" "); 10365 pw.println(header); 10366 needSep = true; 10367 } 10368 pw.print(" UID "); UserHandle.formatUid(pw, uidRec.uid); 10369 pw.print(": "); pw.println(uidRec); 10370 } 10371 return printed; 10372 } 10373 dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)10374 void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) { 10375 final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50); 10376 10377 pw.println(header); 10378 for (int i = 0; i < proxyCounts.length; i++) { 10379 pw.println(" #" + (i + 1) + ": " + proxyCounts[i]); 10380 } 10381 } 10382 dumpBinderProxiesCounts(PrintWriter pw, String header)10383 boolean dumpBinderProxiesCounts(PrintWriter pw, String header) { 10384 SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts(); 10385 if(counts != null) { 10386 pw.println(header); 10387 for (int i = 0; i < counts.size(); i++) { 10388 final int uid = counts.keyAt(i); 10389 final int binderCount = counts.valueAt(i); 10390 pw.print(" UID "); 10391 pw.print(uid); 10392 pw.print(", binder count = "); 10393 pw.print(binderCount); 10394 pw.print(", package(s)= "); 10395 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid); 10396 if (pkgNames != null) { 10397 for (int j = 0; j < pkgNames.length; j++) { 10398 pw.print(pkgNames[j]); 10399 pw.print("; "); 10400 } 10401 } else { 10402 pw.print("NO PACKAGE NAME FOUND"); 10403 } 10404 pw.println(); 10405 } 10406 return true; 10407 } 10408 return false; 10409 } 10410 dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)10411 void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) { 10412 pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)"); 10413 final int proxyCount = BinderProxy.getProxyCount(); 10414 if (proxyCount >= minCountToDumpInterfaces) { 10415 dumpBinderProxyInterfaceCounts(pw, 10416 "Top proxy interface names held by SYSTEM"); 10417 } else { 10418 pw.print("Not dumping proxy interface counts because size (" 10419 + Integer.toString(proxyCount) + ") looks reasonable"); 10420 pw.println(); 10421 } 10422 dumpBinderProxiesCounts(pw, 10423 " Counts of Binder Proxies held by SYSTEM"); 10424 } 10425 dumpLruEntryLocked(PrintWriter pw, int index, ProcessRecord proc)10426 void dumpLruEntryLocked(PrintWriter pw, int index, ProcessRecord proc) { 10427 pw.print(" #"); 10428 pw.print(index); 10429 pw.print(": "); 10430 pw.print(ProcessList.makeOomAdjString(proc.setAdj, false)); 10431 pw.print(" "); 10432 pw.print(ProcessList.makeProcStateString(proc.getCurProcState())); 10433 pw.print(" "); 10434 pw.print(proc.toShortString()); 10435 pw.print(" "); 10436 if (proc.hasActivitiesOrRecentTasks() || proc.hasClientActivities() 10437 || proc.treatLikeActivity) { 10438 pw.print(" activity="); 10439 boolean printed = false; 10440 if (proc.hasActivities()) { 10441 pw.print("activities"); 10442 printed = true; 10443 } 10444 if (proc.hasRecentTasks()) { 10445 if (printed) { 10446 pw.print("|"); 10447 } 10448 pw.print("recents"); 10449 printed = true; 10450 } 10451 if (proc.hasClientActivities()) { 10452 if (printed) { 10453 pw.print("|"); 10454 } 10455 pw.print("client"); 10456 printed = true; 10457 } 10458 if (proc.treatLikeActivity) { 10459 if (printed) { 10460 pw.print("|"); 10461 } 10462 pw.print("treated"); 10463 } 10464 } 10465 pw.println(); 10466 } 10467 10468 // TODO: Move to ProcessList? dumpLruLocked(PrintWriter pw, String dumpPackage)10469 void dumpLruLocked(PrintWriter pw, String dumpPackage) { 10470 pw.println("ACTIVITY MANAGER LRU PROCESSES (dumpsys activity lru)"); 10471 final int N = mProcessList.mLruProcesses.size(); 10472 int i; 10473 boolean first = true; 10474 for (i = N - 1; i >= mProcessList.mLruProcessActivityStart; i--) { 10475 final ProcessRecord r = mProcessList.mLruProcesses.get(i); 10476 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 10477 continue; 10478 } 10479 if (first) { 10480 pw.println(" Activities:"); 10481 first = false; 10482 } 10483 dumpLruEntryLocked(pw, i, r); 10484 } 10485 first = true; 10486 for (; i >= mProcessList.mLruProcessServiceStart; i--) { 10487 final ProcessRecord r = mProcessList.mLruProcesses.get(i); 10488 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 10489 continue; 10490 } 10491 if (first) { 10492 pw.println(" Services:"); 10493 first = false; 10494 } 10495 dumpLruEntryLocked(pw, i, r); 10496 } 10497 first = true; 10498 for (; i >= 0; i--) { 10499 final ProcessRecord r = mProcessList.mLruProcesses.get(i); 10500 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 10501 continue; 10502 } 10503 if (first) { 10504 pw.println(" Other:"); 10505 first = false; 10506 } 10507 dumpLruEntryLocked(pw, i, r); 10508 } 10509 } 10510 10511 // TODO: Move to ProcessList? 10512 @GuardedBy("this") dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, int dumpAppId)10513 void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 10514 int opti, boolean dumpAll, String dumpPackage, int dumpAppId) { 10515 boolean needSep = false; 10516 int numPers = 0; 10517 10518 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)"); 10519 10520 if (dumpAll) { 10521 final int NP = mProcessList.mProcessNames.getMap().size(); 10522 for (int ip=0; ip<NP; ip++) { 10523 SparseArray<ProcessRecord> procs = mProcessList.mProcessNames.getMap().valueAt(ip); 10524 final int NA = procs.size(); 10525 for (int ia=0; ia<NA; ia++) { 10526 ProcessRecord r = procs.valueAt(ia); 10527 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 10528 continue; 10529 } 10530 if (!needSep) { 10531 pw.println(" All known processes:"); 10532 needSep = true; 10533 } 10534 pw.print(r.isPersistent() ? " *PERS*" : " *APP*"); 10535 pw.print(" UID "); pw.print(procs.keyAt(ia)); 10536 pw.print(" "); pw.println(r); 10537 r.dump(pw, " "); 10538 if (r.isPersistent()) { 10539 numPers++; 10540 } 10541 } 10542 } 10543 } 10544 10545 if (mProcessList.mIsolatedProcesses.size() > 0) { 10546 boolean printed = false; 10547 for (int i=0; i<mProcessList.mIsolatedProcesses.size(); i++) { 10548 ProcessRecord r = mProcessList.mIsolatedProcesses.valueAt(i); 10549 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 10550 continue; 10551 } 10552 if (!printed) { 10553 if (needSep) { 10554 pw.println(); 10555 } 10556 pw.println(" Isolated process list (sorted by uid):"); 10557 printed = true; 10558 needSep = true; 10559 } 10560 pw.print(" Isolated #"); pw.print(i); pw.print(": "); 10561 pw.println(r); 10562 } 10563 } 10564 10565 if (mActiveInstrumentation.size() > 0) { 10566 boolean printed = false; 10567 for (int i=0; i<mActiveInstrumentation.size(); i++) { 10568 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 10569 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 10570 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 10571 continue; 10572 } 10573 if (!printed) { 10574 if (needSep) { 10575 pw.println(); 10576 } 10577 pw.println(" Active instrumentation:"); 10578 printed = true; 10579 needSep = true; 10580 } 10581 pw.print(" Instrumentation #"); pw.print(i); pw.print(": "); 10582 pw.println(ai); 10583 ai.dump(pw, " "); 10584 } 10585 } 10586 10587 if (mProcessList.mActiveUids.size() > 0) { 10588 if (dumpUids(pw, dumpPackage, dumpAppId, mProcessList.mActiveUids, 10589 "UID states:", needSep)) { 10590 needSep = true; 10591 } 10592 } 10593 10594 if (dumpAll) { 10595 if (mValidateUids.size() > 0) { 10596 if (dumpUids(pw, dumpPackage, dumpAppId, mValidateUids, "UID validation:", 10597 needSep)) { 10598 needSep = true; 10599 } 10600 } 10601 } 10602 10603 if (mProcessList.getLruSizeLocked() > 0) { 10604 if (needSep) { 10605 pw.println(); 10606 } 10607 mProcessList.dumpLruListHeaderLocked(pw); 10608 dumpProcessOomList(pw, this, mProcessList.mLruProcesses, " ", "Proc", "PERS", false, 10609 dumpPackage); 10610 needSep = true; 10611 } 10612 10613 if (dumpAll || dumpPackage != null) { 10614 synchronized (mPidsSelfLocked) { 10615 boolean printed = false; 10616 for (int i=0; i<mPidsSelfLocked.size(); i++) { 10617 ProcessRecord r = mPidsSelfLocked.valueAt(i); 10618 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 10619 continue; 10620 } 10621 if (!printed) { 10622 if (needSep) pw.println(); 10623 needSep = true; 10624 pw.println(" PID mappings:"); 10625 printed = true; 10626 } 10627 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 10628 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 10629 } 10630 } 10631 } 10632 10633 if (mImportantProcesses.size() > 0) { 10634 synchronized (mPidsSelfLocked) { 10635 boolean printed = false; 10636 for (int i = 0; i< mImportantProcesses.size(); i++) { 10637 ProcessRecord r = mPidsSelfLocked.get( 10638 mImportantProcesses.valueAt(i).pid); 10639 if (dumpPackage != null && (r == null 10640 || !r.pkgList.containsKey(dumpPackage))) { 10641 continue; 10642 } 10643 if (!printed) { 10644 if (needSep) pw.println(); 10645 needSep = true; 10646 pw.println(" Foreground Processes:"); 10647 printed = true; 10648 } 10649 pw.print(" PID #"); pw.print(mImportantProcesses.keyAt(i)); 10650 pw.print(": "); pw.println(mImportantProcesses.valueAt(i)); 10651 } 10652 } 10653 } 10654 10655 if (mPersistentStartingProcesses.size() > 0) { 10656 if (needSep) pw.println(); 10657 needSep = true; 10658 pw.println(" Persisent processes that are starting:"); 10659 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 10660 "Starting Norm", "Restarting PERS", dumpPackage); 10661 } 10662 10663 if (mProcessList.mRemovedProcesses.size() > 0) { 10664 if (needSep) pw.println(); 10665 needSep = true; 10666 pw.println(" Processes that are being removed:"); 10667 dumpProcessList(pw, this, mProcessList.mRemovedProcesses, " ", 10668 "Removed Norm", "Removed PERS", dumpPackage); 10669 } 10670 10671 if (mProcessesOnHold.size() > 0) { 10672 if (needSep) pw.println(); 10673 needSep = true; 10674 pw.println(" Processes that are on old until the system is ready:"); 10675 dumpProcessList(pw, this, mProcessesOnHold, " ", 10676 "OnHold Norm", "OnHold PERS", dumpPackage); 10677 } 10678 10679 needSep = dumpProcessesToGc(pw, needSep, dumpPackage); 10680 10681 needSep = mAppErrors.dumpLocked(fd, pw, needSep, dumpPackage); 10682 10683 if (dumpPackage == null) { 10684 pw.println(); 10685 needSep = false; 10686 mUserController.dump(pw, dumpAll); 10687 } 10688 10689 needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep, 10690 mTestPssMode, mWakefulness); 10691 10692 if (dumpAll && mProcessList.mPendingStarts.size() > 0) { 10693 if (needSep) pw.println(); 10694 needSep = true; 10695 pw.println(" mPendingStarts: "); 10696 for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) { 10697 pw.println(" " + mProcessList.mPendingStarts.keyAt(i) + ": " 10698 + mProcessList.mPendingStarts.valueAt(i)); 10699 } 10700 } 10701 if (dumpAll) { 10702 final int NI = mUidObservers.getRegisteredCallbackCount(); 10703 boolean printed = false; 10704 for (int i=0; i<NI; i++) { 10705 final UidObserverRegistration reg = (UidObserverRegistration) 10706 mUidObservers.getRegisteredCallbackCookie(i); 10707 if (dumpPackage == null || dumpPackage.equals(reg.pkg)) { 10708 if (!printed) { 10709 pw.println(" mUidObservers:"); 10710 printed = true; 10711 } 10712 pw.print(" "); UserHandle.formatUid(pw, reg.uid); 10713 pw.print(" "); pw.print(reg.pkg); 10714 final IUidObserver observer = mUidObservers.getRegisteredCallbackItem(i); 10715 pw.print(" "); pw.print(observer.getClass().getTypeName()); pw.print(":"); 10716 if ((reg.which&ActivityManager.UID_OBSERVER_IDLE) != 0) { 10717 pw.print(" IDLE"); 10718 } 10719 if ((reg.which&ActivityManager.UID_OBSERVER_ACTIVE) != 0) { 10720 pw.print(" ACT" ); 10721 } 10722 if ((reg.which&ActivityManager.UID_OBSERVER_GONE) != 0) { 10723 pw.print(" GONE"); 10724 } 10725 if ((reg.which&ActivityManager.UID_OBSERVER_PROCSTATE) != 0) { 10726 pw.print(" STATE"); 10727 pw.print(" (cut="); pw.print(reg.cutpoint); 10728 pw.print(")"); 10729 } 10730 pw.println(); 10731 if (reg.lastProcStates != null) { 10732 final int NJ = reg.lastProcStates.size(); 10733 for (int j=0; j<NJ; j++) { 10734 pw.print(" Last "); 10735 UserHandle.formatUid(pw, reg.lastProcStates.keyAt(j)); 10736 pw.print(": "); pw.println(reg.lastProcStates.valueAt(j)); 10737 } 10738 } 10739 } 10740 } 10741 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist)); 10742 pw.println(" mDeviceIdleExceptIdleWhitelist=" 10743 + Arrays.toString(mDeviceIdleExceptIdleWhitelist)); 10744 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist)); 10745 if (mPendingTempWhitelist.size() > 0) { 10746 pw.println(" mPendingTempWhitelist:"); 10747 for (int i = 0; i < mPendingTempWhitelist.size(); i++) { 10748 PendingTempWhitelist ptw = mPendingTempWhitelist.valueAt(i); 10749 pw.print(" "); 10750 UserHandle.formatUid(pw, ptw.targetUid); 10751 pw.print(": "); 10752 TimeUtils.formatDuration(ptw.duration, pw); 10753 pw.print(" "); 10754 pw.println(ptw.tag); 10755 } 10756 } 10757 } 10758 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 10759 || mOrigWaitForDebugger) { 10760 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 10761 || dumpPackage.equals(mOrigDebugApp)) { 10762 if (needSep) { 10763 pw.println(); 10764 needSep = false; 10765 } 10766 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 10767 + " mDebugTransient=" + mDebugTransient 10768 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 10769 } 10770 } 10771 if (mMemWatchProcesses.getMap().size() > 0) { 10772 pw.println(" Mem watch processes:"); 10773 final ArrayMap<String, SparseArray<Pair<Long, String>>> procs 10774 = mMemWatchProcesses.getMap(); 10775 for (int i=0; i<procs.size(); i++) { 10776 final String proc = procs.keyAt(i); 10777 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i); 10778 for (int j=0; j<uids.size(); j++) { 10779 if (needSep) { 10780 pw.println(); 10781 needSep = false; 10782 } 10783 StringBuilder sb = new StringBuilder(); 10784 sb.append(" ").append(proc).append('/'); 10785 UserHandle.formatUid(sb, uids.keyAt(j)); 10786 Pair<Long, String> val = uids.valueAt(j); 10787 sb.append(": "); DebugUtils.sizeValueToString(val.first, sb); 10788 if (val.second != null) { 10789 sb.append(", report to ").append(val.second); 10790 } 10791 pw.println(sb.toString()); 10792 } 10793 } 10794 pw.print(" mMemWatchDumpProcName="); pw.println(mMemWatchDumpProcName); 10795 pw.print(" mMemWatchDumpFile="); pw.println(mMemWatchDumpFile); 10796 pw.print(" mMemWatchDumpPid="); pw.println(mMemWatchDumpPid); 10797 pw.print(" mMemWatchDumpUid="); pw.println(mMemWatchDumpUid); 10798 pw.print(" mMemWatchIsUserInitiated="); pw.println(mMemWatchIsUserInitiated); 10799 } 10800 if (mTrackAllocationApp != null) { 10801 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 10802 if (needSep) { 10803 pw.println(); 10804 needSep = false; 10805 } 10806 pw.println(" mTrackAllocationApp=" + mTrackAllocationApp); 10807 } 10808 } 10809 if (mProfileData.getProfileApp() != null || mProfileData.getProfileProc() != null 10810 || (mProfileData.getProfilerInfo() != null && 10811 (mProfileData.getProfilerInfo().profileFile != null 10812 || mProfileData.getProfilerInfo().profileFd != null))) { 10813 if (dumpPackage == null || dumpPackage.equals(mProfileData.getProfileApp())) { 10814 if (needSep) { 10815 pw.println(); 10816 needSep = false; 10817 } 10818 pw.println(" mProfileApp=" + mProfileData.getProfileApp() 10819 + " mProfileProc=" + mProfileData.getProfileProc()); 10820 if (mProfileData.getProfilerInfo() != null) { 10821 pw.println(" mProfileFile=" + mProfileData.getProfilerInfo().profileFile 10822 + " mProfileFd=" + mProfileData.getProfilerInfo().profileFd); 10823 pw.println(" mSamplingInterval=" 10824 + mProfileData.getProfilerInfo().samplingInterval + 10825 " mAutoStopProfiler=" 10826 + mProfileData.getProfilerInfo().autoStopProfiler + 10827 " mStreamingOutput=" + mProfileData.getProfilerInfo().streamingOutput); 10828 pw.println(" mProfileType=" + mProfileType); 10829 } 10830 } 10831 } 10832 if (mNativeDebuggingApp != null) { 10833 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 10834 if (needSep) { 10835 pw.println(); 10836 needSep = false; 10837 } 10838 pw.println(" mNativeDebuggingApp=" + mNativeDebuggingApp); 10839 } 10840 } 10841 if (dumpPackage == null) { 10842 if (mAlwaysFinishActivities) { 10843 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities); 10844 } 10845 if (dumpAll) { 10846 pw.println(" Total persistent processes: " + numPers); 10847 pw.println(" mProcessesReady=" + mProcessesReady 10848 + " mSystemReady=" + mSystemReady 10849 + " mBooted=" + mBooted 10850 + " mFactoryTest=" + mFactoryTest); 10851 pw.println(" mBooting=" + mBooting 10852 + " mCallFinishBooting=" + mCallFinishBooting 10853 + " mBootAnimationComplete=" + mBootAnimationComplete); 10854 pw.print(" mLastPowerCheckUptime="); 10855 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 10856 pw.println(""); 10857 mOomAdjuster.dumpSequenceNumbersLocked(pw); 10858 mOomAdjuster.dumpProcCountsLocked(pw); 10859 pw.println(" mAllowLowerMemLevel=" + mAllowLowerMemLevel 10860 + " mLastMemoryLevel=" + mLastMemoryLevel 10861 + " mLastNumProcesses=" + mLastNumProcesses); 10862 long now = SystemClock.uptimeMillis(); 10863 pw.print(" mLastIdleTime="); 10864 TimeUtils.formatDuration(now, mLastIdleTime, pw); 10865 pw.print(" mLowRamSinceLastIdle="); 10866 TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw); 10867 pw.println(); 10868 pw.println(); 10869 pw.print(" mUidChangeDispatchCount="); 10870 pw.print(mUidChangeDispatchCount); 10871 pw.println(); 10872 10873 pw.println(" Slow UID dispatches:"); 10874 final int N = mUidObservers.beginBroadcast(); 10875 for (int i = 0; i < N; i++) { 10876 UidObserverRegistration r = 10877 (UidObserverRegistration) mUidObservers.getBroadcastCookie(i); 10878 pw.print(" "); 10879 pw.print(mUidObservers.getBroadcastItem(i).getClass().getTypeName()); 10880 pw.print(": "); 10881 pw.print(r.mSlowDispatchCount); 10882 pw.print(" / Max "); 10883 pw.print(r.mMaxDispatchTime); 10884 pw.println("ms"); 10885 } 10886 mUidObservers.finishBroadcast(); 10887 10888 pw.println(); 10889 pw.println(" ServiceManager statistics:"); 10890 ServiceManager.sStatLogger.dump(pw, " "); 10891 pw.println(); 10892 } 10893 } 10894 pw.println(" mForceBackgroundCheck=" + mForceBackgroundCheck); 10895 } 10896 10897 @GuardedBy("this") writeProcessesToProtoLocked(ProtoOutputStream proto, String dumpPackage)10898 void writeProcessesToProtoLocked(ProtoOutputStream proto, String dumpPackage) { 10899 int numPers = 0; 10900 10901 final int NP = mProcessList.mProcessNames.getMap().size(); 10902 for (int ip=0; ip<NP; ip++) { 10903 SparseArray<ProcessRecord> procs = mProcessList.mProcessNames.getMap().valueAt(ip); 10904 final int NA = procs.size(); 10905 for (int ia = 0; ia<NA; ia++) { 10906 ProcessRecord r = procs.valueAt(ia); 10907 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 10908 continue; 10909 } 10910 r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.PROCS, 10911 mProcessList.mLruProcesses.indexOf(r) 10912 ); 10913 if (r.isPersistent()) { 10914 numPers++; 10915 } 10916 } 10917 } 10918 10919 for (int i=0; i<mProcessList.mIsolatedProcesses.size(); i++) { 10920 ProcessRecord r = mProcessList.mIsolatedProcesses.valueAt(i); 10921 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 10922 continue; 10923 } 10924 r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ISOLATED_PROCS, 10925 mProcessList.mLruProcesses.indexOf(r) 10926 ); 10927 } 10928 10929 for (int i=0; i<mActiveInstrumentation.size(); i++) { 10930 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 10931 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 10932 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 10933 continue; 10934 } 10935 ai.writeToProto(proto, 10936 ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS); 10937 } 10938 10939 int whichAppId = getAppId(dumpPackage); 10940 for (int i = 0; i < mProcessList.mActiveUids.size(); i++) { 10941 UidRecord uidRec = mProcessList.mActiveUids.valueAt(i); 10942 if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != whichAppId) { 10943 continue; 10944 } 10945 uidRec.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ACTIVE_UIDS); 10946 } 10947 10948 for (int i = 0; i < mValidateUids.size(); i++) { 10949 UidRecord uidRec = mValidateUids.valueAt(i); 10950 if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != whichAppId) { 10951 continue; 10952 } 10953 uidRec.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS); 10954 } 10955 10956 if (mProcessList.getLruSizeLocked() > 0) { 10957 long lruToken = proto.start(ActivityManagerServiceDumpProcessesProto.LRU_PROCS); 10958 int total = mProcessList.getLruSizeLocked(); 10959 proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.SIZE, total); 10960 proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.NON_ACT_AT, 10961 total - mProcessList.mLruProcessActivityStart); 10962 proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.NON_SVC_AT, 10963 total - mProcessList.mLruProcessServiceStart); 10964 writeProcessOomListToProto(proto, 10965 ActivityManagerServiceDumpProcessesProto.LruProcesses.LIST, this, 10966 mProcessList.mLruProcesses,false, dumpPackage); 10967 proto.end(lruToken); 10968 } 10969 10970 if (dumpPackage != null) { 10971 synchronized (mPidsSelfLocked) { 10972 for (int i=0; i<mPidsSelfLocked.size(); i++) { 10973 ProcessRecord r = mPidsSelfLocked.valueAt(i); 10974 if (!r.pkgList.containsKey(dumpPackage)) { 10975 continue; 10976 } 10977 r.writeToProto(proto, 10978 ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED); 10979 } 10980 } 10981 } 10982 10983 if (mImportantProcesses.size() > 0) { 10984 synchronized (mPidsSelfLocked) { 10985 for (int i=0; i<mImportantProcesses.size(); i++) { 10986 ImportanceToken it = mImportantProcesses.valueAt(i); 10987 ProcessRecord r = mPidsSelfLocked.get(it.pid); 10988 if (dumpPackage != null && (r == null 10989 || !r.pkgList.containsKey(dumpPackage))) { 10990 continue; 10991 } 10992 it.writeToProto(proto, 10993 ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS); 10994 } 10995 } 10996 } 10997 10998 for (int i=0; i<mPersistentStartingProcesses.size(); i++) { 10999 ProcessRecord r = mPersistentStartingProcesses.get(i); 11000 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11001 continue; 11002 } 11003 r.writeToProto(proto, 11004 ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS); 11005 } 11006 11007 for (int i = 0; i < mProcessList.mRemovedProcesses.size(); i++) { 11008 ProcessRecord r = mProcessList.mRemovedProcesses.get(i); 11009 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11010 continue; 11011 } 11012 r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS); 11013 } 11014 11015 for (int i=0; i<mProcessesOnHold.size(); i++) { 11016 ProcessRecord r = mProcessesOnHold.get(i); 11017 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11018 continue; 11019 } 11020 r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS); 11021 } 11022 11023 writeProcessesToGcToProto(proto, ActivityManagerServiceDumpProcessesProto.GC_PROCS, 11024 dumpPackage); 11025 mAppErrors.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS, 11026 dumpPackage); 11027 mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness, mTestPssMode); 11028 11029 if (dumpPackage == null) { 11030 mUserController.writeToProto(proto, 11031 ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER); 11032 } 11033 11034 final int NI = mUidObservers.getRegisteredCallbackCount(); 11035 for (int i=0; i<NI; i++) { 11036 final UidObserverRegistration reg = (UidObserverRegistration) 11037 mUidObservers.getRegisteredCallbackCookie(i); 11038 if (dumpPackage == null || dumpPackage.equals(reg.pkg)) { 11039 reg.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.UID_OBSERVERS); 11040 } 11041 } 11042 11043 for (int v : mDeviceIdleWhitelist) { 11044 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v); 11045 } 11046 11047 for (int v : mDeviceIdleTempWhitelist) { 11048 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v); 11049 } 11050 11051 if (mPendingTempWhitelist.size() > 0) { 11052 for (int i=0; i < mPendingTempWhitelist.size(); i++) { 11053 mPendingTempWhitelist.valueAt(i).writeToProto(proto, 11054 ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST); 11055 } 11056 } 11057 11058 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 11059 || mOrigWaitForDebugger) { 11060 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 11061 || dumpPackage.equals(mOrigDebugApp)) { 11062 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG); 11063 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp); 11064 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp); 11065 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient); 11066 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger); 11067 proto.end(debugAppToken); 11068 } 11069 } 11070 11071 if (mMemWatchProcesses.getMap().size() > 0) { 11072 final long token = proto.start(ActivityManagerServiceDumpProcessesProto.MEM_WATCH_PROCESSES); 11073 ArrayMap<String, SparseArray<Pair<Long, String>>> procs = mMemWatchProcesses.getMap(); 11074 for (int i=0; i<procs.size(); i++) { 11075 final String proc = procs.keyAt(i); 11076 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i); 11077 final long ptoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.PROCS); 11078 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.NAME, proc); 11079 for (int j=0; j<uids.size(); j++) { 11080 final long utoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MEM_STATS); 11081 Pair<Long, String> val = uids.valueAt(j); 11082 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.UID, uids.keyAt(j)); 11083 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.SIZE, 11084 DebugUtils.sizeValueToString(val.first, new StringBuilder())); 11085 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.REPORT_TO, val.second); 11086 proto.end(utoken); 11087 } 11088 proto.end(ptoken); 11089 } 11090 11091 final long dtoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.DUMP); 11092 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.PROC_NAME, mMemWatchDumpProcName); 11093 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.FILE, mMemWatchDumpFile); 11094 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.PID, mMemWatchDumpPid); 11095 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.UID, mMemWatchDumpUid); 11096 proto.write( 11097 ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.IS_USER_INITIATED, 11098 mMemWatchIsUserInitiated); 11099 proto.end(dtoken); 11100 11101 proto.end(token); 11102 } 11103 11104 if (mTrackAllocationApp != null) { 11105 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 11106 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP, 11107 mTrackAllocationApp); 11108 } 11109 } 11110 11111 if (mProfileData.getProfileApp() != null || mProfileData.getProfileProc() != null 11112 || (mProfileData.getProfilerInfo() != null && 11113 (mProfileData.getProfilerInfo().profileFile != null 11114 || mProfileData.getProfilerInfo().profileFd != null))) { 11115 if (dumpPackage == null || dumpPackage.equals(mProfileData.getProfileApp())) { 11116 final long token = proto.start(ActivityManagerServiceDumpProcessesProto.PROFILE); 11117 proto.write(ActivityManagerServiceDumpProcessesProto.Profile.APP_NAME, 11118 mProfileData.getProfileApp()); 11119 mProfileData.getProfileProc().writeToProto(proto, 11120 ActivityManagerServiceDumpProcessesProto.Profile.PROC); 11121 if (mProfileData.getProfilerInfo() != null) { 11122 mProfileData.getProfilerInfo().writeToProto(proto, 11123 ActivityManagerServiceDumpProcessesProto.Profile.INFO); 11124 proto.write(ActivityManagerServiceDumpProcessesProto.Profile.TYPE, 11125 mProfileType); 11126 } 11127 proto.end(token); 11128 } 11129 } 11130 11131 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 11132 proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp); 11133 } 11134 11135 if (dumpPackage == null) { 11136 proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities); 11137 proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers); 11138 proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady); 11139 proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady); 11140 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted); 11141 proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest); 11142 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting); 11143 proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting); 11144 proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete); 11145 proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime); 11146 mOomAdjuster.dumpProcessListVariablesLocked(proto); 11147 proto.write(ActivityManagerServiceDumpProcessesProto.ALLOW_LOWER_MEM_LEVEL, mAllowLowerMemLevel); 11148 proto.write(ActivityManagerServiceDumpProcessesProto.LAST_MEMORY_LEVEL, mLastMemoryLevel); 11149 proto.write(ActivityManagerServiceDumpProcessesProto.LAST_NUM_PROCESSES, mLastNumProcesses); 11150 long now = SystemClock.uptimeMillis(); 11151 ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now); 11152 proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS, getLowRamTimeSinceIdle(now)); 11153 } 11154 } 11155 writeProcessesToGcToProto(ProtoOutputStream proto, long fieldId, String dumpPackage)11156 void writeProcessesToGcToProto(ProtoOutputStream proto, long fieldId, String dumpPackage) { 11157 if (mProcessesToGc.size() > 0) { 11158 long now = SystemClock.uptimeMillis(); 11159 for (int i=0; i<mProcessesToGc.size(); i++) { 11160 ProcessRecord r = mProcessesToGc.get(i); 11161 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11162 continue; 11163 } 11164 final long token = proto.start(fieldId); 11165 r.writeToProto(proto, ProcessToGcProto.PROC); 11166 proto.write(ProcessToGcProto.REPORT_LOW_MEMORY, r.reportLowMemory); 11167 proto.write(ProcessToGcProto.NOW_UPTIME_MS, now); 11168 proto.write(ProcessToGcProto.LAST_GCED_MS, r.lastRequestedGc); 11169 proto.write(ProcessToGcProto.LAST_LOW_MEMORY_MS, r.lastLowMemory); 11170 proto.end(token); 11171 } 11172 } 11173 } 11174 dumpProcessesToGc(PrintWriter pw, boolean needSep, String dumpPackage)11175 boolean dumpProcessesToGc(PrintWriter pw, boolean needSep, String dumpPackage) { 11176 if (mProcessesToGc.size() > 0) { 11177 boolean printed = false; 11178 long now = SystemClock.uptimeMillis(); 11179 for (int i=0; i<mProcessesToGc.size(); i++) { 11180 ProcessRecord proc = mProcessesToGc.get(i); 11181 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) { 11182 continue; 11183 } 11184 if (!printed) { 11185 if (needSep) pw.println(); 11186 needSep = true; 11187 pw.println(" Processes that are waiting to GC:"); 11188 printed = true; 11189 } 11190 pw.print(" Process "); pw.println(proc); 11191 pw.print(" lowMem="); pw.print(proc.reportLowMemory); 11192 pw.print(", last gced="); 11193 pw.print(now-proc.lastRequestedGc); 11194 pw.print(" ms ago, last lowMem="); 11195 pw.print(now-proc.lastLowMemory); 11196 pw.println(" ms ago"); 11197 11198 } 11199 } 11200 return needSep; 11201 } 11202 printOomLevel(PrintWriter pw, String name, int adj)11203 void printOomLevel(PrintWriter pw, String name, int adj) { 11204 pw.print(" "); 11205 if (adj >= 0) { 11206 pw.print(' '); 11207 if (adj < 10) pw.print(' '); 11208 } else { 11209 if (adj > -10) pw.print(' '); 11210 } 11211 pw.print(adj); 11212 pw.print(": "); 11213 pw.print(name); 11214 pw.print(" ("); 11215 pw.print(stringifySize(mProcessList.getMemLevel(adj), 1024)); 11216 pw.println(")"); 11217 } 11218 dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll)11219 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11220 int opti, boolean dumpAll) { 11221 boolean needSep = false; 11222 11223 if (mProcessList.getLruSizeLocked() > 0) { 11224 if (needSep) pw.println(); 11225 needSep = true; 11226 pw.println(" OOM levels:"); 11227 printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ); 11228 printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ); 11229 printOomLevel(pw, "PERSISTENT_SERVICE_ADJ", ProcessList.PERSISTENT_SERVICE_ADJ); 11230 printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ); 11231 printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ); 11232 printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ); 11233 printOomLevel(pw, "PERCEPTIBLE_LOW_APP_ADJ", ProcessList.PERCEPTIBLE_LOW_APP_ADJ); 11234 printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ); 11235 printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ); 11236 printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ); 11237 printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ); 11238 printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ); 11239 printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ); 11240 printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ); 11241 printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ); 11242 11243 if (needSep) pw.println(); 11244 pw.print(" Process OOM control ("); pw.print(mProcessList.getLruSizeLocked()); 11245 pw.print(" total, non-act at "); 11246 pw.print(mProcessList.getLruSizeLocked() 11247 - mProcessList.mLruProcessActivityStart); 11248 pw.print(", non-svc at "); 11249 pw.print(mProcessList.getLruSizeLocked() 11250 - mProcessList.mLruProcessServiceStart); 11251 pw.println("):"); 11252 dumpProcessOomList(pw, this, mProcessList.mLruProcesses, " ", "Proc", "PERS", true, 11253 null); 11254 needSep = true; 11255 } 11256 11257 dumpProcessesToGc(pw, needSep, null); 11258 11259 pw.println(); 11260 mAtmInternal.dumpForOom(pw); 11261 11262 return true; 11263 } 11264 reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)11265 private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) { 11266 Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj); 11267 if (cnt != null) { 11268 pw.println(" kills at or below oom_adj " + oom_adj + ": " + cnt); 11269 return true; 11270 } 11271 return false; 11272 } 11273 dumpLmkLocked(PrintWriter pw)11274 boolean dumpLmkLocked(PrintWriter pw) { 11275 pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)"); 11276 Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ, 11277 ProcessList.UNKNOWN_ADJ); 11278 if (cnt == null) { 11279 return false; 11280 } 11281 pw.println(" Total number of kills: " + cnt); 11282 11283 return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) && 11284 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) && 11285 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) && 11286 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) && 11287 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) && 11288 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) && 11289 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) && 11290 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) && 11291 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) && 11292 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) && 11293 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) && 11294 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ); 11295 } 11296 11297 /** 11298 * There are three ways to call this: 11299 * - no provider specified: dump all the providers 11300 * - a flattened component name that matched an existing provider was specified as the 11301 * first arg: dump that one provider 11302 * - the first arg isn't the flattened component name of an existing provider: 11303 * dump all providers whose component contains the first arg as a substring 11304 */ dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll)11305 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, 11306 int opti, boolean dumpAll) { 11307 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll); 11308 } 11309 11310 /** 11311 * Similar to the dumpProvider, but only dumps the first matching provider. 11312 * The provider is responsible for dumping as proto. 11313 */ dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name, String[] args)11314 protected boolean dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name, 11315 String[] args) { 11316 return mProviderMap.dumpProviderProto(fd, pw, name, args); 11317 } 11318 11319 public static class ItemMatcher { 11320 ArrayList<ComponentName> components; 11321 ArrayList<String> strings; 11322 ArrayList<Integer> objects; 11323 boolean all; 11324 ItemMatcher()11325 public ItemMatcher() { 11326 all = true; 11327 } 11328 build(String name)11329 public void build(String name) { 11330 ComponentName componentName = ComponentName.unflattenFromString(name); 11331 if (componentName != null) { 11332 if (components == null) { 11333 components = new ArrayList<ComponentName>(); 11334 } 11335 components.add(componentName); 11336 all = false; 11337 } else { 11338 int objectId = 0; 11339 // Not a '/' separated full component name; maybe an object ID? 11340 try { 11341 objectId = Integer.parseInt(name, 16); 11342 if (objects == null) { 11343 objects = new ArrayList<Integer>(); 11344 } 11345 objects.add(objectId); 11346 all = false; 11347 } catch (RuntimeException e) { 11348 // Not an integer; just do string match. 11349 if (strings == null) { 11350 strings = new ArrayList<String>(); 11351 } 11352 strings.add(name); 11353 all = false; 11354 } 11355 } 11356 } 11357 build(String[] args, int opti)11358 public int build(String[] args, int opti) { 11359 for (; opti<args.length; opti++) { 11360 String name = args[opti]; 11361 if ("--".equals(name)) { 11362 return opti+1; 11363 } 11364 build(name); 11365 } 11366 return opti; 11367 } 11368 match(Object object, ComponentName comp)11369 public boolean match(Object object, ComponentName comp) { 11370 if (all) { 11371 return true; 11372 } 11373 if (components != null) { 11374 for (int i=0; i<components.size(); i++) { 11375 if (components.get(i).equals(comp)) { 11376 return true; 11377 } 11378 } 11379 } 11380 if (objects != null) { 11381 for (int i=0; i<objects.size(); i++) { 11382 if (System.identityHashCode(object) == objects.get(i)) { 11383 return true; 11384 } 11385 } 11386 } 11387 if (strings != null) { 11388 String flat = comp.flattenToString(); 11389 for (int i=0; i<strings.size(); i++) { 11390 if (flat.contains(strings.get(i))) { 11391 return true; 11392 } 11393 } 11394 } 11395 return false; 11396 } 11397 } 11398 writeBroadcastsToProtoLocked(ProtoOutputStream proto)11399 void writeBroadcastsToProtoLocked(ProtoOutputStream proto) { 11400 if (mRegisteredReceivers.size() > 0) { 11401 Iterator it = mRegisteredReceivers.values().iterator(); 11402 while (it.hasNext()) { 11403 ReceiverList r = (ReceiverList)it.next(); 11404 r.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST); 11405 } 11406 } 11407 mReceiverResolver.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER); 11408 for (BroadcastQueue q : mBroadcastQueues) { 11409 q.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE); 11410 } 11411 for (int user=0; user<mStickyBroadcasts.size(); user++) { 11412 long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS); 11413 proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user)); 11414 for (Map.Entry<String, ArrayList<Intent>> ent 11415 : mStickyBroadcasts.valueAt(user).entrySet()) { 11416 long actionToken = proto.start(StickyBroadcastProto.ACTIONS); 11417 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey()); 11418 for (Intent intent : ent.getValue()) { 11419 intent.writeToProto(proto, StickyBroadcastProto.StickyAction.INTENTS, 11420 false, true, true, false); 11421 } 11422 proto.end(actionToken); 11423 } 11424 proto.end(token); 11425 } 11426 11427 long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER); 11428 proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString()); 11429 mHandler.getLooper().writeToProto(proto, 11430 ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER); 11431 proto.end(handlerToken); 11432 } 11433 dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11434 void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11435 int opti, boolean dumpAll, String dumpPackage) { 11436 boolean needSep = false; 11437 11438 pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)"); 11439 boolean printed = false; 11440 if (mAllowedAssociations != null) { 11441 for (int i = 0; i < mAllowedAssociations.size(); i++) { 11442 final String pkg = mAllowedAssociations.keyAt(i); 11443 final ArraySet<String> asc = 11444 mAllowedAssociations.valueAt(i).getAllowedPackageAssociations(); 11445 boolean printedHeader = false; 11446 for (int j = 0; j < asc.size(); j++) { 11447 if (dumpPackage == null || pkg.equals(dumpPackage) 11448 || asc.valueAt(j).equals(dumpPackage)) { 11449 if (!printed) { 11450 pw.println(" Allowed associations (by restricted package):"); 11451 printed = true; 11452 needSep = true; 11453 } 11454 if (!printedHeader) { 11455 pw.print(" * "); 11456 pw.print(pkg); 11457 pw.println(":"); 11458 printedHeader = true; 11459 } 11460 pw.print(" Allow: "); 11461 pw.println(asc.valueAt(j)); 11462 } 11463 } 11464 if (mAllowedAssociations.valueAt(i).isDebuggable()) { 11465 pw.println(" (debuggable)"); 11466 } 11467 } 11468 } 11469 if (!printed) { 11470 pw.println(" (No association restrictions)"); 11471 } 11472 } 11473 dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11474 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11475 int opti, boolean dumpAll, String dumpPackage) { 11476 boolean needSep = false; 11477 boolean onlyHistory = false; 11478 boolean printedAnything = false; 11479 11480 if ("history".equals(dumpPackage)) { 11481 if (opti < args.length && "-s".equals(args[opti])) { 11482 dumpAll = false; 11483 } 11484 onlyHistory = true; 11485 dumpPackage = null; 11486 } 11487 11488 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 11489 if (!onlyHistory && dumpAll) { 11490 if (mRegisteredReceivers.size() > 0) { 11491 boolean printed = false; 11492 Iterator it = mRegisteredReceivers.values().iterator(); 11493 while (it.hasNext()) { 11494 ReceiverList r = (ReceiverList)it.next(); 11495 if (dumpPackage != null && (r.app == null || 11496 !dumpPackage.equals(r.app.info.packageName))) { 11497 continue; 11498 } 11499 if (!printed) { 11500 pw.println(" Registered Receivers:"); 11501 needSep = true; 11502 printed = true; 11503 printedAnything = true; 11504 } 11505 pw.print(" * "); pw.println(r); 11506 r.dump(pw, " "); 11507 } 11508 } 11509 11510 if (mReceiverResolver.dump(pw, needSep ? 11511 "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 11512 " ", dumpPackage, false, false)) { 11513 needSep = true; 11514 printedAnything = true; 11515 } 11516 } 11517 11518 for (BroadcastQueue q : mBroadcastQueues) { 11519 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep); 11520 printedAnything |= needSep; 11521 } 11522 11523 needSep = true; 11524 11525 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) { 11526 for (int user=0; user<mStickyBroadcasts.size(); user++) { 11527 if (needSep) { 11528 pw.println(); 11529 } 11530 needSep = true; 11531 printedAnything = true; 11532 pw.print(" Sticky broadcasts for user "); 11533 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":"); 11534 StringBuilder sb = new StringBuilder(128); 11535 for (Map.Entry<String, ArrayList<Intent>> ent 11536 : mStickyBroadcasts.valueAt(user).entrySet()) { 11537 pw.print(" * Sticky action "); pw.print(ent.getKey()); 11538 if (dumpAll) { 11539 pw.println(":"); 11540 ArrayList<Intent> intents = ent.getValue(); 11541 final int N = intents.size(); 11542 for (int i=0; i<N; i++) { 11543 sb.setLength(0); 11544 sb.append(" Intent: "); 11545 intents.get(i).toShortString(sb, false, true, false, false); 11546 pw.println(sb.toString()); 11547 Bundle bundle = intents.get(i).getExtras(); 11548 if (bundle != null) { 11549 pw.print(" "); 11550 pw.println(bundle.toString()); 11551 } 11552 } 11553 } else { 11554 pw.println(""); 11555 } 11556 } 11557 } 11558 } 11559 11560 if (!onlyHistory && dumpAll) { 11561 pw.println(); 11562 for (BroadcastQueue queue : mBroadcastQueues) { 11563 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]=" 11564 + queue.mBroadcastsScheduled); 11565 } 11566 pw.println(" mHandler:"); 11567 mHandler.dump(new PrintWriterPrinter(pw), " "); 11568 needSep = true; 11569 printedAnything = true; 11570 } 11571 11572 if (!printedAnything) { 11573 pw.println(" (nothing)"); 11574 } 11575 } 11576 dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11577 void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11578 int opti, boolean dumpAll, String dumpPackage) { 11579 if (mCurBroadcastStats == null) { 11580 return; 11581 } 11582 11583 pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)"); 11584 final long now = SystemClock.elapsedRealtime(); 11585 if (mLastBroadcastStats != null) { 11586 pw.print(" Last stats (from "); 11587 TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw); 11588 pw.print(" to "); 11589 TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw); 11590 pw.print(", "); 11591 TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime 11592 - mLastBroadcastStats.mStartUptime, pw); 11593 pw.println(" uptime):"); 11594 if (!mLastBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 11595 pw.println(" (nothing)"); 11596 } 11597 pw.println(); 11598 } 11599 pw.print(" Current stats (from "); 11600 TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw); 11601 pw.print(" to now, "); 11602 TimeUtils.formatDuration(SystemClock.uptimeMillis() 11603 - mCurBroadcastStats.mStartUptime, pw); 11604 pw.println(" uptime):"); 11605 if (!mCurBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 11606 pw.println(" (nothing)"); 11607 } 11608 } 11609 dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)11610 void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11611 int opti, boolean fullCheckin, String dumpPackage) { 11612 if (mCurBroadcastStats == null) { 11613 return; 11614 } 11615 11616 if (mLastBroadcastStats != null) { 11617 mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage); 11618 if (fullCheckin) { 11619 mLastBroadcastStats = null; 11620 return; 11621 } 11622 } 11623 mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage); 11624 if (fullCheckin) { 11625 mCurBroadcastStats = null; 11626 } 11627 } 11628 dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11629 void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11630 int opti, boolean dumpAll, String dumpPackage) { 11631 boolean needSep; 11632 boolean printedAnything = false; 11633 11634 ItemMatcher matcher = new ItemMatcher(); 11635 matcher.build(args, opti); 11636 11637 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)"); 11638 11639 needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage); 11640 printedAnything |= needSep; 11641 11642 if (mLaunchingProviders.size() > 0) { 11643 boolean printed = false; 11644 for (int i=mLaunchingProviders.size()-1; i>=0; i--) { 11645 ContentProviderRecord r = mLaunchingProviders.get(i); 11646 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) { 11647 continue; 11648 } 11649 if (!printed) { 11650 if (needSep) pw.println(); 11651 needSep = true; 11652 pw.println(" Launching content providers:"); 11653 printed = true; 11654 printedAnything = true; 11655 } 11656 pw.print(" Launching #"); pw.print(i); pw.print(": "); 11657 pw.println(r); 11658 } 11659 } 11660 11661 if (!printedAnything) { 11662 pw.println(" (nothing)"); 11663 } 11664 } 11665 11666 @GuardedBy("this") dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11667 void dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11668 int opti, boolean dumpAll, String dumpPackage) { 11669 11670 pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)"); 11671 11672 mUgmInternal.dump(pw, dumpAll, dumpPackage); 11673 } 11674 dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)11675 private static final int dumpProcessList(PrintWriter pw, 11676 ActivityManagerService service, List list, 11677 String prefix, String normalLabel, String persistentLabel, 11678 String dumpPackage) { 11679 int numPers = 0; 11680 final int N = list.size()-1; 11681 for (int i=N; i>=0; i--) { 11682 ProcessRecord r = (ProcessRecord)list.get(i); 11683 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11684 continue; 11685 } 11686 pw.println(String.format("%s%s #%2d: %s", 11687 prefix, (r.isPersistent() ? persistentLabel : normalLabel), 11688 i, r.toString())); 11689 if (r.isPersistent()) { 11690 numPers++; 11691 } 11692 } 11693 return numPers; 11694 } 11695 11696 private static final ArrayList<Pair<ProcessRecord, Integer>> sortProcessOomList(List<ProcessRecord> origList, String dumpPackage)11697 sortProcessOomList(List<ProcessRecord> origList, String dumpPackage) { 11698 ArrayList<Pair<ProcessRecord, Integer>> list 11699 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size()); 11700 for (int i=0; i<origList.size(); i++) { 11701 ProcessRecord r = origList.get(i); 11702 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 11703 continue; 11704 } 11705 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i)); 11706 } 11707 11708 Comparator<Pair<ProcessRecord, Integer>> comparator 11709 = new Comparator<Pair<ProcessRecord, Integer>>() { 11710 @Override 11711 public int compare(Pair<ProcessRecord, Integer> object1, 11712 Pair<ProcessRecord, Integer> object2) { 11713 if (object1.first.setAdj != object2.first.setAdj) { 11714 return object1.first.setAdj > object2.first.setAdj ? -1 : 1; 11715 } 11716 if (object1.first.setProcState != object2.first.setProcState) { 11717 return object1.first.setProcState > object2.first.setProcState ? -1 : 1; 11718 } 11719 if (object1.second.intValue() != object2.second.intValue()) { 11720 return object1.second.intValue() > object2.second.intValue() ? -1 : 1; 11721 } 11722 return 0; 11723 } 11724 }; 11725 11726 Collections.sort(list, comparator); 11727 return list; 11728 } 11729 writeProcessOomListToProto(ProtoOutputStream proto, long fieldId, ActivityManagerService service, List<ProcessRecord> origList, boolean inclDetails, String dumpPackage)11730 private static final boolean writeProcessOomListToProto(ProtoOutputStream proto, long fieldId, 11731 ActivityManagerService service, List<ProcessRecord> origList, 11732 boolean inclDetails, String dumpPackage) { 11733 ArrayList<Pair<ProcessRecord, Integer>> list = sortProcessOomList(origList, dumpPackage); 11734 if (list.isEmpty()) return false; 11735 11736 final long curUptime = SystemClock.uptimeMillis(); 11737 11738 for (int i = list.size() - 1; i >= 0; i--) { 11739 ProcessRecord r = list.get(i).first; 11740 long token = proto.start(fieldId); 11741 String oomAdj = ProcessList.makeOomAdjString(r.setAdj, true); 11742 proto.write(ProcessOomProto.PERSISTENT, r.isPersistent()); 11743 proto.write(ProcessOomProto.NUM, (origList.size()-1)-list.get(i).second); 11744 proto.write(ProcessOomProto.OOM_ADJ, oomAdj); 11745 int schedGroup = ProcessOomProto.SCHED_GROUP_UNKNOWN; 11746 switch (r.setSchedGroup) { 11747 case ProcessList.SCHED_GROUP_BACKGROUND: 11748 schedGroup = ProcessOomProto.SCHED_GROUP_BACKGROUND; 11749 break; 11750 case ProcessList.SCHED_GROUP_DEFAULT: 11751 schedGroup = ProcessOomProto.SCHED_GROUP_DEFAULT; 11752 break; 11753 case ProcessList.SCHED_GROUP_TOP_APP: 11754 schedGroup = ProcessOomProto.SCHED_GROUP_TOP_APP; 11755 break; 11756 case ProcessList.SCHED_GROUP_TOP_APP_BOUND: 11757 schedGroup = ProcessOomProto.SCHED_GROUP_TOP_APP_BOUND; 11758 break; 11759 } 11760 if (schedGroup != ProcessOomProto.SCHED_GROUP_UNKNOWN) { 11761 proto.write(ProcessOomProto.SCHED_GROUP, schedGroup); 11762 } 11763 if (r.hasForegroundActivities()) { 11764 proto.write(ProcessOomProto.ACTIVITIES, true); 11765 } else if (r.hasForegroundServices()) { 11766 proto.write(ProcessOomProto.SERVICES, true); 11767 } 11768 proto.write(ProcessOomProto.STATE, 11769 ProcessList.makeProcStateProtoEnum(r.getCurProcState())); 11770 proto.write(ProcessOomProto.TRIM_MEMORY_LEVEL, r.trimMemoryLevel); 11771 r.writeToProto(proto, ProcessOomProto.PROC); 11772 proto.write(ProcessOomProto.ADJ_TYPE, r.adjType); 11773 if (r.adjSource != null || r.adjTarget != null) { 11774 if (r.adjTarget instanceof ComponentName) { 11775 ComponentName cn = (ComponentName) r.adjTarget; 11776 cn.writeToProto(proto, ProcessOomProto.ADJ_TARGET_COMPONENT_NAME); 11777 } else if (r.adjTarget != null) { 11778 proto.write(ProcessOomProto.ADJ_TARGET_OBJECT, r.adjTarget.toString()); 11779 } 11780 if (r.adjSource instanceof ProcessRecord) { 11781 ProcessRecord p = (ProcessRecord) r.adjSource; 11782 p.writeToProto(proto, ProcessOomProto.ADJ_SOURCE_PROC); 11783 } else if (r.adjSource != null) { 11784 proto.write(ProcessOomProto.ADJ_SOURCE_OBJECT, r.adjSource.toString()); 11785 } 11786 } 11787 if (inclDetails) { 11788 long detailToken = proto.start(ProcessOomProto.DETAIL); 11789 proto.write(ProcessOomProto.Detail.MAX_ADJ, r.maxAdj); 11790 proto.write(ProcessOomProto.Detail.CUR_RAW_ADJ, r.getCurRawAdj()); 11791 proto.write(ProcessOomProto.Detail.SET_RAW_ADJ, r.setRawAdj); 11792 proto.write(ProcessOomProto.Detail.CUR_ADJ, r.curAdj); 11793 proto.write(ProcessOomProto.Detail.SET_ADJ, r.setAdj); 11794 proto.write(ProcessOomProto.Detail.CURRENT_STATE, 11795 ProcessList.makeProcStateProtoEnum(r.getCurProcState())); 11796 proto.write(ProcessOomProto.Detail.SET_STATE, 11797 ProcessList.makeProcStateProtoEnum(r.setProcState)); 11798 proto.write(ProcessOomProto.Detail.LAST_PSS, DebugUtils.sizeValueToString( 11799 r.lastPss*1024, new StringBuilder())); 11800 proto.write(ProcessOomProto.Detail.LAST_SWAP_PSS, DebugUtils.sizeValueToString( 11801 r.lastSwapPss*1024, new StringBuilder())); 11802 proto.write(ProcessOomProto.Detail.LAST_CACHED_PSS, DebugUtils.sizeValueToString( 11803 r.lastCachedPss*1024, new StringBuilder())); 11804 proto.write(ProcessOomProto.Detail.CACHED, r.cached); 11805 proto.write(ProcessOomProto.Detail.EMPTY, r.empty); 11806 proto.write(ProcessOomProto.Detail.HAS_ABOVE_CLIENT, r.hasAboveClient); 11807 11808 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) { 11809 if (r.lastCpuTime != 0) { 11810 long uptimeSince = curUptime - service.mLastPowerCheckUptime; 11811 long timeUsed = r.curCpuTime - r.lastCpuTime; 11812 long cpuTimeToken = proto.start(ProcessOomProto.Detail.SERVICE_RUN_TIME); 11813 proto.write(ProcessOomProto.Detail.CpuRunTime.OVER_MS, uptimeSince); 11814 proto.write(ProcessOomProto.Detail.CpuRunTime.USED_MS, timeUsed); 11815 proto.write(ProcessOomProto.Detail.CpuRunTime.ULTILIZATION, 11816 (100.0*timeUsed)/uptimeSince); 11817 proto.end(cpuTimeToken); 11818 } 11819 } 11820 proto.end(detailToken); 11821 } 11822 proto.end(token); 11823 } 11824 11825 return true; 11826 } 11827 dumpProcessOomList(PrintWriter pw, ActivityManagerService service, List<ProcessRecord> origList, String prefix, String normalLabel, String persistentLabel, boolean inclDetails, String dumpPackage)11828 private static final boolean dumpProcessOomList(PrintWriter pw, 11829 ActivityManagerService service, List<ProcessRecord> origList, 11830 String prefix, String normalLabel, String persistentLabel, 11831 boolean inclDetails, String dumpPackage) { 11832 11833 ArrayList<Pair<ProcessRecord, Integer>> list = sortProcessOomList(origList, dumpPackage); 11834 if (list.isEmpty()) return false; 11835 11836 final long curUptime = SystemClock.uptimeMillis(); 11837 final long uptimeSince = curUptime - service.mLastPowerCheckUptime; 11838 11839 for (int i=list.size()-1; i>=0; i--) { 11840 ProcessRecord r = list.get(i).first; 11841 String oomAdj = ProcessList.makeOomAdjString(r.setAdj, false); 11842 char schedGroup; 11843 switch (r.setSchedGroup) { 11844 case ProcessList.SCHED_GROUP_BACKGROUND: 11845 schedGroup = 'B'; 11846 break; 11847 case ProcessList.SCHED_GROUP_DEFAULT: 11848 schedGroup = 'F'; 11849 break; 11850 case ProcessList.SCHED_GROUP_TOP_APP: 11851 schedGroup = 'T'; 11852 break; 11853 case ProcessList.SCHED_GROUP_RESTRICTED: 11854 schedGroup = 'R'; 11855 break; 11856 default: 11857 schedGroup = '?'; 11858 break; 11859 } 11860 char foreground; 11861 if (r.hasForegroundActivities()) { 11862 foreground = 'A'; 11863 } else if (r.hasForegroundServices()) { 11864 foreground = 'S'; 11865 } else { 11866 foreground = ' '; 11867 } 11868 String procState = ProcessList.makeProcStateString(r.getCurProcState()); 11869 pw.print(prefix); 11870 pw.print(r.isPersistent() ? persistentLabel : normalLabel); 11871 pw.print(" #"); 11872 int num = (origList.size()-1)-list.get(i).second; 11873 if (num < 10) pw.print(' '); 11874 pw.print(num); 11875 pw.print(": "); 11876 pw.print(oomAdj); 11877 pw.print(' '); 11878 pw.print(schedGroup); 11879 pw.print('/'); 11880 pw.print(foreground); 11881 pw.print('/'); 11882 pw.print(procState); 11883 pw.print(" trm:"); 11884 if (r.trimMemoryLevel < 10) pw.print(' '); 11885 pw.print(r.trimMemoryLevel); 11886 pw.print(' '); 11887 pw.print(r.toShortString()); 11888 pw.print(" ("); 11889 pw.print(r.adjType); 11890 pw.println(')'); 11891 if (r.adjSource != null || r.adjTarget != null) { 11892 pw.print(prefix); 11893 pw.print(" "); 11894 if (r.adjTarget instanceof ComponentName) { 11895 pw.print(((ComponentName)r.adjTarget).flattenToShortString()); 11896 } else if (r.adjTarget != null) { 11897 pw.print(r.adjTarget.toString()); 11898 } else { 11899 pw.print("{null}"); 11900 } 11901 pw.print("<="); 11902 if (r.adjSource instanceof ProcessRecord) { 11903 pw.print("Proc{"); 11904 pw.print(((ProcessRecord)r.adjSource).toShortString()); 11905 pw.println("}"); 11906 } else if (r.adjSource != null) { 11907 pw.println(r.adjSource.toString()); 11908 } else { 11909 pw.println("{null}"); 11910 } 11911 } 11912 if (inclDetails) { 11913 pw.print(prefix); 11914 pw.print(" "); 11915 pw.print("oom: max="); pw.print(r.maxAdj); 11916 pw.print(" curRaw="); pw.print(r.getCurRawAdj()); 11917 pw.print(" setRaw="); pw.print(r.setRawAdj); 11918 pw.print(" cur="); pw.print(r.curAdj); 11919 pw.print(" set="); pw.println(r.setAdj); 11920 pw.print(prefix); 11921 pw.print(" "); 11922 pw.print("state: cur="); pw.print( 11923 ProcessList.makeProcStateString(r.getCurProcState())); 11924 pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState)); 11925 pw.print(" lastPss="); DebugUtils.printSizeValue(pw, r.lastPss*1024); 11926 pw.print(" lastSwapPss="); DebugUtils.printSizeValue(pw, r.lastSwapPss*1024); 11927 pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, r.lastCachedPss*1024); 11928 pw.println(); 11929 pw.print(prefix); 11930 pw.print(" "); 11931 pw.print("cached="); pw.print(r.cached); 11932 pw.print(" empty="); pw.print(r.empty); 11933 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient); 11934 11935 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) { 11936 if (r.lastCpuTime != 0) { 11937 long timeUsed = r.curCpuTime - r.lastCpuTime; 11938 pw.print(prefix); 11939 pw.print(" "); 11940 pw.print("run cpu over "); 11941 TimeUtils.formatDuration(uptimeSince, pw); 11942 pw.print(" used "); 11943 TimeUtils.formatDuration(timeUsed, pw); 11944 pw.print(" ("); 11945 pw.print((timeUsed*100)/uptimeSince); 11946 pw.println("%)"); 11947 } 11948 } 11949 } 11950 } 11951 return true; 11952 } 11953 collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)11954 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs, 11955 String[] args) { 11956 synchronized (this) { 11957 return mProcessList.collectProcessesLocked(start, allPkgs, args); 11958 } 11959 } 11960 dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)11961 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 11962 PrintWriter pw, String[] args) { 11963 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 11964 if (procs == null) { 11965 pw.println("No process found for: " + args[0]); 11966 return; 11967 } 11968 11969 long uptime = SystemClock.uptimeMillis(); 11970 long realtime = SystemClock.elapsedRealtime(); 11971 pw.println("Applications Graphics Acceleration Info:"); 11972 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 11973 11974 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 11975 ProcessRecord r = procs.get(i); 11976 if (r.thread != null) { 11977 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **"); 11978 pw.flush(); 11979 try { 11980 TransferPipe tp = new TransferPipe(); 11981 try { 11982 r.thread.dumpGfxInfo(tp.getWriteFd(), args); 11983 tp.go(fd); 11984 } finally { 11985 tp.kill(); 11986 } 11987 } catch (IOException e) { 11988 pw.println("Failure while dumping the app: " + r); 11989 pw.flush(); 11990 } catch (RemoteException e) { 11991 pw.println("Got a RemoteException while dumping the app " + r); 11992 pw.flush(); 11993 } 11994 } 11995 } 11996 } 11997 dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)11998 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 11999 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 12000 if (procs == null) { 12001 pw.println("No process found for: " + args[0]); 12002 return; 12003 } 12004 12005 pw.println("Applications Database Info:"); 12006 12007 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 12008 ProcessRecord r = procs.get(i); 12009 if (r.thread != null) { 12010 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **"); 12011 pw.flush(); 12012 try { 12013 TransferPipe tp = new TransferPipe(); 12014 try { 12015 r.thread.dumpDbInfo(tp.getWriteFd(), args); 12016 tp.go(fd); 12017 } finally { 12018 tp.kill(); 12019 } 12020 } catch (IOException e) { 12021 pw.println("Failure while dumping the app: " + r); 12022 pw.flush(); 12023 } catch (RemoteException e) { 12024 pw.println("Got a RemoteException while dumping the app " + r); 12025 pw.flush(); 12026 } 12027 } 12028 } 12029 } 12030 12031 final static class MemItem { 12032 final boolean isProc; 12033 final String label; 12034 final String shortLabel; 12035 final long pss; 12036 final long swapPss; 12037 final int id; 12038 final boolean hasActivities; 12039 ArrayList<MemItem> subitems; 12040 MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id, boolean _hasActivities)12041 public MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id, 12042 boolean _hasActivities) { 12043 isProc = true; 12044 label = _label; 12045 shortLabel = _shortLabel; 12046 pss = _pss; 12047 swapPss = _swapPss; 12048 id = _id; 12049 hasActivities = _hasActivities; 12050 } 12051 MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id)12052 public MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id) { 12053 isProc = false; 12054 label = _label; 12055 shortLabel = _shortLabel; 12056 pss = _pss; 12057 swapPss = _swapPss; 12058 id = _id; 12059 hasActivities = false; 12060 } 12061 } 12062 sortMemItems(List<MemItem> items)12063 private static void sortMemItems(List<MemItem> items) { 12064 Collections.sort(items, new Comparator<MemItem>() { 12065 @Override 12066 public int compare(MemItem lhs, MemItem rhs) { 12067 if (lhs.pss < rhs.pss) { 12068 return 1; 12069 } else if (lhs.pss > rhs.pss) { 12070 return -1; 12071 } 12072 return 0; 12073 } 12074 }); 12075 } 12076 dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpSwapPss)12077 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 12078 ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpSwapPss) { 12079 if (sort && !isCompact) { 12080 sortMemItems(items); 12081 } 12082 12083 for (int i=0; i<items.size(); i++) { 12084 MemItem mi = items.get(i); 12085 if (!isCompact) { 12086 if (dumpSwapPss) { 12087 pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss), 12088 mi.label, stringifyKBSize(mi.swapPss)); 12089 } else { 12090 pw.printf("%s%s: %s\n", prefix, stringifyKBSize(mi.pss), mi.label); 12091 } 12092 } else if (mi.isProc) { 12093 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 12094 pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss); pw.print(","); 12095 pw.print(dumpSwapPss ? mi.swapPss : "N/A"); 12096 pw.println(mi.hasActivities ? ",a" : ",e"); 12097 } else { 12098 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 12099 pw.print(mi.pss); pw.print(","); pw.println(dumpSwapPss ? mi.swapPss : "N/A"); 12100 } 12101 if (mi.subitems != null) { 12102 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 12103 true, isCompact, dumpSwapPss); 12104 } 12105 } 12106 } 12107 dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpSwapPss)12108 static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, 12109 ArrayList<MemItem> items, boolean sort, boolean dumpSwapPss) { 12110 if (sort) { 12111 sortMemItems(items); 12112 } 12113 12114 for (int i=0; i<items.size(); i++) { 12115 MemItem mi = items.get(i); 12116 final long token = proto.start(fieldId); 12117 12118 proto.write(MemInfoDumpProto.MemItem.TAG, tag); 12119 proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel); 12120 proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc); 12121 proto.write(MemInfoDumpProto.MemItem.ID, mi.id); 12122 proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities); 12123 proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss); 12124 if (dumpSwapPss) { 12125 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss); 12126 } 12127 if (mi.subitems != null) { 12128 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems, 12129 true, dumpSwapPss); 12130 } 12131 proto.end(token); 12132 } 12133 } 12134 12135 // These are in KB. 12136 static final long[] DUMP_MEM_BUCKETS = new long[] { 12137 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 12138 120*1024, 160*1024, 200*1024, 12139 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 12140 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 12141 }; 12142 appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)12143 static final void appendMemBucket(StringBuilder out, long memKB, String label, 12144 boolean stackLike) { 12145 int start = label.lastIndexOf('.'); 12146 if (start >= 0) start++; 12147 else start = 0; 12148 int end = label.length(); 12149 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 12150 if (DUMP_MEM_BUCKETS[i] >= memKB) { 12151 long bucket = DUMP_MEM_BUCKETS[i]/1024; 12152 out.append(bucket); 12153 out.append(stackLike ? "MB." : "MB "); 12154 out.append(label, start, end); 12155 return; 12156 } 12157 } 12158 out.append(memKB/1024); 12159 out.append(stackLike ? "MB." : "MB "); 12160 out.append(label, start, end); 12161 } 12162 12163 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 12164 ProcessList.NATIVE_ADJ, 12165 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, 12166 ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ, 12167 ProcessList.VISIBLE_APP_ADJ, 12168 ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ, 12169 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 12170 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 12171 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ 12172 }; 12173 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 12174 "Native", 12175 "System", "Persistent", "Persistent Service", "Foreground", 12176 "Visible", "Perceptible", "Perceptible Low", 12177 "Heavy Weight", "Backup", 12178 "A Services", "Home", 12179 "Previous", "B Services", "Cached" 12180 }; 12181 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 12182 "native", 12183 "sys", "pers", "persvc", "fore", 12184 "vis", "percept", "perceptl", 12185 "heavy", "backup", 12186 "servicea", "home", 12187 "prev", "serviceb", "cached" 12188 }; 12189 dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)12190 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 12191 long realtime, boolean isCheckinRequest, boolean isCompact) { 12192 if (isCompact) { 12193 pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION); 12194 } 12195 if (isCheckinRequest || isCompact) { 12196 // short checkin version 12197 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 12198 } else { 12199 pw.println("Applications Memory Usage (in Kilobytes):"); 12200 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 12201 } 12202 } 12203 12204 private static final int KSM_SHARED = 0; 12205 private static final int KSM_SHARING = 1; 12206 private static final int KSM_UNSHARED = 2; 12207 private static final int KSM_VOLATILE = 3; 12208 getKsmInfo()12209 private final long[] getKsmInfo() { 12210 long[] longOut = new long[4]; 12211 final int[] SINGLE_LONG_FORMAT = new int[] { 12212 PROC_SPACE_TERM| PROC_OUT_LONG 12213 }; 12214 long[] longTmp = new long[1]; 12215 readProcFile("/sys/kernel/mm/ksm/pages_shared", 12216 SINGLE_LONG_FORMAT, null, longTmp, null); 12217 longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12218 longTmp[0] = 0; 12219 readProcFile("/sys/kernel/mm/ksm/pages_sharing", 12220 SINGLE_LONG_FORMAT, null, longTmp, null); 12221 longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12222 longTmp[0] = 0; 12223 readProcFile("/sys/kernel/mm/ksm/pages_unshared", 12224 SINGLE_LONG_FORMAT, null, longTmp, null); 12225 longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12226 longTmp[0] = 0; 12227 readProcFile("/sys/kernel/mm/ksm/pages_volatile", 12228 SINGLE_LONG_FORMAT, null, longTmp, null); 12229 longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12230 return longOut; 12231 } 12232 stringifySize(long size, int order)12233 private static String stringifySize(long size, int order) { 12234 Locale locale = Locale.US; 12235 switch (order) { 12236 case 1: 12237 return String.format(locale, "%,13d", size); 12238 case 1024: 12239 return String.format(locale, "%,9dK", size / 1024); 12240 case 1024 * 1024: 12241 return String.format(locale, "%,5dM", size / 1024 / 1024); 12242 case 1024 * 1024 * 1024: 12243 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024); 12244 default: 12245 throw new IllegalArgumentException("Invalid size order"); 12246 } 12247 } 12248 stringifyKBSize(long size)12249 private static String stringifyKBSize(long size) { 12250 return stringifySize(size * 1024, 1024); 12251 } 12252 12253 // Update this version number if you change the 'compact' format. 12254 private static final int MEMINFO_COMPACT_VERSION = 1; 12255 12256 private static class MemoryUsageDumpOptions { 12257 boolean dumpDetails; 12258 boolean dumpFullDetails; 12259 boolean dumpDalvik; 12260 boolean dumpSummaryOnly; 12261 boolean dumpUnreachable; 12262 boolean oomOnly; 12263 boolean isCompact; 12264 boolean localOnly; 12265 boolean packages; 12266 boolean isCheckinRequest; 12267 boolean dumpSwapPss; 12268 boolean dumpProto; 12269 } 12270 dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)12271 final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 12272 String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) { 12273 MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions(); 12274 opts.dumpDetails = false; 12275 opts.dumpFullDetails = false; 12276 opts.dumpDalvik = false; 12277 opts.dumpSummaryOnly = false; 12278 opts.dumpUnreachable = false; 12279 opts.oomOnly = false; 12280 opts.isCompact = false; 12281 opts.localOnly = false; 12282 opts.packages = false; 12283 opts.isCheckinRequest = false; 12284 opts.dumpSwapPss = false; 12285 opts.dumpProto = asProto; 12286 12287 int opti = 0; 12288 while (opti < args.length) { 12289 String opt = args[opti]; 12290 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12291 break; 12292 } 12293 opti++; 12294 if ("-a".equals(opt)) { 12295 opts.dumpDetails = true; 12296 opts.dumpFullDetails = true; 12297 opts.dumpDalvik = true; 12298 opts.dumpSwapPss = true; 12299 } else if ("-d".equals(opt)) { 12300 opts.dumpDalvik = true; 12301 } else if ("-c".equals(opt)) { 12302 opts.isCompact = true; 12303 } else if ("-s".equals(opt)) { 12304 opts.dumpDetails = true; 12305 opts.dumpSummaryOnly = true; 12306 } else if ("-S".equals(opt)) { 12307 opts.dumpSwapPss = true; 12308 } else if ("--unreachable".equals(opt)) { 12309 opts.dumpUnreachable = true; 12310 } else if ("--oom".equals(opt)) { 12311 opts.oomOnly = true; 12312 } else if ("--local".equals(opt)) { 12313 opts.localOnly = true; 12314 } else if ("--package".equals(opt)) { 12315 opts.packages = true; 12316 } else if ("--checkin".equals(opt)) { 12317 opts.isCheckinRequest = true; 12318 } else if ("--proto".equals(opt)) { 12319 opts.dumpProto = true; 12320 12321 } else if ("-h".equals(opt)) { 12322 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]"); 12323 pw.println(" -a: include all available information for each process."); 12324 pw.println(" -d: include dalvik details."); 12325 pw.println(" -c: dump in a compact machine-parseable representation."); 12326 pw.println(" -s: dump only summary of application memory usage."); 12327 pw.println(" -S: dump also SwapPss."); 12328 pw.println(" --oom: only show processes organized by oom adj."); 12329 pw.println(" --local: only collect details locally, don't call process."); 12330 pw.println(" --package: interpret process arg as package, dumping all"); 12331 pw.println(" processes that have loaded that package."); 12332 pw.println(" --checkin: dump data for a checkin"); 12333 pw.println(" --proto: dump data to proto"); 12334 pw.println("If [process] is specified it can be the name or "); 12335 pw.println("pid of a specific process to dump."); 12336 return; 12337 } else { 12338 pw.println("Unknown argument: " + opt + "; use -h for help"); 12339 } 12340 } 12341 12342 String[] innerArgs = new String[args.length-opti]; 12343 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 12344 12345 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args); 12346 if (opts.dumpProto) { 12347 dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs); 12348 } else { 12349 dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw); 12350 } 12351 } 12352 dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs, PrintWriter categoryPw)12353 private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 12354 MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, 12355 ArrayList<ProcessRecord> procs, PrintWriter categoryPw) { 12356 long uptime = SystemClock.uptimeMillis(); 12357 long realtime = SystemClock.elapsedRealtime(); 12358 final long[] tmpLong = new long[1]; 12359 12360 if (procs == null) { 12361 // No Java processes. Maybe they want to print a native process. 12362 String proc = "N/A"; 12363 if (innerArgs.length > 0) { 12364 proc = innerArgs[0]; 12365 if (proc.charAt(0) != '-') { 12366 ArrayList<ProcessCpuTracker.Stats> nativeProcs 12367 = new ArrayList<ProcessCpuTracker.Stats>(); 12368 updateCpuStatsNow(); 12369 int findPid = -1; 12370 try { 12371 findPid = Integer.parseInt(innerArgs[0]); 12372 } catch (NumberFormatException e) { 12373 } 12374 synchronized (mProcessCpuTracker) { 12375 final int N = mProcessCpuTracker.countStats(); 12376 for (int i=0; i<N; i++) { 12377 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 12378 if (st.pid == findPid || (st.baseName != null 12379 && st.baseName.equals(innerArgs[0]))) { 12380 nativeProcs.add(st); 12381 } 12382 } 12383 } 12384 if (nativeProcs.size() > 0) { 12385 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, 12386 opts.isCheckinRequest, opts.isCompact); 12387 Debug.MemoryInfo mi = null; 12388 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 12389 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 12390 final int pid = r.pid; 12391 if (!opts.isCheckinRequest && opts.dumpDetails) { 12392 pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **"); 12393 } 12394 if (mi == null) { 12395 mi = new Debug.MemoryInfo(); 12396 } 12397 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 12398 Debug.getMemoryInfo(pid, mi); 12399 } else { 12400 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null); 12401 mi.dalvikPrivateDirty = (int)tmpLong[0]; 12402 } 12403 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, 12404 opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 12405 pid, r.baseName, 0, 0, 0, 0, 0, 0); 12406 if (opts.isCheckinRequest) { 12407 pw.println(); 12408 } 12409 } 12410 return; 12411 } 12412 } 12413 } 12414 pw.println("No process found for: " + proc); 12415 return; 12416 } 12417 12418 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 12419 opts.dumpDetails = true; 12420 } 12421 12422 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact); 12423 12424 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 12425 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 12426 long nativePss = 0; 12427 long nativeSwapPss = 0; 12428 long dalvikPss = 0; 12429 long dalvikSwapPss = 0; 12430 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12431 EmptyArray.LONG; 12432 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12433 EmptyArray.LONG; 12434 long otherPss = 0; 12435 long otherSwapPss = 0; 12436 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12437 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12438 12439 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 12440 long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 12441 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 12442 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 12443 12444 long totalPss = 0; 12445 long totalSwapPss = 0; 12446 long cachedPss = 0; 12447 long cachedSwapPss = 0; 12448 boolean hasSwapPss = false; 12449 12450 Debug.MemoryInfo mi = null; 12451 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 12452 final ProcessRecord r = procs.get(i); 12453 final IApplicationThread thread; 12454 final int pid; 12455 final int oomAdj; 12456 final boolean hasActivities; 12457 synchronized (this) { 12458 thread = r.thread; 12459 pid = r.pid; 12460 oomAdj = r.getSetAdjWithServices(); 12461 hasActivities = r.hasActivities(); 12462 } 12463 if (thread != null) { 12464 if (!opts.isCheckinRequest && opts.dumpDetails) { 12465 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 12466 } 12467 if (mi == null) { 12468 mi = new Debug.MemoryInfo(); 12469 } 12470 final int reportType; 12471 final long startTime; 12472 final long endTime; 12473 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 12474 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 12475 startTime = SystemClock.currentThreadTimeMillis(); 12476 Debug.getMemoryInfo(pid, mi); 12477 endTime = SystemClock.currentThreadTimeMillis(); 12478 hasSwapPss = mi.hasSwappedOutPss; 12479 } else { 12480 reportType = ProcessStats.ADD_PSS_EXTERNAL; 12481 startTime = SystemClock.currentThreadTimeMillis(); 12482 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null); 12483 endTime = SystemClock.currentThreadTimeMillis(); 12484 mi.dalvikPrivateDirty = (int)tmpLong[0]; 12485 } 12486 if (opts.dumpDetails) { 12487 if (opts.localOnly) { 12488 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails, 12489 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0); 12490 if (opts.isCheckinRequest) { 12491 pw.println(); 12492 } 12493 } else { 12494 pw.flush(); 12495 try { 12496 TransferPipe tp = new TransferPipe(); 12497 try { 12498 thread.dumpMemInfo(tp.getWriteFd(), 12499 mi, opts.isCheckinRequest, opts.dumpFullDetails, 12500 opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs); 12501 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000); 12502 } finally { 12503 tp.kill(); 12504 } 12505 } catch (IOException e) { 12506 if (!opts.isCheckinRequest) { 12507 pw.println("Got IoException! " + e); 12508 pw.flush(); 12509 } 12510 } catch (RemoteException e) { 12511 if (!opts.isCheckinRequest) { 12512 pw.println("Got RemoteException! " + e); 12513 pw.flush(); 12514 } 12515 } 12516 } 12517 } 12518 12519 final long myTotalPss = mi.getTotalPss(); 12520 final long myTotalUss = mi.getTotalUss(); 12521 final long myTotalRss = mi.getTotalRss(); 12522 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 12523 12524 synchronized (this) { 12525 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) { 12526 // Record this for posterity if the process has been stable. 12527 r.baseProcessTracker.addPss(myTotalPss, myTotalUss, myTotalRss, true, 12528 reportType, endTime-startTime, r.pkgList.mPkgList); 12529 for (int ipkg = r.pkgList.size() - 1; ipkg >= 0; ipkg--) { 12530 ProcessStats.ProcessStateHolder holder = r.pkgList.valueAt(ipkg); 12531 StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED, 12532 r.info.uid, 12533 holder.state.getName(), 12534 holder.state.getPackage(), 12535 myTotalPss, myTotalUss, myTotalRss, reportType, 12536 endTime-startTime, 12537 holder.appVersion); 12538 } 12539 } 12540 } 12541 12542 if (!opts.isCheckinRequest && mi != null) { 12543 totalPss += myTotalPss; 12544 totalSwapPss += myTotalSwapPss; 12545 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 12546 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 12547 myTotalSwapPss, pid, hasActivities); 12548 procMems.add(pssItem); 12549 procMemsMap.put(pid, pssItem); 12550 12551 nativePss += mi.nativePss; 12552 nativeSwapPss += mi.nativeSwappedOutPss; 12553 dalvikPss += mi.dalvikPss; 12554 dalvikSwapPss += mi.dalvikSwappedOutPss; 12555 for (int j=0; j<dalvikSubitemPss.length; j++) { 12556 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12557 dalvikSubitemSwapPss[j] += 12558 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12559 } 12560 otherPss += mi.otherPss; 12561 otherSwapPss += mi.otherSwappedOutPss; 12562 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12563 long mem = mi.getOtherPss(j); 12564 miscPss[j] += mem; 12565 otherPss -= mem; 12566 mem = mi.getOtherSwappedOutPss(j); 12567 miscSwapPss[j] += mem; 12568 otherSwapPss -= mem; 12569 } 12570 12571 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 12572 cachedPss += myTotalPss; 12573 cachedSwapPss += myTotalSwapPss; 12574 } 12575 12576 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 12577 if (oomIndex == (oomPss.length - 1) 12578 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 12579 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 12580 oomPss[oomIndex] += myTotalPss; 12581 oomSwapPss[oomIndex] += myTotalSwapPss; 12582 if (oomProcs[oomIndex] == null) { 12583 oomProcs[oomIndex] = new ArrayList<MemItem>(); 12584 } 12585 oomProcs[oomIndex].add(pssItem); 12586 break; 12587 } 12588 } 12589 } 12590 } 12591 } 12592 12593 long nativeProcTotalPss = 0; 12594 12595 if (!opts.isCheckinRequest && procs.size() > 1 && !opts.packages) { 12596 // If we are showing aggregations, also look for native processes to 12597 // include so that our aggregations are more accurate. 12598 updateCpuStatsNow(); 12599 mi = null; 12600 synchronized (mProcessCpuTracker) { 12601 final int N = mProcessCpuTracker.countStats(); 12602 for (int i=0; i<N; i++) { 12603 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 12604 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 12605 if (mi == null) { 12606 mi = new Debug.MemoryInfo(); 12607 } 12608 if (!brief && !opts.oomOnly) { 12609 Debug.getMemoryInfo(st.pid, mi); 12610 } else { 12611 mi.nativePss = (int)Debug.getPss(st.pid, tmpLong, null); 12612 mi.nativePrivateDirty = (int)tmpLong[0]; 12613 } 12614 12615 final long myTotalPss = mi.getTotalPss(); 12616 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 12617 totalPss += myTotalPss; 12618 totalSwapPss += myTotalSwapPss; 12619 nativeProcTotalPss += myTotalPss; 12620 12621 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 12622 st.name, myTotalPss, mi.getSummaryTotalSwapPss(), st.pid, false); 12623 procMems.add(pssItem); 12624 12625 nativePss += mi.nativePss; 12626 nativeSwapPss += mi.nativeSwappedOutPss; 12627 dalvikPss += mi.dalvikPss; 12628 dalvikSwapPss += mi.dalvikSwappedOutPss; 12629 for (int j=0; j<dalvikSubitemPss.length; j++) { 12630 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12631 dalvikSubitemSwapPss[j] += 12632 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12633 } 12634 otherPss += mi.otherPss; 12635 otherSwapPss += mi.otherSwappedOutPss; 12636 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12637 long mem = mi.getOtherPss(j); 12638 miscPss[j] += mem; 12639 otherPss -= mem; 12640 mem = mi.getOtherSwappedOutPss(j); 12641 miscSwapPss[j] += mem; 12642 otherSwapPss -= mem; 12643 } 12644 oomPss[0] += myTotalPss; 12645 oomSwapPss[0] += myTotalSwapPss; 12646 if (oomProcs[0] == null) { 12647 oomProcs[0] = new ArrayList<MemItem>(); 12648 } 12649 oomProcs[0].add(pssItem); 12650 } 12651 } 12652 } 12653 12654 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 12655 12656 catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, -1)); 12657 final int dalvikId = -2; 12658 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, dalvikId)); 12659 catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, -3)); 12660 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12661 String label = Debug.MemoryInfo.getOtherLabel(j); 12662 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], j)); 12663 } 12664 if (dalvikSubitemPss.length > 0) { 12665 // Add dalvik subitems. 12666 for (MemItem memItem : catMems) { 12667 int memItemStart = 0, memItemEnd = 0; 12668 if (memItem.id == dalvikId) { 12669 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 12670 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 12671 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 12672 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 12673 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 12674 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 12675 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 12676 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 12677 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 12678 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 12679 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 12680 } else { 12681 continue; // No subitems, continue. 12682 } 12683 memItem.subitems = new ArrayList<MemItem>(); 12684 for (int j=memItemStart; j<=memItemEnd; j++) { 12685 final String name = Debug.MemoryInfo.getOtherLabel( 12686 Debug.MemoryInfo.NUM_OTHER_STATS + j); 12687 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 12688 dalvikSubitemSwapPss[j], j)); 12689 } 12690 } 12691 } 12692 12693 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 12694 for (int j=0; j<oomPss.length; j++) { 12695 if (oomPss[j] != 0) { 12696 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 12697 : DUMP_MEM_OOM_LABEL[j]; 12698 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], 12699 DUMP_MEM_OOM_ADJ[j]); 12700 item.subitems = oomProcs[j]; 12701 oomMems.add(item); 12702 } 12703 } 12704 12705 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && totalSwapPss != 0; 12706 if (!brief && !opts.oomOnly && !opts.isCompact) { 12707 pw.println(); 12708 pw.println("Total PSS by process:"); 12709 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, opts.dumpSwapPss); 12710 pw.println(); 12711 } 12712 if (!opts.isCompact) { 12713 pw.println("Total PSS by OOM adjustment:"); 12714 } 12715 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, opts.dumpSwapPss); 12716 if (!brief && !opts.oomOnly) { 12717 PrintWriter out = categoryPw != null ? categoryPw : pw; 12718 if (!opts.isCompact) { 12719 out.println(); 12720 out.println("Total PSS by category:"); 12721 } 12722 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, opts.dumpSwapPss); 12723 } 12724 if (!opts.isCompact) { 12725 pw.println(); 12726 } 12727 MemInfoReader memInfo = new MemInfoReader(); 12728 memInfo.readMemInfo(); 12729 if (nativeProcTotalPss > 0) { 12730 synchronized (this) { 12731 final long cachedKb = memInfo.getCachedSizeKb(); 12732 final long freeKb = memInfo.getFreeSizeKb(); 12733 final long zramKb = memInfo.getZramTotalSizeKb(); 12734 final long kernelKb = memInfo.getKernelUsedSizeKb(); 12735 EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024, 12736 kernelKb*1024, nativeProcTotalPss*1024); 12737 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 12738 nativeProcTotalPss); 12739 } 12740 } 12741 if (!brief) { 12742 if (!opts.isCompact) { 12743 pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb())); 12744 pw.print(" (status "); 12745 switch (mLastMemoryLevel) { 12746 case ProcessStats.ADJ_MEM_FACTOR_NORMAL: 12747 pw.println("normal)"); 12748 break; 12749 case ProcessStats.ADJ_MEM_FACTOR_MODERATE: 12750 pw.println("moderate)"); 12751 break; 12752 case ProcessStats.ADJ_MEM_FACTOR_LOW: 12753 pw.println("low)"); 12754 break; 12755 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 12756 pw.println("critical)"); 12757 break; 12758 default: 12759 pw.print(mLastMemoryLevel); 12760 pw.println(")"); 12761 break; 12762 } 12763 pw.print(" Free RAM: "); 12764 pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb() 12765 + memInfo.getFreeSizeKb())); 12766 pw.print(" ("); 12767 pw.print(stringifyKBSize(cachedPss)); 12768 pw.print(" cached pss + "); 12769 pw.print(stringifyKBSize(memInfo.getCachedSizeKb())); 12770 pw.print(" cached kernel + "); 12771 pw.print(stringifyKBSize(memInfo.getFreeSizeKb())); 12772 pw.println(" free)"); 12773 } else { 12774 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 12775 pw.print(cachedPss + memInfo.getCachedSizeKb() 12776 + memInfo.getFreeSizeKb()); pw.print(","); 12777 pw.println(totalPss - cachedPss); 12778 } 12779 } 12780 long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss) 12781 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 12782 - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb(); 12783 if (!opts.isCompact) { 12784 pw.print(" Used RAM: "); pw.print(stringifyKBSize(totalPss - cachedPss 12785 + memInfo.getKernelUsedSizeKb())); pw.print(" ("); 12786 pw.print(stringifyKBSize(totalPss - cachedPss)); pw.print(" used pss + "); 12787 pw.print(stringifyKBSize(memInfo.getKernelUsedSizeKb())); pw.print(" kernel)\n"); 12788 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM)); 12789 } else { 12790 pw.print("lostram,"); pw.println(lostRAM); 12791 } 12792 if (!brief) { 12793 if (memInfo.getZramTotalSizeKb() != 0) { 12794 if (!opts.isCompact) { 12795 pw.print(" ZRAM: "); 12796 pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb())); 12797 pw.print(" physical used for "); 12798 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb() 12799 - memInfo.getSwapFreeSizeKb())); 12800 pw.print(" in swap ("); 12801 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb())); 12802 pw.println(" total swap)"); 12803 } else { 12804 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 12805 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 12806 pw.println(memInfo.getSwapFreeSizeKb()); 12807 } 12808 } 12809 final long[] ksm = getKsmInfo(); 12810 if (!opts.isCompact) { 12811 if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 12812 || ksm[KSM_VOLATILE] != 0) { 12813 pw.print(" KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING])); 12814 pw.print(" saved from shared "); 12815 pw.print(stringifyKBSize(ksm[KSM_SHARED])); 12816 pw.print(" "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED])); 12817 pw.print(" unshared; "); 12818 pw.print(stringifyKBSize( 12819 ksm[KSM_VOLATILE])); pw.println(" volatile"); 12820 } 12821 pw.print(" Tuning: "); 12822 pw.print(ActivityManager.staticGetMemoryClass()); 12823 pw.print(" (large "); 12824 pw.print(ActivityManager.staticGetLargeMemoryClass()); 12825 pw.print("), oom "); 12826 pw.print(stringifySize( 12827 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024)); 12828 pw.print(", restore limit "); 12829 pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb())); 12830 if (ActivityManager.isLowRamDeviceStatic()) { 12831 pw.print(" (low-ram)"); 12832 } 12833 if (ActivityManager.isHighEndGfx()) { 12834 pw.print(" (high-end-gfx)"); 12835 } 12836 pw.println(); 12837 } else { 12838 pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(","); 12839 pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]); 12840 pw.print(","); pw.println(ksm[KSM_VOLATILE]); 12841 pw.print("tuning,"); 12842 pw.print(ActivityManager.staticGetMemoryClass()); 12843 pw.print(','); 12844 pw.print(ActivityManager.staticGetLargeMemoryClass()); 12845 pw.print(','); 12846 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 12847 if (ActivityManager.isLowRamDeviceStatic()) { 12848 pw.print(",low-ram"); 12849 } 12850 if (ActivityManager.isHighEndGfx()) { 12851 pw.print(",high-end-gfx"); 12852 } 12853 pw.println(); 12854 } 12855 } 12856 } 12857 } 12858 dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)12859 private final void dumpApplicationMemoryUsage(FileDescriptor fd, 12860 MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, 12861 ArrayList<ProcessRecord> procs) { 12862 final long uptimeMs = SystemClock.uptimeMillis(); 12863 final long realtimeMs = SystemClock.elapsedRealtime(); 12864 final long[] tmpLong = new long[1]; 12865 12866 if (procs == null) { 12867 // No Java processes. Maybe they want to print a native process. 12868 String proc = "N/A"; 12869 if (innerArgs.length > 0) { 12870 proc = innerArgs[0]; 12871 if (proc.charAt(0) != '-') { 12872 ArrayList<ProcessCpuTracker.Stats> nativeProcs 12873 = new ArrayList<ProcessCpuTracker.Stats>(); 12874 updateCpuStatsNow(); 12875 int findPid = -1; 12876 try { 12877 findPid = Integer.parseInt(innerArgs[0]); 12878 } catch (NumberFormatException e) { 12879 } 12880 synchronized (mProcessCpuTracker) { 12881 final int N = mProcessCpuTracker.countStats(); 12882 for (int i=0; i<N; i++) { 12883 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 12884 if (st.pid == findPid || (st.baseName != null 12885 && st.baseName.equals(innerArgs[0]))) { 12886 nativeProcs.add(st); 12887 } 12888 } 12889 } 12890 if (nativeProcs.size() > 0) { 12891 ProtoOutputStream proto = new ProtoOutputStream(fd); 12892 12893 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 12894 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 12895 Debug.MemoryInfo mi = null; 12896 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 12897 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 12898 final int pid = r.pid; 12899 final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES); 12900 12901 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 12902 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName); 12903 12904 if (mi == null) { 12905 mi = new Debug.MemoryInfo(); 12906 } 12907 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 12908 Debug.getMemoryInfo(pid, mi); 12909 } else { 12910 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null); 12911 mi.dalvikPrivateDirty = (int)tmpLong[0]; 12912 } 12913 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 12914 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 12915 12916 proto.end(nToken); 12917 } 12918 12919 proto.flush(); 12920 return; 12921 } 12922 } 12923 } 12924 Log.d(TAG, "No process found for: " + innerArgs[0]); 12925 return; 12926 } 12927 12928 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 12929 opts.dumpDetails = true; 12930 } 12931 12932 ProtoOutputStream proto = new ProtoOutputStream(fd); 12933 12934 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 12935 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 12936 12937 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 12938 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 12939 long nativePss = 0; 12940 long nativeSwapPss = 0; 12941 long dalvikPss = 0; 12942 long dalvikSwapPss = 0; 12943 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12944 EmptyArray.LONG; 12945 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12946 EmptyArray.LONG; 12947 long otherPss = 0; 12948 long otherSwapPss = 0; 12949 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12950 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12951 12952 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 12953 long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 12954 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 12955 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 12956 12957 long totalPss = 0; 12958 long totalSwapPss = 0; 12959 long cachedPss = 0; 12960 long cachedSwapPss = 0; 12961 boolean hasSwapPss = false; 12962 12963 Debug.MemoryInfo mi = null; 12964 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 12965 final ProcessRecord r = procs.get(i); 12966 final IApplicationThread thread; 12967 final int pid; 12968 final int oomAdj; 12969 final boolean hasActivities; 12970 synchronized (this) { 12971 thread = r.thread; 12972 pid = r.pid; 12973 oomAdj = r.getSetAdjWithServices(); 12974 hasActivities = r.hasActivities(); 12975 } 12976 if (thread == null) { 12977 continue; 12978 } 12979 if (mi == null) { 12980 mi = new Debug.MemoryInfo(); 12981 } 12982 final int reportType; 12983 final long startTime; 12984 final long endTime; 12985 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 12986 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 12987 startTime = SystemClock.currentThreadTimeMillis(); 12988 Debug.getMemoryInfo(pid, mi); 12989 endTime = SystemClock.currentThreadTimeMillis(); 12990 hasSwapPss = mi.hasSwappedOutPss; 12991 } else { 12992 reportType = ProcessStats.ADD_PSS_EXTERNAL; 12993 startTime = SystemClock.currentThreadTimeMillis(); 12994 mi.dalvikPss = (int) Debug.getPss(pid, tmpLong, null); 12995 endTime = SystemClock.currentThreadTimeMillis(); 12996 mi.dalvikPrivateDirty = (int) tmpLong[0]; 12997 } 12998 if (opts.dumpDetails) { 12999 if (opts.localOnly) { 13000 final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES); 13001 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY); 13002 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 13003 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName); 13004 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 13005 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 13006 proto.end(mToken); 13007 proto.end(aToken); 13008 } else { 13009 try { 13010 ByteTransferPipe tp = new ByteTransferPipe(); 13011 try { 13012 thread.dumpMemInfoProto(tp.getWriteFd(), 13013 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 13014 opts.dumpUnreachable, innerArgs); 13015 proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get()); 13016 } finally { 13017 tp.kill(); 13018 } 13019 } catch (IOException e) { 13020 Log.e(TAG, "Got IOException!", e); 13021 } catch (RemoteException e) { 13022 Log.e(TAG, "Got RemoteException!", e); 13023 } 13024 } 13025 } 13026 13027 final long myTotalPss = mi.getTotalPss(); 13028 final long myTotalUss = mi.getTotalUss(); 13029 final long myTotalRss = mi.getTotalRss(); 13030 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 13031 13032 synchronized (this) { 13033 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) { 13034 // Record this for posterity if the process has been stable. 13035 r.baseProcessTracker.addPss(myTotalPss, myTotalUss, myTotalRss, true, 13036 reportType, endTime-startTime, r.pkgList.mPkgList); 13037 for (int ipkg = r.pkgList.size() - 1; ipkg >= 0; ipkg--) { 13038 ProcessStats.ProcessStateHolder holder = r.pkgList.valueAt(ipkg); 13039 StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED, 13040 r.info.uid, 13041 holder.state.getName(), 13042 holder.state.getPackage(), 13043 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime, 13044 holder.appVersion); 13045 } 13046 } 13047 } 13048 13049 if (!opts.isCheckinRequest && mi != null) { 13050 totalPss += myTotalPss; 13051 totalSwapPss += myTotalSwapPss; 13052 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 13053 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 13054 myTotalSwapPss, pid, hasActivities); 13055 procMems.add(pssItem); 13056 procMemsMap.put(pid, pssItem); 13057 13058 nativePss += mi.nativePss; 13059 nativeSwapPss += mi.nativeSwappedOutPss; 13060 dalvikPss += mi.dalvikPss; 13061 dalvikSwapPss += mi.dalvikSwappedOutPss; 13062 for (int j=0; j<dalvikSubitemPss.length; j++) { 13063 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13064 dalvikSubitemSwapPss[j] += 13065 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13066 } 13067 otherPss += mi.otherPss; 13068 otherSwapPss += mi.otherSwappedOutPss; 13069 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13070 long mem = mi.getOtherPss(j); 13071 miscPss[j] += mem; 13072 otherPss -= mem; 13073 mem = mi.getOtherSwappedOutPss(j); 13074 miscSwapPss[j] += mem; 13075 otherSwapPss -= mem; 13076 } 13077 13078 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 13079 cachedPss += myTotalPss; 13080 cachedSwapPss += myTotalSwapPss; 13081 } 13082 13083 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 13084 if (oomIndex == (oomPss.length - 1) 13085 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 13086 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 13087 oomPss[oomIndex] += myTotalPss; 13088 oomSwapPss[oomIndex] += myTotalSwapPss; 13089 if (oomProcs[oomIndex] == null) { 13090 oomProcs[oomIndex] = new ArrayList<MemItem>(); 13091 } 13092 oomProcs[oomIndex].add(pssItem); 13093 break; 13094 } 13095 } 13096 } 13097 } 13098 13099 long nativeProcTotalPss = 0; 13100 13101 if (procs.size() > 1 && !opts.packages) { 13102 // If we are showing aggregations, also look for native processes to 13103 // include so that our aggregations are more accurate. 13104 updateCpuStatsNow(); 13105 mi = null; 13106 synchronized (mProcessCpuTracker) { 13107 final int N = mProcessCpuTracker.countStats(); 13108 for (int i=0; i<N; i++) { 13109 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 13110 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 13111 if (mi == null) { 13112 mi = new Debug.MemoryInfo(); 13113 } 13114 if (!brief && !opts.oomOnly) { 13115 Debug.getMemoryInfo(st.pid, mi); 13116 } else { 13117 mi.nativePss = (int)Debug.getPss(st.pid, tmpLong, null); 13118 mi.nativePrivateDirty = (int)tmpLong[0]; 13119 } 13120 13121 final long myTotalPss = mi.getTotalPss(); 13122 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 13123 totalPss += myTotalPss; 13124 nativeProcTotalPss += myTotalPss; 13125 13126 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 13127 st.name, myTotalPss, mi.getSummaryTotalSwapPss(), st.pid, false); 13128 procMems.add(pssItem); 13129 13130 nativePss += mi.nativePss; 13131 nativeSwapPss += mi.nativeSwappedOutPss; 13132 dalvikPss += mi.dalvikPss; 13133 dalvikSwapPss += mi.dalvikSwappedOutPss; 13134 for (int j=0; j<dalvikSubitemPss.length; j++) { 13135 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13136 dalvikSubitemSwapPss[j] += 13137 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13138 } 13139 otherPss += mi.otherPss; 13140 otherSwapPss += mi.otherSwappedOutPss; 13141 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13142 long mem = mi.getOtherPss(j); 13143 miscPss[j] += mem; 13144 otherPss -= mem; 13145 mem = mi.getOtherSwappedOutPss(j); 13146 miscSwapPss[j] += mem; 13147 otherSwapPss -= mem; 13148 } 13149 oomPss[0] += myTotalPss; 13150 oomSwapPss[0] += myTotalSwapPss; 13151 if (oomProcs[0] == null) { 13152 oomProcs[0] = new ArrayList<MemItem>(); 13153 } 13154 oomProcs[0].add(pssItem); 13155 } 13156 } 13157 } 13158 13159 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 13160 13161 catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, -1)); 13162 final int dalvikId = -2; 13163 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, dalvikId)); 13164 catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, -3)); 13165 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13166 String label = Debug.MemoryInfo.getOtherLabel(j); 13167 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], j)); 13168 } 13169 if (dalvikSubitemPss.length > 0) { 13170 // Add dalvik subitems. 13171 for (MemItem memItem : catMems) { 13172 int memItemStart = 0, memItemEnd = 0; 13173 if (memItem.id == dalvikId) { 13174 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 13175 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 13176 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 13177 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 13178 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 13179 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 13180 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 13181 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 13182 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 13183 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 13184 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 13185 } else { 13186 continue; // No subitems, continue. 13187 } 13188 memItem.subitems = new ArrayList<MemItem>(); 13189 for (int j=memItemStart; j<=memItemEnd; j++) { 13190 final String name = Debug.MemoryInfo.getOtherLabel( 13191 Debug.MemoryInfo.NUM_OTHER_STATS + j); 13192 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 13193 dalvikSubitemSwapPss[j], j)); 13194 } 13195 } 13196 } 13197 13198 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 13199 for (int j=0; j<oomPss.length; j++) { 13200 if (oomPss[j] != 0) { 13201 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 13202 : DUMP_MEM_OOM_LABEL[j]; 13203 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], 13204 DUMP_MEM_OOM_ADJ[j]); 13205 item.subitems = oomProcs[j]; 13206 oomMems.add(item); 13207 } 13208 } 13209 13210 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && totalSwapPss != 0; 13211 if (!opts.oomOnly) { 13212 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc", 13213 procMems, true, opts.dumpSwapPss); 13214 } 13215 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom", 13216 oomMems, false, opts.dumpSwapPss); 13217 if (!brief && !opts.oomOnly) { 13218 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat", 13219 catMems, true, opts.dumpSwapPss); 13220 } 13221 MemInfoReader memInfo = new MemInfoReader(); 13222 memInfo.readMemInfo(); 13223 if (nativeProcTotalPss > 0) { 13224 synchronized (this) { 13225 final long cachedKb = memInfo.getCachedSizeKb(); 13226 final long freeKb = memInfo.getFreeSizeKb(); 13227 final long zramKb = memInfo.getZramTotalSizeKb(); 13228 final long kernelKb = memInfo.getKernelUsedSizeKb(); 13229 EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024, 13230 kernelKb*1024, nativeProcTotalPss*1024); 13231 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 13232 nativeProcTotalPss); 13233 } 13234 } 13235 if (!brief) { 13236 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb()); 13237 proto.write(MemInfoDumpProto.STATUS, mLastMemoryLevel); 13238 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss); 13239 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb()); 13240 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb()); 13241 } 13242 long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss) 13243 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 13244 - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb(); 13245 proto.write(MemInfoDumpProto.USED_PSS_KB, totalPss - cachedPss); 13246 proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb()); 13247 proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM); 13248 if (!brief) { 13249 if (memInfo.getZramTotalSizeKb() != 0) { 13250 proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb()); 13251 proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB, 13252 memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb()); 13253 proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb()); 13254 } 13255 final long[] ksm = getKsmInfo(); 13256 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]); 13257 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]); 13258 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]); 13259 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]); 13260 13261 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass()); 13262 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass()); 13263 proto.write(MemInfoDumpProto.OOM_KB, 13264 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024); 13265 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB, 13266 mProcessList.getCachedRestoreThresholdKb()); 13267 13268 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic()); 13269 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx()); 13270 } 13271 } 13272 13273 proto.flush(); 13274 } 13275 appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)13276 private void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, 13277 long memtrack, String name) { 13278 sb.append(" "); 13279 sb.append(ProcessList.makeOomAdjString(oomAdj, false)); 13280 sb.append(' '); 13281 sb.append(ProcessList.makeProcStateString(procState)); 13282 sb.append(' '); 13283 ProcessList.appendRamKb(sb, pss); 13284 sb.append(": "); 13285 sb.append(name); 13286 if (memtrack > 0) { 13287 sb.append(" ("); 13288 sb.append(stringifyKBSize(memtrack)); 13289 sb.append(" memtrack)"); 13290 } 13291 } 13292 appendMemInfo(StringBuilder sb, ProcessMemInfo mi)13293 private void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) { 13294 appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name); 13295 sb.append(" (pid "); 13296 sb.append(mi.pid); 13297 sb.append(") "); 13298 sb.append(mi.adjType); 13299 sb.append('\n'); 13300 if (mi.adjReason != null) { 13301 sb.append(" "); 13302 sb.append(mi.adjReason); 13303 sb.append('\n'); 13304 } 13305 } 13306 reportMemUsage(ArrayList<ProcessMemInfo> memInfos)13307 void reportMemUsage(ArrayList<ProcessMemInfo> memInfos) { 13308 final SparseArray<ProcessMemInfo> infoMap = new SparseArray<>(memInfos.size()); 13309 for (int i=0, N=memInfos.size(); i<N; i++) { 13310 ProcessMemInfo mi = memInfos.get(i); 13311 infoMap.put(mi.pid, mi); 13312 } 13313 updateCpuStatsNow(); 13314 long[] memtrackTmp = new long[1]; 13315 long[] swaptrackTmp = new long[2]; 13316 final List<ProcessCpuTracker.Stats> stats; 13317 // Get a list of Stats that have vsize > 0 13318 synchronized (mProcessCpuTracker) { 13319 stats = mProcessCpuTracker.getStats((st) -> { 13320 return st.vsize > 0; 13321 }); 13322 } 13323 final int statsCount = stats.size(); 13324 for (int i = 0; i < statsCount; i++) { 13325 ProcessCpuTracker.Stats st = stats.get(i); 13326 long pss = Debug.getPss(st.pid, swaptrackTmp, memtrackTmp); 13327 if (pss > 0) { 13328 if (infoMap.indexOfKey(st.pid) < 0) { 13329 ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid, 13330 ProcessList.NATIVE_ADJ, -1, "native", null); 13331 mi.pss = pss; 13332 mi.swapPss = swaptrackTmp[1]; 13333 mi.memtrack = memtrackTmp[0]; 13334 memInfos.add(mi); 13335 } 13336 } 13337 } 13338 13339 long totalPss = 0; 13340 long totalSwapPss = 0; 13341 long totalMemtrack = 0; 13342 for (int i=0, N=memInfos.size(); i<N; i++) { 13343 ProcessMemInfo mi = memInfos.get(i); 13344 if (mi.pss == 0) { 13345 mi.pss = Debug.getPss(mi.pid, swaptrackTmp, memtrackTmp); 13346 mi.swapPss = swaptrackTmp[1]; 13347 mi.memtrack = memtrackTmp[0]; 13348 } 13349 totalPss += mi.pss; 13350 totalSwapPss += mi.swapPss; 13351 totalMemtrack += mi.memtrack; 13352 } 13353 Collections.sort(memInfos, new Comparator<ProcessMemInfo>() { 13354 @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) { 13355 if (lhs.oomAdj != rhs.oomAdj) { 13356 return lhs.oomAdj < rhs.oomAdj ? -1 : 1; 13357 } 13358 if (lhs.pss != rhs.pss) { 13359 return lhs.pss < rhs.pss ? 1 : -1; 13360 } 13361 return 0; 13362 } 13363 }); 13364 13365 StringBuilder tag = new StringBuilder(128); 13366 StringBuilder stack = new StringBuilder(128); 13367 tag.append("Low on memory -- "); 13368 appendMemBucket(tag, totalPss, "total", false); 13369 appendMemBucket(stack, totalPss, "total", true); 13370 13371 StringBuilder fullNativeBuilder = new StringBuilder(1024); 13372 StringBuilder shortNativeBuilder = new StringBuilder(1024); 13373 StringBuilder fullJavaBuilder = new StringBuilder(1024); 13374 13375 boolean firstLine = true; 13376 int lastOomAdj = Integer.MIN_VALUE; 13377 long extraNativeRam = 0; 13378 long extraNativeMemtrack = 0; 13379 long cachedPss = 0; 13380 for (int i=0, N=memInfos.size(); i<N; i++) { 13381 ProcessMemInfo mi = memInfos.get(i); 13382 13383 if (mi.oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 13384 cachedPss += mi.pss; 13385 } 13386 13387 if (mi.oomAdj != ProcessList.NATIVE_ADJ 13388 && (mi.oomAdj < ProcessList.SERVICE_ADJ 13389 || mi.oomAdj == ProcessList.HOME_APP_ADJ 13390 || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) { 13391 if (lastOomAdj != mi.oomAdj) { 13392 lastOomAdj = mi.oomAdj; 13393 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) { 13394 tag.append(" / "); 13395 } 13396 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) { 13397 if (firstLine) { 13398 stack.append(":"); 13399 firstLine = false; 13400 } 13401 stack.append("\n\t at "); 13402 } else { 13403 stack.append("$"); 13404 } 13405 } else { 13406 tag.append(" "); 13407 stack.append("$"); 13408 } 13409 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) { 13410 appendMemBucket(tag, mi.pss, mi.name, false); 13411 } 13412 appendMemBucket(stack, mi.pss, mi.name, true); 13413 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ 13414 && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) { 13415 stack.append("("); 13416 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) { 13417 if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) { 13418 stack.append(DUMP_MEM_OOM_LABEL[k]); 13419 stack.append(":"); 13420 stack.append(DUMP_MEM_OOM_ADJ[k]); 13421 } 13422 } 13423 stack.append(")"); 13424 } 13425 } 13426 13427 appendMemInfo(fullNativeBuilder, mi); 13428 if (mi.oomAdj == ProcessList.NATIVE_ADJ) { 13429 // The short form only has native processes that are >= 512K. 13430 if (mi.pss >= 512) { 13431 appendMemInfo(shortNativeBuilder, mi); 13432 } else { 13433 extraNativeRam += mi.pss; 13434 extraNativeMemtrack += mi.memtrack; 13435 } 13436 } else { 13437 // Short form has all other details, but if we have collected RAM 13438 // from smaller native processes let's dump a summary of that. 13439 if (extraNativeRam > 0) { 13440 appendBasicMemEntry(shortNativeBuilder, ProcessList.NATIVE_ADJ, 13441 -1, extraNativeRam, extraNativeMemtrack, "(Other native)"); 13442 shortNativeBuilder.append('\n'); 13443 extraNativeRam = 0; 13444 } 13445 appendMemInfo(fullJavaBuilder, mi); 13446 } 13447 } 13448 13449 fullJavaBuilder.append(" "); 13450 ProcessList.appendRamKb(fullJavaBuilder, totalPss); 13451 fullJavaBuilder.append(": TOTAL"); 13452 if (totalMemtrack > 0) { 13453 fullJavaBuilder.append(" ("); 13454 fullJavaBuilder.append(stringifyKBSize(totalMemtrack)); 13455 fullJavaBuilder.append(" memtrack)"); 13456 } else { 13457 } 13458 fullJavaBuilder.append("\n"); 13459 13460 MemInfoReader memInfo = new MemInfoReader(); 13461 memInfo.readMemInfo(); 13462 final long[] infos = memInfo.getRawInfo(); 13463 13464 StringBuilder memInfoBuilder = new StringBuilder(1024); 13465 Debug.getMemInfo(infos); 13466 memInfoBuilder.append(" MemInfo: "); 13467 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SLAB])).append(" slab, "); 13468 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SHMEM])).append(" shmem, "); 13469 memInfoBuilder.append(stringifyKBSize( 13470 infos[Debug.MEMINFO_VM_ALLOC_USED])).append(" vm alloc, "); 13471 memInfoBuilder.append(stringifyKBSize( 13472 infos[Debug.MEMINFO_PAGE_TABLES])).append(" page tables "); 13473 memInfoBuilder.append(stringifyKBSize( 13474 infos[Debug.MEMINFO_KERNEL_STACK])).append(" kernel stack\n"); 13475 memInfoBuilder.append(" "); 13476 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_BUFFERS])).append(" buffers, "); 13477 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_CACHED])).append(" cached, "); 13478 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_MAPPED])).append(" mapped, "); 13479 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_FREE])).append(" free\n"); 13480 if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) { 13481 memInfoBuilder.append(" ZRAM: "); 13482 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_ZRAM_TOTAL])); 13483 memInfoBuilder.append(" RAM, "); 13484 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SWAP_TOTAL])); 13485 memInfoBuilder.append(" swap total, "); 13486 memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SWAP_FREE])); 13487 memInfoBuilder.append(" swap free\n"); 13488 } 13489 final long[] ksm = getKsmInfo(); 13490 if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 13491 || ksm[KSM_VOLATILE] != 0) { 13492 memInfoBuilder.append(" KSM: "); 13493 memInfoBuilder.append(stringifyKBSize(ksm[KSM_SHARING])); 13494 memInfoBuilder.append(" saved from shared "); 13495 memInfoBuilder.append(stringifyKBSize(ksm[KSM_SHARED])); 13496 memInfoBuilder.append("\n "); 13497 memInfoBuilder.append(stringifyKBSize(ksm[KSM_UNSHARED])); 13498 memInfoBuilder.append(" unshared; "); 13499 memInfoBuilder.append(stringifyKBSize(ksm[KSM_VOLATILE])); 13500 memInfoBuilder.append(" volatile\n"); 13501 } 13502 memInfoBuilder.append(" Free RAM: "); 13503 memInfoBuilder.append(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb() 13504 + memInfo.getFreeSizeKb())); 13505 memInfoBuilder.append("\n"); 13506 memInfoBuilder.append(" Used RAM: "); 13507 memInfoBuilder.append(stringifyKBSize( 13508 totalPss - cachedPss + memInfo.getKernelUsedSizeKb())); 13509 memInfoBuilder.append("\n"); 13510 memInfoBuilder.append(" Lost RAM: "); 13511 memInfoBuilder.append(stringifyKBSize(memInfo.getTotalSizeKb() 13512 - (totalPss - totalSwapPss) - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 13513 - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb())); 13514 memInfoBuilder.append("\n"); 13515 Slog.i(TAG, "Low on memory:"); 13516 Slog.i(TAG, shortNativeBuilder.toString()); 13517 Slog.i(TAG, fullJavaBuilder.toString()); 13518 Slog.i(TAG, memInfoBuilder.toString()); 13519 13520 StringBuilder dropBuilder = new StringBuilder(1024); 13521 /* 13522 StringWriter oomSw = new StringWriter(); 13523 PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256); 13524 StringWriter catSw = new StringWriter(); 13525 PrintWriter catPw = new FastPrintWriter(catSw, false, 256); 13526 String[] emptyArgs = new String[] { }; 13527 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw); 13528 oomPw.flush(); 13529 String oomString = oomSw.toString(); 13530 */ 13531 dropBuilder.append("Low on memory:"); 13532 dropBuilder.append(stack); 13533 dropBuilder.append('\n'); 13534 dropBuilder.append(fullNativeBuilder); 13535 dropBuilder.append(fullJavaBuilder); 13536 dropBuilder.append('\n'); 13537 dropBuilder.append(memInfoBuilder); 13538 dropBuilder.append('\n'); 13539 /* 13540 dropBuilder.append(oomString); 13541 dropBuilder.append('\n'); 13542 */ 13543 StringWriter catSw = new StringWriter(); 13544 synchronized (ActivityManagerService.this) { 13545 PrintWriter catPw = new FastPrintWriter(catSw, false, 256); 13546 String[] emptyArgs = new String[] { }; 13547 catPw.println(); 13548 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null, -1); 13549 catPw.println(); 13550 mServices.newServiceDumperLocked(null, catPw, emptyArgs, 0, 13551 false, null).dumpLocked(); 13552 catPw.println(); 13553 mAtmInternal.dump(DUMP_ACTIVITIES_CMD, null, catPw, emptyArgs, 0, false, false, null); 13554 catPw.flush(); 13555 } 13556 dropBuilder.append(catSw.toString()); 13557 StatsLog.write(StatsLog.LOW_MEM_REPORTED); 13558 addErrorToDropBox("lowmem", null, "system_server", null, 13559 null, null, tag.toString(), dropBuilder.toString(), null, null); 13560 //Slog.i(TAG, "Sent to dropbox:"); 13561 //Slog.i(TAG, dropBuilder.toString()); 13562 synchronized (ActivityManagerService.this) { 13563 long now = SystemClock.uptimeMillis(); 13564 if (mLastMemUsageReportTime < now) { 13565 mLastMemUsageReportTime = now; 13566 } 13567 } 13568 } 13569 13570 /** 13571 * Searches array of arguments for the specified string 13572 * @param args array of argument strings 13573 * @param value value to search for 13574 * @return true if the value is contained in the array 13575 */ scanArgs(String[] args, String value)13576 private static boolean scanArgs(String[] args, String value) { 13577 if (args != null) { 13578 for (String arg : args) { 13579 if (value.equals(arg)) { 13580 return true; 13581 } 13582 } 13583 } 13584 return false; 13585 } 13586 removeDyingProviderLocked(ProcessRecord proc, ContentProviderRecord cpr, boolean always)13587 private final boolean removeDyingProviderLocked(ProcessRecord proc, 13588 ContentProviderRecord cpr, boolean always) { 13589 final boolean inLaunching = mLaunchingProviders.contains(cpr); 13590 13591 if (!inLaunching || always) { 13592 synchronized (cpr) { 13593 cpr.launchingApp = null; 13594 cpr.notifyAll(); 13595 } 13596 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid)); 13597 String names[] = cpr.info.authority.split(";"); 13598 for (int j = 0; j < names.length; j++) { 13599 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid)); 13600 } 13601 } 13602 13603 for (int i = cpr.connections.size() - 1; i >= 0; i--) { 13604 ContentProviderConnection conn = cpr.connections.get(i); 13605 if (conn.waiting) { 13606 // If this connection is waiting for the provider, then we don't 13607 // need to mess with its process unless we are always removing 13608 // or for some reason the provider is not currently launching. 13609 if (inLaunching && !always) { 13610 continue; 13611 } 13612 } 13613 ProcessRecord capp = conn.client; 13614 conn.dead = true; 13615 if (conn.stableCount > 0) { 13616 if (!capp.isPersistent() && capp.thread != null 13617 && capp.pid != 0 13618 && capp.pid != MY_PID) { 13619 capp.kill("depends on provider " 13620 + cpr.name.flattenToShortString() 13621 + " in dying proc " + (proc != null ? proc.processName : "??") 13622 + " (adj " + (proc != null ? proc.setAdj : "??") + ")", true); 13623 } 13624 } else if (capp.thread != null && conn.provider.provider != null) { 13625 try { 13626 capp.thread.unstableProviderDied(conn.provider.provider.asBinder()); 13627 } catch (RemoteException e) { 13628 } 13629 // In the protocol here, we don't expect the client to correctly 13630 // clean up this connection, we'll just remove it. 13631 cpr.connections.remove(i); 13632 if (conn.client.conProviders.remove(conn)) { 13633 stopAssociationLocked(capp.uid, capp.processName, cpr.uid, 13634 cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName); 13635 } 13636 } 13637 } 13638 13639 if (inLaunching && always) { 13640 mLaunchingProviders.remove(cpr); 13641 } 13642 return inLaunching; 13643 } 13644 13645 /** 13646 * Main code for cleaning up a process when it has gone away. This is 13647 * called both as a result of the process dying, or directly when stopping 13648 * a process when running in single process mode. 13649 * 13650 * @return Returns true if the given process has been restarted, so the 13651 * app that was passed in must remain on the process lists. 13652 */ 13653 @GuardedBy("this") cleanUpApplicationRecordLocked(ProcessRecord app, boolean restarting, boolean allowRestart, int index, boolean replacingPid)13654 final boolean cleanUpApplicationRecordLocked(ProcessRecord app, 13655 boolean restarting, boolean allowRestart, int index, boolean replacingPid) { 13656 if (index >= 0) { 13657 removeLruProcessLocked(app); 13658 ProcessList.remove(app.pid); 13659 } 13660 13661 mProcessesToGc.remove(app); 13662 mPendingPssProcesses.remove(app); 13663 ProcessList.abortNextPssTime(app.procStateMemTracker); 13664 13665 // Dismiss any open dialogs. 13666 if (app.crashDialog != null && !app.forceCrashReport) { 13667 app.crashDialog.dismiss(); 13668 app.crashDialog = null; 13669 } 13670 if (app.anrDialog != null) { 13671 app.anrDialog.dismiss(); 13672 app.anrDialog = null; 13673 } 13674 if (app.waitDialog != null) { 13675 app.waitDialog.dismiss(); 13676 app.waitDialog = null; 13677 } 13678 13679 app.setCrashing(false); 13680 app.setNotResponding(false); 13681 13682 app.resetPackageList(mProcessStats); 13683 app.unlinkDeathRecipient(); 13684 app.makeInactive(mProcessStats); 13685 app.waitingToKill = null; 13686 app.forcingToImportant = null; 13687 updateProcessForegroundLocked(app, false, 0, false); 13688 app.setHasForegroundActivities(false); 13689 app.hasShownUi = false; 13690 app.treatLikeActivity = false; 13691 app.hasAboveClient = false; 13692 app.setHasClientActivities(false); 13693 13694 mServices.killServicesLocked(app, allowRestart); 13695 13696 boolean restart = false; 13697 13698 // Remove published content providers. 13699 for (int i = app.pubProviders.size() - 1; i >= 0; i--) { 13700 ContentProviderRecord cpr = app.pubProviders.valueAt(i); 13701 final boolean always = app.bad || !allowRestart; 13702 boolean inLaunching = removeDyingProviderLocked(app, cpr, always); 13703 if ((inLaunching || always) && cpr.hasConnectionOrHandle()) { 13704 // We left the provider in the launching list, need to 13705 // restart it. 13706 restart = true; 13707 } 13708 13709 cpr.provider = null; 13710 cpr.setProcess(null); 13711 } 13712 app.pubProviders.clear(); 13713 13714 // Take care of any launching providers waiting for this process. 13715 if (cleanupAppInLaunchingProvidersLocked(app, false)) { 13716 restart = true; 13717 } 13718 13719 // Unregister from connected content providers. 13720 if (!app.conProviders.isEmpty()) { 13721 for (int i = app.conProviders.size() - 1; i >= 0; i--) { 13722 ContentProviderConnection conn = app.conProviders.get(i); 13723 conn.provider.connections.remove(conn); 13724 stopAssociationLocked(app.uid, app.processName, conn.provider.uid, 13725 conn.provider.appInfo.longVersionCode, conn.provider.name, 13726 conn.provider.info.processName); 13727 } 13728 app.conProviders.clear(); 13729 } 13730 13731 // At this point there may be remaining entries in mLaunchingProviders 13732 // where we were the only one waiting, so they are no longer of use. 13733 // Look for these and clean up if found. 13734 // XXX Commented out for now. Trying to figure out a way to reproduce 13735 // the actual situation to identify what is actually going on. 13736 if (false) { 13737 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 13738 ContentProviderRecord cpr = mLaunchingProviders.get(i); 13739 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) { 13740 synchronized (cpr) { 13741 cpr.launchingApp = null; 13742 cpr.notifyAll(); 13743 } 13744 } 13745 } 13746 } 13747 13748 skipCurrentReceiverLocked(app); 13749 13750 // Unregister any receivers. 13751 for (int i = app.receivers.size() - 1; i >= 0; i--) { 13752 removeReceiverLocked(app.receivers.valueAt(i)); 13753 } 13754 app.receivers.clear(); 13755 13756 // If the app is undergoing backup, tell the backup manager about it 13757 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 13758 if (backupTarget != null && app.pid == backupTarget.app.pid) { 13759 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App " 13760 + backupTarget.appInfo + " died during backup"); 13761 mHandler.post(new Runnable() { 13762 @Override 13763 public void run(){ 13764 try { 13765 IBackupManager bm = IBackupManager.Stub.asInterface( 13766 ServiceManager.getService(Context.BACKUP_SERVICE)); 13767 bm.agentDisconnectedForUser(app.userId, app.info.packageName); 13768 } catch (RemoteException e) { 13769 // can't happen; backup manager is local 13770 } 13771 } 13772 }); 13773 } 13774 13775 for (int i = mPendingProcessChanges.size() - 1; i >= 0; i--) { 13776 ProcessChangeItem item = mPendingProcessChanges.get(i); 13777 if (app.pid > 0 && item.pid == app.pid) { 13778 mPendingProcessChanges.remove(i); 13779 mAvailProcessChanges.add(item); 13780 } 13781 } 13782 mUiHandler.obtainMessage(DISPATCH_PROCESS_DIED_UI_MSG, app.pid, app.info.uid, 13783 null).sendToTarget(); 13784 13785 // If the caller is restarting this app, then leave it in its 13786 // current lists and let the caller take care of it. 13787 if (restarting) { 13788 return false; 13789 } 13790 13791 if (!app.isPersistent() || app.isolated) { 13792 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 13793 "Removing non-persistent process during cleanup: " + app); 13794 if (!replacingPid) { 13795 mProcessList.removeProcessNameLocked(app.processName, app.uid, app); 13796 } 13797 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 13798 } else if (!app.removed) { 13799 // This app is persistent, so we need to keep its record around. 13800 // If it is not already on the pending app list, add it there 13801 // and start a new process for it. 13802 if (mPersistentStartingProcesses.indexOf(app) < 0) { 13803 mPersistentStartingProcesses.add(app); 13804 restart = true; 13805 } 13806 } 13807 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v( 13808 TAG_CLEANUP, "Clean-up removing on hold: " + app); 13809 mProcessesOnHold.remove(app); 13810 13811 mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController()); 13812 13813 if (restart && !app.isolated) { 13814 // We have components that still need to be running in the 13815 // process, so re-launch it. 13816 if (index < 0) { 13817 ProcessList.remove(app.pid); 13818 } 13819 mProcessList.addProcessNameLocked(app); 13820 app.pendingStart = false; 13821 mProcessList.startProcessLocked(app, 13822 new HostingRecord("restart", app.processName)); 13823 return true; 13824 } else if (app.pid > 0 && app.pid != MY_PID) { 13825 // Goodbye! 13826 mPidsSelfLocked.remove(app); 13827 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 13828 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 13829 if (app.isolated) { 13830 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 13831 } 13832 app.setPid(0); 13833 } 13834 return false; 13835 } 13836 checkAppInLaunchingProvidersLocked(ProcessRecord app)13837 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app) { 13838 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 13839 ContentProviderRecord cpr = mLaunchingProviders.get(i); 13840 if (cpr.launchingApp == app) { 13841 return true; 13842 } 13843 } 13844 return false; 13845 } 13846 cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad)13847 boolean cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) { 13848 // Look through the content providers we are waiting to have launched, 13849 // and if any run in this process then either schedule a restart of 13850 // the process or kill the client waiting for it if this process has 13851 // gone bad. 13852 boolean restart = false; 13853 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 13854 ContentProviderRecord cpr = mLaunchingProviders.get(i); 13855 if (cpr.launchingApp == app) { 13856 if (!alwaysBad && !app.bad && cpr.hasConnectionOrHandle()) { 13857 restart = true; 13858 } else { 13859 removeDyingProviderLocked(app, cpr, true); 13860 } 13861 } 13862 } 13863 return restart; 13864 } 13865 13866 // ========================================================= 13867 // SERVICES 13868 // ========================================================= 13869 13870 @Override getServices(int maxNum, int flags)13871 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) { 13872 enforceNotIsolatedCaller("getServices"); 13873 13874 final int callingUid = Binder.getCallingUid(); 13875 final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission( 13876 INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED); 13877 final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices", 13878 Binder.getCallingPid(), callingUid); 13879 synchronized (this) { 13880 return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid, 13881 allowed, canInteractAcrossUsers); 13882 } 13883 } 13884 13885 @Override getRunningServiceControlPanel(ComponentName name)13886 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 13887 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 13888 synchronized (this) { 13889 return mServices.getRunningServiceControlPanelLocked(name); 13890 } 13891 } 13892 13893 @Override startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, int userId)13894 public ComponentName startService(IApplicationThread caller, Intent service, 13895 String resolvedType, boolean requireForeground, String callingPackage, int userId) 13896 throws TransactionTooLargeException { 13897 enforceNotIsolatedCaller("startService"); 13898 // Refuse possible leaked file descriptors 13899 if (service != null && service.hasFileDescriptors() == true) { 13900 throw new IllegalArgumentException("File descriptors passed in Intent"); 13901 } 13902 13903 if (callingPackage == null) { 13904 throw new IllegalArgumentException("callingPackage cannot be null"); 13905 } 13906 13907 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 13908 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground); 13909 synchronized(this) { 13910 final int callingPid = Binder.getCallingPid(); 13911 final int callingUid = Binder.getCallingUid(); 13912 final long origId = Binder.clearCallingIdentity(); 13913 ComponentName res; 13914 try { 13915 res = mServices.startServiceLocked(caller, service, 13916 resolvedType, callingPid, callingUid, 13917 requireForeground, callingPackage, userId); 13918 } finally { 13919 Binder.restoreCallingIdentity(origId); 13920 } 13921 return res; 13922 } 13923 } 13924 13925 @Override stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)13926 public int stopService(IApplicationThread caller, Intent service, 13927 String resolvedType, int userId) { 13928 enforceNotIsolatedCaller("stopService"); 13929 // Refuse possible leaked file descriptors 13930 if (service != null && service.hasFileDescriptors() == true) { 13931 throw new IllegalArgumentException("File descriptors passed in Intent"); 13932 } 13933 13934 synchronized(this) { 13935 return mServices.stopServiceLocked(caller, service, resolvedType, userId); 13936 } 13937 } 13938 13939 @Override peekService(Intent service, String resolvedType, String callingPackage)13940 public IBinder peekService(Intent service, String resolvedType, String callingPackage) { 13941 enforceNotIsolatedCaller("peekService"); 13942 // Refuse possible leaked file descriptors 13943 if (service != null && service.hasFileDescriptors() == true) { 13944 throw new IllegalArgumentException("File descriptors passed in Intent"); 13945 } 13946 13947 if (callingPackage == null) { 13948 throw new IllegalArgumentException("callingPackage cannot be null"); 13949 } 13950 13951 synchronized(this) { 13952 return mServices.peekServiceLocked(service, resolvedType, callingPackage); 13953 } 13954 } 13955 13956 @Override stopServiceToken(ComponentName className, IBinder token, int startId)13957 public boolean stopServiceToken(ComponentName className, IBinder token, 13958 int startId) { 13959 synchronized(this) { 13960 return mServices.stopServiceTokenLocked(className, token, startId); 13961 } 13962 } 13963 13964 @Override setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)13965 public void setServiceForeground(ComponentName className, IBinder token, 13966 int id, Notification notification, int flags, int foregroundServiceType) { 13967 synchronized(this) { 13968 mServices.setServiceForegroundLocked(className, token, id, notification, flags, 13969 foregroundServiceType); 13970 } 13971 } 13972 13973 @Override getForegroundServiceType(ComponentName className, IBinder token)13974 public int getForegroundServiceType(ComponentName className, IBinder token) { 13975 synchronized (this) { 13976 return mServices.getForegroundServiceTypeLocked(className, token); 13977 } 13978 } 13979 13980 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)13981 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 13982 boolean requireFull, String name, String callerPackage) { 13983 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 13984 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 13985 } 13986 isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)13987 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 13988 String className, int flags) { 13989 boolean result = false; 13990 // For apps that don't have pre-defined UIDs, check for permission 13991 if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) { 13992 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 13993 if (ActivityManager.checkUidPermission( 13994 INTERACT_ACROSS_USERS, 13995 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 13996 ComponentName comp = new ComponentName(aInfo.packageName, className); 13997 String msg = "Permission Denial: Component " + comp.flattenToShortString() 13998 + " requests FLAG_SINGLE_USER, but app does not hold " 13999 + INTERACT_ACROSS_USERS; 14000 Slog.w(TAG, msg); 14001 throw new SecurityException(msg); 14002 } 14003 // Permission passed 14004 result = true; 14005 } 14006 } else if ("system".equals(componentProcessName)) { 14007 result = true; 14008 } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 14009 // Phone app and persistent apps are allowed to export singleuser providers. 14010 result = UserHandle.isSameApp(aInfo.uid, PHONE_UID) 14011 || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 14012 } 14013 if (DEBUG_MU) Slog.v(TAG_MU, 14014 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x" 14015 + Integer.toHexString(flags) + ") = " + result); 14016 return result; 14017 } 14018 14019 /** 14020 * Checks to see if the caller is in the same app as the singleton 14021 * component, or the component is in a special app. It allows special apps 14022 * to export singleton components but prevents exporting singleton 14023 * components for regular apps. 14024 */ isValidSingletonCall(int callingUid, int componentUid)14025 boolean isValidSingletonCall(int callingUid, int componentUid) { 14026 int componentAppId = UserHandle.getAppId(componentUid); 14027 return UserHandle.isSameApp(callingUid, componentUid) 14028 || componentAppId == SYSTEM_UID 14029 || componentAppId == PHONE_UID 14030 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 14031 == PackageManager.PERMISSION_GRANTED; 14032 } 14033 bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)14034 public int bindService(IApplicationThread caller, IBinder token, Intent service, 14035 String resolvedType, IServiceConnection connection, int flags, 14036 String callingPackage, int userId) throws TransactionTooLargeException { 14037 return bindIsolatedService(caller, token, service, resolvedType, connection, flags, 14038 null, callingPackage, userId); 14039 } 14040 bindIsolatedService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, String callingPackage, int userId)14041 public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service, 14042 String resolvedType, IServiceConnection connection, int flags, String instanceName, 14043 String callingPackage, int userId) throws TransactionTooLargeException { 14044 enforceNotIsolatedCaller("bindService"); 14045 14046 // Refuse possible leaked file descriptors 14047 if (service != null && service.hasFileDescriptors() == true) { 14048 throw new IllegalArgumentException("File descriptors passed in Intent"); 14049 } 14050 14051 if (callingPackage == null) { 14052 throw new IllegalArgumentException("callingPackage cannot be null"); 14053 } 14054 14055 // Ensure that instanceName, which is caller provided, does not contain 14056 // unusual characters. 14057 if (instanceName != null) { 14058 for (int i = 0; i < instanceName.length(); ++i) { 14059 char c = instanceName.charAt(i); 14060 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') 14061 || (c >= '0' && c <= '9') || c == '_' || c == '.')) { 14062 throw new IllegalArgumentException("Illegal instanceName"); 14063 } 14064 } 14065 } 14066 14067 synchronized(this) { 14068 return mServices.bindServiceLocked(caller, token, service, 14069 resolvedType, connection, flags, instanceName, callingPackage, userId); 14070 } 14071 } 14072 updateServiceGroup(IServiceConnection connection, int group, int importance)14073 public void updateServiceGroup(IServiceConnection connection, int group, int importance) { 14074 synchronized (this) { 14075 mServices.updateServiceGroupLocked(connection, group, importance); 14076 } 14077 } 14078 unbindService(IServiceConnection connection)14079 public boolean unbindService(IServiceConnection connection) { 14080 synchronized (this) { 14081 return mServices.unbindServiceLocked(connection); 14082 } 14083 } 14084 publishService(IBinder token, Intent intent, IBinder service)14085 public void publishService(IBinder token, Intent intent, IBinder service) { 14086 // Refuse possible leaked file descriptors 14087 if (intent != null && intent.hasFileDescriptors() == true) { 14088 throw new IllegalArgumentException("File descriptors passed in Intent"); 14089 } 14090 14091 synchronized(this) { 14092 if (!(token instanceof ServiceRecord)) { 14093 throw new IllegalArgumentException("Invalid service token"); 14094 } 14095 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 14096 } 14097 } 14098 unbindFinished(IBinder token, Intent intent, boolean doRebind)14099 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) { 14100 // Refuse possible leaked file descriptors 14101 if (intent != null && intent.hasFileDescriptors() == true) { 14102 throw new IllegalArgumentException("File descriptors passed in Intent"); 14103 } 14104 14105 synchronized(this) { 14106 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind); 14107 } 14108 } 14109 serviceDoneExecuting(IBinder token, int type, int startId, int res)14110 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) { 14111 synchronized(this) { 14112 if (!(token instanceof ServiceRecord)) { 14113 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token); 14114 throw new IllegalArgumentException("Invalid service token"); 14115 } 14116 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res); 14117 } 14118 } 14119 14120 // ========================================================= 14121 // BACKUP AND RESTORE 14122 // ========================================================= 14123 14124 // Cause the target app to be launched if necessary and its backup agent 14125 // instantiated. The backup agent will invoke backupAgentCreated() on the 14126 // activity manager to announce its creation. bindBackupAgent(String packageName, int backupMode, int targetUserId)14127 public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId) { 14128 if (DEBUG_BACKUP) { 14129 Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode 14130 + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid() 14131 + " uid = " + Process.myUid()); 14132 } 14133 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 14134 14135 // The instantiatedUserId is the user of the process the backup agent is started in. This is 14136 // different from the targetUserId which is the user whose data is to be backed up or 14137 // restored. This distinction is important for system-process packages that live in the 14138 // system user's process but backup/restore data for non-system users. 14139 // TODO (b/123688746): Handle all system-process packages with singleton check. 14140 final int instantiatedUserId = 14141 PLATFORM_PACKAGE_NAME.equals(packageName) ? UserHandle.USER_SYSTEM : targetUserId; 14142 14143 IPackageManager pm = AppGlobals.getPackageManager(); 14144 ApplicationInfo app = null; 14145 try { 14146 app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId); 14147 } catch (RemoteException e) { 14148 // can't happen; package manager is process-local 14149 } 14150 if (app == null) { 14151 Slog.w(TAG, "Unable to bind backup agent for " + packageName); 14152 return false; 14153 } 14154 14155 int oldBackupUid; 14156 int newBackupUid; 14157 14158 synchronized(this) { 14159 // !!! TODO: currently no check here that we're already bound 14160 // Backup agent is now in use, its package can't be stopped. 14161 try { 14162 AppGlobals.getPackageManager().setPackageStoppedState( 14163 app.packageName, false, UserHandle.getUserId(app.uid)); 14164 } catch (RemoteException e) { 14165 } catch (IllegalArgumentException e) { 14166 Slog.w(TAG, "Failed trying to unstop package " 14167 + app.packageName + ": " + e); 14168 } 14169 14170 BackupRecord r = new BackupRecord(app, backupMode, targetUserId); 14171 ComponentName hostingName = 14172 (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL) 14173 ? new ComponentName(app.packageName, app.backupAgentName) 14174 : new ComponentName("android", "FullBackupAgent"); 14175 14176 // startProcessLocked() returns existing proc's record if it's already running 14177 ProcessRecord proc = startProcessLocked(app.processName, app, 14178 false, 0, 14179 new HostingRecord("backup", hostingName), 14180 false, false, false); 14181 if (proc == null) { 14182 Slog.e(TAG, "Unable to start backup agent process " + r); 14183 return false; 14184 } 14185 14186 // If the app is a regular app (uid >= 10000) and not the system server or phone 14187 // process, etc, then mark it as being in full backup so that certain calls to the 14188 // process can be blocked. This is not reset to false anywhere because we kill the 14189 // process after the full backup is done and the ProcessRecord will vaporize anyway. 14190 if (UserHandle.isApp(app.uid) && 14191 backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) { 14192 proc.inFullBackup = true; 14193 } 14194 r.app = proc; 14195 final BackupRecord backupTarget = mBackupTargets.get(targetUserId); 14196 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 14197 newBackupUid = proc.inFullBackup ? r.appInfo.uid : -1; 14198 mBackupTargets.put(targetUserId, r); 14199 14200 // Try not to kill the process during backup 14201 updateOomAdjLocked(proc, true, OomAdjuster.OOM_ADJ_REASON_NONE); 14202 14203 // If the process is already attached, schedule the creation of the backup agent now. 14204 // If it is not yet live, this will be done when it attaches to the framework. 14205 if (proc.thread != null) { 14206 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc); 14207 try { 14208 proc.thread.scheduleCreateBackupAgent(app, 14209 compatibilityInfoForPackage(app), backupMode, targetUserId); 14210 } catch (RemoteException e) { 14211 // Will time out on the backup manager side 14212 } 14213 } else { 14214 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach"); 14215 } 14216 // Invariants: at this point, the target app process exists and the application 14217 // is either already running or in the process of coming up. mBackupTarget and 14218 // mBackupAppName describe the app, so that when it binds back to the AM we 14219 // know that it's scheduled for a backup-agent operation. 14220 } 14221 14222 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14223 if (oldBackupUid != -1) { 14224 js.removeBackingUpUid(oldBackupUid); 14225 } 14226 if (newBackupUid != -1) { 14227 js.addBackingUpUid(newBackupUid); 14228 } 14229 14230 return true; 14231 } 14232 clearPendingBackup(int userId)14233 private void clearPendingBackup(int userId) { 14234 if (DEBUG_BACKUP) { 14235 Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = " 14236 + Binder.getCallingUid() + " uid = " + Process.myUid()); 14237 } 14238 14239 synchronized (this) { 14240 mBackupTargets.delete(userId); 14241 } 14242 14243 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14244 js.clearAllBackingUpUids(); 14245 } 14246 14247 // A backup agent has just come up 14248 @Override backupAgentCreated(String agentPackageName, IBinder agent, int userId)14249 public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) { 14250 // Resolve the target user id and enforce permissions. 14251 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 14252 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null); 14253 if (DEBUG_BACKUP) { 14254 Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent 14255 + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId 14256 + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid()); 14257 } 14258 14259 synchronized(this) { 14260 final BackupRecord backupTarget = mBackupTargets.get(userId); 14261 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 14262 if (!agentPackageName.equals(backupAppName)) { 14263 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 14264 return; 14265 } 14266 } 14267 14268 long oldIdent = Binder.clearCallingIdentity(); 14269 try { 14270 IBackupManager bm = IBackupManager.Stub.asInterface( 14271 ServiceManager.getService(Context.BACKUP_SERVICE)); 14272 bm.agentConnectedForUser(userId, agentPackageName, agent); 14273 } catch (RemoteException e) { 14274 // can't happen; the backup manager service is local 14275 } catch (Exception e) { 14276 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 14277 e.printStackTrace(); 14278 } finally { 14279 Binder.restoreCallingIdentity(oldIdent); 14280 } 14281 } 14282 14283 // done with this agent unbindBackupAgent(ApplicationInfo appInfo)14284 public void unbindBackupAgent(ApplicationInfo appInfo) { 14285 if (DEBUG_BACKUP) { 14286 Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = " 14287 + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = " 14288 + Process.myUid()); 14289 } 14290 14291 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent"); 14292 if (appInfo == null) { 14293 Slog.w(TAG, "unbind backup agent for null app"); 14294 return; 14295 } 14296 14297 int oldBackupUid; 14298 14299 final int userId = UserHandle.getUserId(appInfo.uid); 14300 synchronized(this) { 14301 final BackupRecord backupTarget = mBackupTargets.get(userId); 14302 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 14303 try { 14304 if (backupAppName == null) { 14305 Slog.w(TAG, "Unbinding backup agent with no active backup"); 14306 return; 14307 } 14308 14309 if (!backupAppName.equals(appInfo.packageName)) { 14310 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 14311 return; 14312 } 14313 14314 // Not backing this app up any more; reset its OOM adjustment 14315 final ProcessRecord proc = backupTarget.app; 14316 updateOomAdjLocked(proc, true, OomAdjuster.OOM_ADJ_REASON_NONE); 14317 proc.inFullBackup = false; 14318 14319 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 14320 14321 // If the app crashed during backup, 'thread' will be null here 14322 if (proc.thread != null) { 14323 try { 14324 proc.thread.scheduleDestroyBackupAgent(appInfo, 14325 compatibilityInfoForPackage(appInfo), userId); 14326 } catch (Exception e) { 14327 Slog.e(TAG, "Exception when unbinding backup agent:"); 14328 e.printStackTrace(); 14329 } 14330 } 14331 } finally { 14332 mBackupTargets.delete(userId); 14333 } 14334 } 14335 14336 if (oldBackupUid != -1) { 14337 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14338 js.removeBackingUpUid(oldBackupUid); 14339 } 14340 } 14341 14342 // ========================================================= 14343 // BROADCASTS 14344 // ========================================================= 14345 isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)14346 private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) { 14347 if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) { 14348 return false; 14349 } 14350 // Easy case -- we have the app's ProcessRecord. 14351 if (record != null) { 14352 return record.info.isInstantApp(); 14353 } 14354 // Otherwise check with PackageManager. 14355 IPackageManager pm = AppGlobals.getPackageManager(); 14356 try { 14357 if (callerPackage == null) { 14358 final String[] packageNames = pm.getPackagesForUid(uid); 14359 if (packageNames == null || packageNames.length == 0) { 14360 throw new IllegalArgumentException("Unable to determine caller package name"); 14361 } 14362 // Instant Apps can't use shared uids, so its safe to only check the first package. 14363 callerPackage = packageNames[0]; 14364 } 14365 mAppOpsService.checkPackage(uid, callerPackage); 14366 return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid)); 14367 } catch (RemoteException e) { 14368 Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e); 14369 return true; 14370 } 14371 } 14372 isPendingBroadcastProcessLocked(int pid)14373 boolean isPendingBroadcastProcessLocked(int pid) { 14374 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 14375 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 14376 || mOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid); 14377 } 14378 skipPendingBroadcastLocked(int pid)14379 void skipPendingBroadcastLocked(int pid) { 14380 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 14381 for (BroadcastQueue queue : mBroadcastQueues) { 14382 queue.skipPendingBroadcastLocked(pid); 14383 } 14384 } 14385 14386 // The app just attached; send any pending broadcasts that it should receive sendPendingBroadcastsLocked(ProcessRecord app)14387 boolean sendPendingBroadcastsLocked(ProcessRecord app) { 14388 boolean didSomething = false; 14389 for (BroadcastQueue queue : mBroadcastQueues) { 14390 didSomething |= queue.sendPendingBroadcastsLocked(app); 14391 } 14392 return didSomething; 14393 } 14394 registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)14395 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 14396 IIntentReceiver receiver, IntentFilter filter, String permission, int userId, 14397 int flags) { 14398 enforceNotIsolatedCaller("registerReceiver"); 14399 ArrayList<Intent> stickyIntents = null; 14400 ProcessRecord callerApp = null; 14401 final boolean visibleToInstantApps 14402 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0; 14403 int callingUid; 14404 int callingPid; 14405 boolean instantApp; 14406 synchronized(this) { 14407 if (caller != null) { 14408 callerApp = getRecordForAppLocked(caller); 14409 if (callerApp == null) { 14410 throw new SecurityException( 14411 "Unable to find app for caller " + caller 14412 + " (pid=" + Binder.getCallingPid() 14413 + ") when registering receiver " + receiver); 14414 } 14415 if (callerApp.info.uid != SYSTEM_UID && 14416 !callerApp.pkgList.containsKey(callerPackage) && 14417 !"android".equals(callerPackage)) { 14418 throw new SecurityException("Given caller package " + callerPackage 14419 + " is not running in process " + callerApp); 14420 } 14421 callingUid = callerApp.info.uid; 14422 callingPid = callerApp.pid; 14423 } else { 14424 callerPackage = null; 14425 callingUid = Binder.getCallingUid(); 14426 callingPid = Binder.getCallingPid(); 14427 } 14428 14429 instantApp = isInstantApp(callerApp, callerPackage, callingUid); 14430 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 14431 ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 14432 14433 Iterator<String> actions = filter.actionsIterator(); 14434 if (actions == null) { 14435 ArrayList<String> noAction = new ArrayList<String>(1); 14436 noAction.add(null); 14437 actions = noAction.iterator(); 14438 } 14439 14440 // Collect stickies of users 14441 int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) }; 14442 while (actions.hasNext()) { 14443 String action = actions.next(); 14444 for (int id : userIds) { 14445 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(id); 14446 if (stickies != null) { 14447 ArrayList<Intent> intents = stickies.get(action); 14448 if (intents != null) { 14449 if (stickyIntents == null) { 14450 stickyIntents = new ArrayList<Intent>(); 14451 } 14452 stickyIntents.addAll(intents); 14453 } 14454 } 14455 } 14456 } 14457 } 14458 14459 ArrayList<Intent> allSticky = null; 14460 if (stickyIntents != null) { 14461 final ContentResolver resolver = mContext.getContentResolver(); 14462 // Look for any matching sticky broadcasts... 14463 for (int i = 0, N = stickyIntents.size(); i < N; i++) { 14464 Intent intent = stickyIntents.get(i); 14465 // Don't provided intents that aren't available to instant apps. 14466 if (instantApp && 14467 (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) { 14468 continue; 14469 } 14470 // If intent has scheme "content", it will need to acccess 14471 // provider that needs to lock mProviderMap in ActivityThread 14472 // and also it may need to wait application response, so we 14473 // cannot lock ActivityManagerService here. 14474 if (filter.match(resolver, intent, true, TAG) >= 0) { 14475 if (allSticky == null) { 14476 allSticky = new ArrayList<Intent>(); 14477 } 14478 allSticky.add(intent); 14479 } 14480 } 14481 } 14482 14483 // The first sticky in the list is returned directly back to the client. 14484 Intent sticky = allSticky != null ? allSticky.get(0) : null; 14485 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky); 14486 if (receiver == null) { 14487 return sticky; 14488 } 14489 14490 synchronized (this) { 14491 if (callerApp != null && (callerApp.thread == null 14492 || callerApp.thread.asBinder() != caller.asBinder())) { 14493 // Original caller already died 14494 return null; 14495 } 14496 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 14497 if (rl == null) { 14498 rl = new ReceiverList(this, callerApp, callingPid, callingUid, 14499 userId, receiver); 14500 if (rl.app != null) { 14501 final int totalReceiversForApp = rl.app.receivers.size(); 14502 if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) { 14503 throw new IllegalStateException("Too many receivers, total of " 14504 + totalReceiversForApp + ", registered for pid: " 14505 + rl.pid + ", callerPackage: " + callerPackage); 14506 } 14507 rl.app.receivers.add(rl); 14508 } else { 14509 try { 14510 receiver.asBinder().linkToDeath(rl, 0); 14511 } catch (RemoteException e) { 14512 return sticky; 14513 } 14514 rl.linkedToDeath = true; 14515 } 14516 mRegisteredReceivers.put(receiver.asBinder(), rl); 14517 } else if (rl.uid != callingUid) { 14518 throw new IllegalArgumentException( 14519 "Receiver requested to register for uid " + callingUid 14520 + " was previously registered for uid " + rl.uid 14521 + " callerPackage is " + callerPackage); 14522 } else if (rl.pid != callingPid) { 14523 throw new IllegalArgumentException( 14524 "Receiver requested to register for pid " + callingPid 14525 + " was previously registered for pid " + rl.pid 14526 + " callerPackage is " + callerPackage); 14527 } else if (rl.userId != userId) { 14528 throw new IllegalArgumentException( 14529 "Receiver requested to register for user " + userId 14530 + " was previously registered for user " + rl.userId 14531 + " callerPackage is " + callerPackage); 14532 } 14533 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, 14534 permission, callingUid, userId, instantApp, visibleToInstantApps); 14535 if (rl.containsFilter(filter)) { 14536 Slog.w(TAG, "Receiver with filter " + filter 14537 + " already registered for pid " + rl.pid 14538 + ", callerPackage is " + callerPackage); 14539 } else { 14540 rl.add(bf); 14541 if (!bf.debugCheck()) { 14542 Slog.w(TAG, "==> For Dynamic broadcast"); 14543 } 14544 mReceiverResolver.addFilter(bf); 14545 } 14546 14547 // Enqueue broadcasts for all existing stickies that match 14548 // this filter. 14549 if (allSticky != null) { 14550 ArrayList receivers = new ArrayList(); 14551 receivers.add(bf); 14552 14553 final int stickyCount = allSticky.size(); 14554 for (int i = 0; i < stickyCount; i++) { 14555 Intent intent = allSticky.get(i); 14556 BroadcastQueue queue = broadcastQueueForIntent(intent); 14557 BroadcastRecord r = new BroadcastRecord(queue, intent, null, 14558 null, -1, -1, false, null, null, OP_NONE, null, receivers, 14559 null, 0, null, null, false, true, true, -1, false, 14560 false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */); 14561 queue.enqueueParallelBroadcastLocked(r); 14562 queue.scheduleBroadcastsLocked(); 14563 } 14564 } 14565 14566 return sticky; 14567 } 14568 } 14569 unregisterReceiver(IIntentReceiver receiver)14570 public void unregisterReceiver(IIntentReceiver receiver) { 14571 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver); 14572 14573 final long origId = Binder.clearCallingIdentity(); 14574 try { 14575 boolean doTrim = false; 14576 14577 synchronized(this) { 14578 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 14579 if (rl != null) { 14580 final BroadcastRecord r = rl.curBroadcast; 14581 if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) { 14582 final boolean doNext = r.queue.finishReceiverLocked( 14583 r, r.resultCode, r.resultData, r.resultExtras, 14584 r.resultAbort, false); 14585 if (doNext) { 14586 doTrim = true; 14587 r.queue.processNextBroadcast(false); 14588 } 14589 } 14590 14591 if (rl.app != null) { 14592 rl.app.receivers.remove(rl); 14593 } 14594 removeReceiverLocked(rl); 14595 if (rl.linkedToDeath) { 14596 rl.linkedToDeath = false; 14597 rl.receiver.asBinder().unlinkToDeath(rl, 0); 14598 } 14599 } 14600 } 14601 14602 // If we actually concluded any broadcasts, we might now be able 14603 // to trim the recipients' apps from our working set 14604 if (doTrim) { 14605 trimApplications(OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER); 14606 return; 14607 } 14608 14609 } finally { 14610 Binder.restoreCallingIdentity(origId); 14611 } 14612 } 14613 removeReceiverLocked(ReceiverList rl)14614 void removeReceiverLocked(ReceiverList rl) { 14615 mRegisteredReceivers.remove(rl.receiver.asBinder()); 14616 for (int i = rl.size() - 1; i >= 0; i--) { 14617 mReceiverResolver.removeFilter(rl.get(i)); 14618 } 14619 } 14620 sendPackageBroadcastLocked(int cmd, String[] packages, int userId)14621 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 14622 mProcessList.sendPackageBroadcastLocked(cmd, packages, userId); 14623 } 14624 collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users)14625 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType, 14626 int callingUid, int[] users) { 14627 // TODO: come back and remove this assumption to triage all broadcasts 14628 int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING; 14629 14630 List<ResolveInfo> receivers = null; 14631 try { 14632 HashSet<ComponentName> singleUserReceivers = null; 14633 boolean scannedFirstReceivers = false; 14634 for (int user : users) { 14635 // Skip users that have Shell restrictions, with exception of always permitted 14636 // Shell broadcasts 14637 if (callingUid == SHELL_UID 14638 && mUserController.hasUserRestriction( 14639 UserManager.DISALLOW_DEBUGGING_FEATURES, user) 14640 && !isPermittedShellBroadcast(intent)) { 14641 continue; 14642 } 14643 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager() 14644 .queryIntentReceivers(intent, resolvedType, pmFlags, user).getList(); 14645 if (user != UserHandle.USER_SYSTEM && newReceivers != null) { 14646 // If this is not the system user, we need to check for 14647 // any receivers that should be filtered out. 14648 for (int i=0; i<newReceivers.size(); i++) { 14649 ResolveInfo ri = newReceivers.get(i); 14650 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 14651 newReceivers.remove(i); 14652 i--; 14653 } 14654 } 14655 } 14656 if (newReceivers != null && newReceivers.size() == 0) { 14657 newReceivers = null; 14658 } 14659 if (receivers == null) { 14660 receivers = newReceivers; 14661 } else if (newReceivers != null) { 14662 // We need to concatenate the additional receivers 14663 // found with what we have do far. This would be easy, 14664 // but we also need to de-dup any receivers that are 14665 // singleUser. 14666 if (!scannedFirstReceivers) { 14667 // Collect any single user receivers we had already retrieved. 14668 scannedFirstReceivers = true; 14669 for (int i=0; i<receivers.size(); i++) { 14670 ResolveInfo ri = receivers.get(i); 14671 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 14672 ComponentName cn = new ComponentName( 14673 ri.activityInfo.packageName, ri.activityInfo.name); 14674 if (singleUserReceivers == null) { 14675 singleUserReceivers = new HashSet<ComponentName>(); 14676 } 14677 singleUserReceivers.add(cn); 14678 } 14679 } 14680 } 14681 // Add the new results to the existing results, tracking 14682 // and de-dupping single user receivers. 14683 for (int i=0; i<newReceivers.size(); i++) { 14684 ResolveInfo ri = newReceivers.get(i); 14685 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 14686 ComponentName cn = new ComponentName( 14687 ri.activityInfo.packageName, ri.activityInfo.name); 14688 if (singleUserReceivers == null) { 14689 singleUserReceivers = new HashSet<ComponentName>(); 14690 } 14691 if (!singleUserReceivers.contains(cn)) { 14692 singleUserReceivers.add(cn); 14693 receivers.add(ri); 14694 } 14695 } else { 14696 receivers.add(ri); 14697 } 14698 } 14699 } 14700 } 14701 } catch (RemoteException ex) { 14702 // pm is in same process, this will never happen. 14703 } 14704 return receivers; 14705 } 14706 isPermittedShellBroadcast(Intent intent)14707 private boolean isPermittedShellBroadcast(Intent intent) { 14708 // remote bugreport should always be allowed to be taken 14709 return INTENT_REMOTE_BUGREPORT_FINISHED.equals(intent.getAction()); 14710 } 14711 checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)14712 private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, 14713 String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) { 14714 if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 14715 // Don't yell about broadcasts sent via shell 14716 return; 14717 } 14718 14719 final String action = intent.getAction(); 14720 if (isProtectedBroadcast 14721 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action) 14722 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action) 14723 || Intent.ACTION_MEDIA_BUTTON.equals(action) 14724 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action) 14725 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action) 14726 || Intent.ACTION_MASTER_CLEAR.equals(action) 14727 || Intent.ACTION_FACTORY_RESET.equals(action) 14728 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 14729 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) 14730 || LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION.equals(action) 14731 || TelephonyIntents.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action) 14732 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action) 14733 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action) 14734 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) { 14735 // Broadcast is either protected, or it's a public action that 14736 // we've relaxed, so it's fine for system internals to send. 14737 return; 14738 } 14739 14740 // This broadcast may be a problem... but there are often system components that 14741 // want to send an internal broadcast to themselves, which is annoying to have to 14742 // explicitly list each action as a protected broadcast, so we will check for that 14743 // one safe case and allow it: an explicit broadcast, only being received by something 14744 // that has protected itself. 14745 if (intent.getPackage() != null || intent.getComponent() != null) { 14746 if (receivers == null || receivers.size() == 0) { 14747 // Intent is explicit and there's no receivers. 14748 // This happens, e.g. , when a system component sends a broadcast to 14749 // its own runtime receiver, and there's no manifest receivers for it, 14750 // because this method is called twice for each broadcast, 14751 // for runtime receivers and manifest receivers and the later check would find 14752 // no receivers. 14753 return; 14754 } 14755 boolean allProtected = true; 14756 for (int i = receivers.size()-1; i >= 0; i--) { 14757 Object target = receivers.get(i); 14758 if (target instanceof ResolveInfo) { 14759 ResolveInfo ri = (ResolveInfo)target; 14760 if (ri.activityInfo.exported && ri.activityInfo.permission == null) { 14761 allProtected = false; 14762 break; 14763 } 14764 } else { 14765 BroadcastFilter bf = (BroadcastFilter)target; 14766 if (bf.requiredPermission == null) { 14767 allProtected = false; 14768 break; 14769 } 14770 } 14771 } 14772 if (allProtected) { 14773 // All safe! 14774 return; 14775 } 14776 } 14777 14778 // The vast majority of broadcasts sent from system internals 14779 // should be protected to avoid security holes, so yell loudly 14780 // to ensure we examine these cases. 14781 if (callerApp != null) { 14782 Log.wtf(TAG, "Sending non-protected broadcast " + action 14783 + " from system " + callerApp.toShortString() + " pkg " + callerPackage, 14784 new Throwable()); 14785 } else { 14786 Log.wtf(TAG, "Sending non-protected broadcast " + action 14787 + " from system uid " + UserHandle.formatUid(callingUid) 14788 + " pkg " + callerPackage, 14789 new Throwable()); 14790 } 14791 } 14792 14793 @GuardedBy("this") broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId)14794 final int broadcastIntentLocked(ProcessRecord callerApp, 14795 String callerPackage, Intent intent, String resolvedType, 14796 IIntentReceiver resultTo, int resultCode, String resultData, 14797 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, 14798 boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, 14799 int realCallingPid, int userId) { 14800 return broadcastIntentLocked(callerApp, callerPackage, intent, resolvedType, resultTo, 14801 resultCode, resultData, resultExtras, requiredPermissions, appOp, bOptions, ordered, 14802 sticky, callingPid, callingUid, realCallingUid, realCallingPid, userId, 14803 false /* allowBackgroundActivityStarts */); 14804 } 14805 14806 @GuardedBy("this") broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, boolean allowBackgroundActivityStarts)14807 final int broadcastIntentLocked(ProcessRecord callerApp, 14808 String callerPackage, Intent intent, String resolvedType, 14809 IIntentReceiver resultTo, int resultCode, String resultData, 14810 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, 14811 boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, 14812 int realCallingPid, int userId, boolean allowBackgroundActivityStarts) { 14813 intent = new Intent(intent); 14814 14815 final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid); 14816 // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS 14817 if (callerInstantApp) { 14818 intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 14819 } 14820 14821 // By default broadcasts do not go to stopped apps. 14822 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 14823 14824 // If we have not finished booting, don't allow this to launch new processes. 14825 if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 14826 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 14827 } 14828 14829 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 14830 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent 14831 + " ordered=" + ordered + " userid=" + userId); 14832 if ((resultTo != null) && !ordered) { 14833 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!"); 14834 } 14835 14836 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 14837 ALLOW_NON_FULL, "broadcast", callerPackage); 14838 14839 // Make sure that the user who is receiving this broadcast or its parent is running. 14840 // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps. 14841 if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) { 14842 if ((callingUid != SYSTEM_UID 14843 || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) 14844 && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { 14845 Slog.w(TAG, "Skipping broadcast of " + intent 14846 + ": user " + userId + " and its parent (if any) are stopped"); 14847 return ActivityManager.BROADCAST_FAILED_USER_STOPPED; 14848 } 14849 } 14850 14851 final String action = intent.getAction(); 14852 BroadcastOptions brOptions = null; 14853 if (bOptions != null) { 14854 brOptions = new BroadcastOptions(bOptions); 14855 if (brOptions.getTemporaryAppWhitelistDuration() > 0) { 14856 // See if the caller is allowed to do this. Note we are checking against 14857 // the actual real caller (not whoever provided the operation as say a 14858 // PendingIntent), because that who is actually supplied the arguments. 14859 if (checkComponentPermission( 14860 android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST, 14861 realCallingPid, realCallingUid, -1, true) 14862 != PackageManager.PERMISSION_GRANTED) { 14863 String msg = "Permission Denial: " + intent.getAction() 14864 + " broadcast from " + callerPackage + " (pid=" + callingPid 14865 + ", uid=" + callingUid + ")" 14866 + " requires " 14867 + android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST; 14868 Slog.w(TAG, msg); 14869 throw new SecurityException(msg); 14870 } 14871 } 14872 if (brOptions.isDontSendToRestrictedApps() 14873 && !isUidActiveLocked(callingUid) 14874 && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) { 14875 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage 14876 + " has background restrictions"); 14877 return ActivityManager.START_CANCELED; 14878 } 14879 if (brOptions.allowsBackgroundActivityStarts()) { 14880 // See if the caller is allowed to do this. Note we are checking against 14881 // the actual real caller (not whoever provided the operation as say a 14882 // PendingIntent), because that who is actually supplied the arguments. 14883 if (checkComponentPermission( 14884 android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND, 14885 realCallingPid, realCallingUid, -1, true) 14886 != PackageManager.PERMISSION_GRANTED) { 14887 String msg = "Permission Denial: " + intent.getAction() 14888 + " broadcast from " + callerPackage + " (pid=" + callingPid 14889 + ", uid=" + callingUid + ")" 14890 + " requires " 14891 + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; 14892 Slog.w(TAG, msg); 14893 throw new SecurityException(msg); 14894 } else { 14895 allowBackgroundActivityStarts = true; 14896 } 14897 } 14898 } 14899 14900 // Verify that protected broadcasts are only being sent by system code, 14901 // and that system code is only sending protected broadcasts. 14902 final boolean isProtectedBroadcast; 14903 try { 14904 isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action); 14905 } catch (RemoteException e) { 14906 Slog.w(TAG, "Remote exception", e); 14907 return ActivityManager.BROADCAST_SUCCESS; 14908 } 14909 14910 final boolean isCallerSystem; 14911 switch (UserHandle.getAppId(callingUid)) { 14912 case ROOT_UID: 14913 case SYSTEM_UID: 14914 case PHONE_UID: 14915 case BLUETOOTH_UID: 14916 case NFC_UID: 14917 case SE_UID: 14918 case NETWORK_STACK_UID: 14919 isCallerSystem = true; 14920 break; 14921 default: 14922 isCallerSystem = (callerApp != null) && callerApp.isPersistent(); 14923 break; 14924 } 14925 14926 // First line security check before anything else: stop non-system apps from 14927 // sending protected broadcasts. 14928 if (!isCallerSystem) { 14929 if (isProtectedBroadcast) { 14930 String msg = "Permission Denial: not allowed to send broadcast " 14931 + action + " from pid=" 14932 + callingPid + ", uid=" + callingUid; 14933 Slog.w(TAG, msg); 14934 throw new SecurityException(msg); 14935 14936 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 14937 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { 14938 // Special case for compatibility: we don't want apps to send this, 14939 // but historically it has not been protected and apps may be using it 14940 // to poke their own app widget. So, instead of making it protected, 14941 // just limit it to the caller. 14942 if (callerPackage == null) { 14943 String msg = "Permission Denial: not allowed to send broadcast " 14944 + action + " from unknown caller."; 14945 Slog.w(TAG, msg); 14946 throw new SecurityException(msg); 14947 } else if (intent.getComponent() != null) { 14948 // They are good enough to send to an explicit component... verify 14949 // it is being sent to the calling app. 14950 if (!intent.getComponent().getPackageName().equals( 14951 callerPackage)) { 14952 String msg = "Permission Denial: not allowed to send broadcast " 14953 + action + " to " 14954 + intent.getComponent().getPackageName() + " from " 14955 + callerPackage; 14956 Slog.w(TAG, msg); 14957 throw new SecurityException(msg); 14958 } 14959 } else { 14960 // Limit broadcast to their own package. 14961 intent.setPackage(callerPackage); 14962 } 14963 } 14964 } 14965 14966 boolean timeoutExempt = false; 14967 14968 if (action != null) { 14969 if (getBackgroundLaunchBroadcasts().contains(action)) { 14970 if (DEBUG_BACKGROUND_CHECK) { 14971 Slog.i(TAG, "Broadcast action " + action + " forcing include-background"); 14972 } 14973 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 14974 } 14975 14976 switch (action) { 14977 case Intent.ACTION_UID_REMOVED: 14978 case Intent.ACTION_PACKAGE_REMOVED: 14979 case Intent.ACTION_PACKAGE_CHANGED: 14980 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 14981 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 14982 case Intent.ACTION_PACKAGES_SUSPENDED: 14983 case Intent.ACTION_PACKAGES_UNSUSPENDED: 14984 // Handle special intents: if this broadcast is from the package 14985 // manager about a package being removed, we need to remove all of 14986 // its activities from the history stack. 14987 if (checkComponentPermission( 14988 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 14989 callingPid, callingUid, -1, true) 14990 != PackageManager.PERMISSION_GRANTED) { 14991 String msg = "Permission Denial: " + intent.getAction() 14992 + " broadcast from " + callerPackage + " (pid=" + callingPid 14993 + ", uid=" + callingUid + ")" 14994 + " requires " 14995 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 14996 Slog.w(TAG, msg); 14997 throw new SecurityException(msg); 14998 } 14999 switch (action) { 15000 case Intent.ACTION_UID_REMOVED: 15001 final int uid = getUidFromIntent(intent); 15002 if (uid >= 0) { 15003 mBatteryStatsService.removeUid(uid); 15004 mAppOpsService.uidRemoved(uid); 15005 } 15006 break; 15007 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 15008 // If resources are unavailable just force stop all those packages 15009 // and flush the attribute cache as well. 15010 String list[] = 15011 intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 15012 if (list != null && list.length > 0) { 15013 for (int i = 0; i < list.length; i++) { 15014 forceStopPackageLocked(list[i], -1, false, true, true, 15015 false, false, userId, "storage unmount"); 15016 } 15017 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 15018 sendPackageBroadcastLocked( 15019 ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE, 15020 list, userId); 15021 } 15022 break; 15023 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 15024 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 15025 break; 15026 case Intent.ACTION_PACKAGE_REMOVED: 15027 case Intent.ACTION_PACKAGE_CHANGED: 15028 Uri data = intent.getData(); 15029 String ssp; 15030 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 15031 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action); 15032 final boolean replacing = 15033 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 15034 final boolean killProcess = 15035 !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false); 15036 final boolean fullUninstall = removed && !replacing; 15037 if (removed) { 15038 if (killProcess) { 15039 forceStopPackageLocked(ssp, UserHandle.getAppId( 15040 intent.getIntExtra(Intent.EXTRA_UID, -1)), 15041 false, true, true, false, fullUninstall, userId, 15042 removed ? "pkg removed" : "pkg changed"); 15043 } 15044 final int cmd = killProcess 15045 ? ApplicationThreadConstants.PACKAGE_REMOVED 15046 : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL; 15047 sendPackageBroadcastLocked(cmd, 15048 new String[] {ssp}, userId); 15049 if (fullUninstall) { 15050 mAppOpsService.packageRemoved( 15051 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp); 15052 15053 // Remove all permissions granted from/to this package 15054 mUgmInternal.removeUriPermissionsForPackage(ssp, userId, 15055 true, false); 15056 15057 mAtmInternal.removeRecentTasksByPackageName(ssp, userId); 15058 15059 mServices.forceStopPackageLocked(ssp, userId); 15060 mAtmInternal.onPackageUninstalled(ssp); 15061 mBatteryStatsService.notePackageUninstalled(ssp); 15062 } 15063 } else { 15064 if (killProcess) { 15065 final int extraUid = intent.getIntExtra(Intent.EXTRA_UID, 15066 -1); 15067 mProcessList.killPackageProcessesLocked(ssp, 15068 UserHandle.getAppId(extraUid), 15069 userId, ProcessList.INVALID_ADJ, "change " + ssp); 15070 } 15071 cleanupDisabledPackageComponentsLocked(ssp, userId, 15072 intent.getStringArrayExtra( 15073 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST)); 15074 } 15075 } 15076 break; 15077 case Intent.ACTION_PACKAGES_SUSPENDED: 15078 case Intent.ACTION_PACKAGES_UNSUSPENDED: 15079 final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals( 15080 intent.getAction()); 15081 final String[] packageNames = intent.getStringArrayExtra( 15082 Intent.EXTRA_CHANGED_PACKAGE_LIST); 15083 final int userHandle = intent.getIntExtra( 15084 Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 15085 15086 mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended, 15087 userHandle); 15088 break; 15089 } 15090 break; 15091 case Intent.ACTION_PACKAGE_REPLACED: 15092 { 15093 final Uri data = intent.getData(); 15094 final String ssp; 15095 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 15096 ApplicationInfo aInfo = null; 15097 try { 15098 aInfo = AppGlobals.getPackageManager() 15099 .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId); 15100 } catch (RemoteException ignore) {} 15101 if (aInfo == null) { 15102 Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:" 15103 + " ssp=" + ssp + " data=" + data); 15104 return ActivityManager.BROADCAST_SUCCESS; 15105 } 15106 updateAssociationForApp(aInfo); 15107 mAtmInternal.onPackageReplaced(aInfo); 15108 mServices.updateServiceApplicationInfoLocked(aInfo); 15109 sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED, 15110 new String[] {ssp}, userId); 15111 } 15112 break; 15113 } 15114 case Intent.ACTION_PACKAGE_ADDED: 15115 { 15116 // Special case for adding a package: by default turn on compatibility mode. 15117 Uri data = intent.getData(); 15118 String ssp; 15119 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 15120 final boolean replacing = 15121 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 15122 mAtmInternal.onPackageAdded(ssp, replacing); 15123 15124 try { 15125 ApplicationInfo ai = AppGlobals.getPackageManager(). 15126 getApplicationInfo(ssp, STOCK_PM_FLAGS, 0); 15127 mBatteryStatsService.notePackageInstalled(ssp, 15128 ai != null ? ai.longVersionCode : 0); 15129 } catch (RemoteException e) { 15130 } 15131 } 15132 break; 15133 } 15134 case Intent.ACTION_PACKAGE_DATA_CLEARED: 15135 { 15136 Uri data = intent.getData(); 15137 String ssp; 15138 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 15139 mAtmInternal.onPackageDataCleared(ssp); 15140 } 15141 break; 15142 } 15143 case Intent.ACTION_TIMEZONE_CHANGED: 15144 // If this is the time zone changed action, queue up a message that will reset 15145 // the timezone of all currently running processes. This message will get 15146 // queued up before the broadcast happens. 15147 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 15148 break; 15149 case Intent.ACTION_TIME_CHANGED: 15150 // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between 15151 // the tri-state value it may contain and "unknown". 15152 // For convenience we re-use the Intent extra values. 15153 final int NO_EXTRA_VALUE_FOUND = -1; 15154 final int timeFormatPreferenceMsgValue = intent.getIntExtra( 15155 Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, 15156 NO_EXTRA_VALUE_FOUND /* defaultValue */); 15157 // Only send a message if the time preference is available. 15158 if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) { 15159 Message updateTimePreferenceMsg = 15160 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG, 15161 timeFormatPreferenceMsgValue, 0); 15162 mHandler.sendMessage(updateTimePreferenceMsg); 15163 } 15164 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 15165 synchronized (stats) { 15166 stats.noteCurrentTimeChangedLocked(); 15167 } 15168 break; 15169 case Intent.ACTION_CLEAR_DNS_CACHE: 15170 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 15171 break; 15172 case Proxy.PROXY_CHANGE_ACTION: 15173 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG)); 15174 break; 15175 case android.hardware.Camera.ACTION_NEW_PICTURE: 15176 case android.hardware.Camera.ACTION_NEW_VIDEO: 15177 // In N we just turned these off; in O we are turing them back on partly, 15178 // only for registered receivers. This will still address the main problem 15179 // (a spam of apps waking up when a picture is taken putting significant 15180 // memory pressure on the system at a bad point), while still allowing apps 15181 // that are already actively running to know about this happening. 15182 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 15183 break; 15184 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED: 15185 mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG); 15186 break; 15187 case "com.android.launcher.action.INSTALL_SHORTCUT": 15188 // As of O, we no longer support this broadcasts, even for pre-O apps. 15189 // Apps should now be using ShortcutManager.pinRequestShortcut(). 15190 Log.w(TAG, "Broadcast " + action 15191 + " no longer supported. It will not be delivered."); 15192 return ActivityManager.BROADCAST_SUCCESS; 15193 case Intent.ACTION_PRE_BOOT_COMPLETED: 15194 timeoutExempt = true; 15195 break; 15196 } 15197 15198 if (Intent.ACTION_PACKAGE_ADDED.equals(action) || 15199 Intent.ACTION_PACKAGE_REMOVED.equals(action) || 15200 Intent.ACTION_PACKAGE_REPLACED.equals(action)) { 15201 final int uid = getUidFromIntent(intent); 15202 if (uid != -1) { 15203 final UidRecord uidRec = mProcessList.getUidRecordLocked(uid); 15204 if (uidRec != null) { 15205 uidRec.updateHasInternetPermission(); 15206 } 15207 } 15208 } 15209 } 15210 15211 // Add to the sticky list if requested. 15212 if (sticky) { 15213 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY, 15214 callingPid, callingUid) 15215 != PackageManager.PERMISSION_GRANTED) { 15216 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid=" 15217 + callingPid + ", uid=" + callingUid 15218 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 15219 Slog.w(TAG, msg); 15220 throw new SecurityException(msg); 15221 } 15222 if (requiredPermissions != null && requiredPermissions.length > 0) { 15223 Slog.w(TAG, "Can't broadcast sticky intent " + intent 15224 + " and enforce permissions " + Arrays.toString(requiredPermissions)); 15225 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 15226 } 15227 if (intent.getComponent() != null) { 15228 throw new SecurityException( 15229 "Sticky broadcasts can't target a specific component"); 15230 } 15231 // We use userId directly here, since the "all" target is maintained 15232 // as a separate set of sticky broadcasts. 15233 if (userId != UserHandle.USER_ALL) { 15234 // But first, if this is not a broadcast to all users, then 15235 // make sure it doesn't conflict with an existing broadcast to 15236 // all users. 15237 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get( 15238 UserHandle.USER_ALL); 15239 if (stickies != null) { 15240 ArrayList<Intent> list = stickies.get(intent.getAction()); 15241 if (list != null) { 15242 int N = list.size(); 15243 int i; 15244 for (i=0; i<N; i++) { 15245 if (intent.filterEquals(list.get(i))) { 15246 throw new IllegalArgumentException( 15247 "Sticky broadcast " + intent + " for user " 15248 + userId + " conflicts with existing global broadcast"); 15249 } 15250 } 15251 } 15252 } 15253 } 15254 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 15255 if (stickies == null) { 15256 stickies = new ArrayMap<>(); 15257 mStickyBroadcasts.put(userId, stickies); 15258 } 15259 ArrayList<Intent> list = stickies.get(intent.getAction()); 15260 if (list == null) { 15261 list = new ArrayList<>(); 15262 stickies.put(intent.getAction(), list); 15263 } 15264 final int stickiesCount = list.size(); 15265 int i; 15266 for (i = 0; i < stickiesCount; i++) { 15267 if (intent.filterEquals(list.get(i))) { 15268 // This sticky already exists, replace it. 15269 list.set(i, new Intent(intent)); 15270 break; 15271 } 15272 } 15273 if (i >= stickiesCount) { 15274 list.add(new Intent(intent)); 15275 } 15276 } 15277 15278 int[] users; 15279 if (userId == UserHandle.USER_ALL) { 15280 // Caller wants broadcast to go to all started users. 15281 users = mUserController.getStartedUserArray(); 15282 } else { 15283 // Caller wants broadcast to go to one specific user. 15284 users = new int[] {userId}; 15285 } 15286 15287 // Figure out who all will receive this broadcast. 15288 List receivers = null; 15289 List<BroadcastFilter> registeredReceivers = null; 15290 // Need to resolve the intent to interested receivers... 15291 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) 15292 == 0) { 15293 receivers = collectReceiverComponents(intent, resolvedType, callingUid, users); 15294 } 15295 if (intent.getComponent() == null) { 15296 if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) { 15297 // Query one target user at a time, excluding shell-restricted users 15298 for (int i = 0; i < users.length; i++) { 15299 if (mUserController.hasUserRestriction( 15300 UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) { 15301 continue; 15302 } 15303 List<BroadcastFilter> registeredReceiversForUser = 15304 mReceiverResolver.queryIntent(intent, 15305 resolvedType, false /*defaultOnly*/, users[i]); 15306 if (registeredReceivers == null) { 15307 registeredReceivers = registeredReceiversForUser; 15308 } else if (registeredReceiversForUser != null) { 15309 registeredReceivers.addAll(registeredReceiversForUser); 15310 } 15311 } 15312 } else { 15313 registeredReceivers = mReceiverResolver.queryIntent(intent, 15314 resolvedType, false /*defaultOnly*/, userId); 15315 } 15316 } 15317 15318 final boolean replacePending = 15319 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 15320 15321 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction() 15322 + " replacePending=" + replacePending); 15323 15324 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 15325 if (!ordered && NR > 0) { 15326 // If we are not serializing this broadcast, then send the 15327 // registered receivers separately so they don't wait for the 15328 // components to be launched. 15329 if (isCallerSystem) { 15330 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid, 15331 isProtectedBroadcast, registeredReceivers); 15332 } 15333 final BroadcastQueue queue = broadcastQueueForIntent(intent); 15334 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 15335 callerPackage, callingPid, callingUid, callerInstantApp, resolvedType, 15336 requiredPermissions, appOp, brOptions, registeredReceivers, resultTo, 15337 resultCode, resultData, resultExtras, ordered, sticky, false, userId, 15338 allowBackgroundActivityStarts, timeoutExempt); 15339 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r); 15340 final boolean replaced = replacePending 15341 && (queue.replaceParallelBroadcastLocked(r) != null); 15342 // Note: We assume resultTo is null for non-ordered broadcasts. 15343 if (!replaced) { 15344 queue.enqueueParallelBroadcastLocked(r); 15345 queue.scheduleBroadcastsLocked(); 15346 } 15347 registeredReceivers = null; 15348 NR = 0; 15349 } 15350 15351 // Merge into one list. 15352 int ir = 0; 15353 if (receivers != null) { 15354 // A special case for PACKAGE_ADDED: do not allow the package 15355 // being added to see this broadcast. This prevents them from 15356 // using this as a back door to get run as soon as they are 15357 // installed. Maybe in the future we want to have a special install 15358 // broadcast or such for apps, but we'd like to deliberately make 15359 // this decision. 15360 String skipPackages[] = null; 15361 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 15362 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 15363 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 15364 Uri data = intent.getData(); 15365 if (data != null) { 15366 String pkgName = data.getSchemeSpecificPart(); 15367 if (pkgName != null) { 15368 skipPackages = new String[] { pkgName }; 15369 } 15370 } 15371 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 15372 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 15373 } 15374 if (skipPackages != null && (skipPackages.length > 0)) { 15375 for (String skipPackage : skipPackages) { 15376 if (skipPackage != null) { 15377 int NT = receivers.size(); 15378 for (int it=0; it<NT; it++) { 15379 ResolveInfo curt = (ResolveInfo)receivers.get(it); 15380 if (curt.activityInfo.packageName.equals(skipPackage)) { 15381 receivers.remove(it); 15382 it--; 15383 NT--; 15384 } 15385 } 15386 } 15387 } 15388 } 15389 15390 int NT = receivers != null ? receivers.size() : 0; 15391 int it = 0; 15392 ResolveInfo curt = null; 15393 BroadcastFilter curr = null; 15394 while (it < NT && ir < NR) { 15395 if (curt == null) { 15396 curt = (ResolveInfo)receivers.get(it); 15397 } 15398 if (curr == null) { 15399 curr = registeredReceivers.get(ir); 15400 } 15401 if (curr.getPriority() >= curt.priority) { 15402 // Insert this broadcast record into the final list. 15403 receivers.add(it, curr); 15404 ir++; 15405 curr = null; 15406 it++; 15407 NT++; 15408 } else { 15409 // Skip to the next ResolveInfo in the final list. 15410 it++; 15411 curt = null; 15412 } 15413 } 15414 } 15415 while (ir < NR) { 15416 if (receivers == null) { 15417 receivers = new ArrayList(); 15418 } 15419 receivers.add(registeredReceivers.get(ir)); 15420 ir++; 15421 } 15422 15423 if (isCallerSystem) { 15424 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid, 15425 isProtectedBroadcast, receivers); 15426 } 15427 15428 if ((receivers != null && receivers.size() > 0) 15429 || resultTo != null) { 15430 BroadcastQueue queue = broadcastQueueForIntent(intent); 15431 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 15432 callerPackage, callingPid, callingUid, callerInstantApp, resolvedType, 15433 requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode, 15434 resultData, resultExtras, ordered, sticky, false, userId, 15435 allowBackgroundActivityStarts, timeoutExempt); 15436 15437 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r); 15438 15439 final BroadcastRecord oldRecord = 15440 replacePending ? queue.replaceOrderedBroadcastLocked(r) : null; 15441 if (oldRecord != null) { 15442 // Replaced, fire the result-to receiver. 15443 if (oldRecord.resultTo != null) { 15444 final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent); 15445 try { 15446 oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo, 15447 oldRecord.intent, 15448 Activity.RESULT_CANCELED, null, null, 15449 false, false, oldRecord.userId); 15450 } catch (RemoteException e) { 15451 Slog.w(TAG, "Failure [" 15452 + queue.mQueueName + "] sending broadcast result of " 15453 + intent, e); 15454 15455 } 15456 } 15457 } else { 15458 queue.enqueueOrderedBroadcastLocked(r); 15459 queue.scheduleBroadcastsLocked(); 15460 } 15461 } else { 15462 // There was nobody interested in the broadcast, but we still want to record 15463 // that it happened. 15464 if (intent.getComponent() == null && intent.getPackage() == null 15465 && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 15466 // This was an implicit broadcast... let's record it for posterity. 15467 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0); 15468 } 15469 } 15470 15471 return ActivityManager.BROADCAST_SUCCESS; 15472 } 15473 15474 /** 15475 * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1 15476 */ getUidFromIntent(Intent intent)15477 private int getUidFromIntent(Intent intent) { 15478 if (intent == null) { 15479 return -1; 15480 } 15481 final Bundle intentExtras = intent.getExtras(); 15482 return intent.hasExtra(Intent.EXTRA_UID) 15483 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 15484 } 15485 rotateBroadcastStatsIfNeededLocked()15486 final void rotateBroadcastStatsIfNeededLocked() { 15487 final long now = SystemClock.elapsedRealtime(); 15488 if (mCurBroadcastStats == null || 15489 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) { 15490 mLastBroadcastStats = mCurBroadcastStats; 15491 if (mLastBroadcastStats != null) { 15492 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime(); 15493 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis(); 15494 } 15495 mCurBroadcastStats = new BroadcastStats(); 15496 } 15497 } 15498 addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)15499 final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount, 15500 int skipCount, long dispatchTime) { 15501 rotateBroadcastStatsIfNeededLocked(); 15502 mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime); 15503 } 15504 addBackgroundCheckViolationLocked(String action, String targetPackage)15505 final void addBackgroundCheckViolationLocked(String action, String targetPackage) { 15506 rotateBroadcastStatsIfNeededLocked(); 15507 mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage); 15508 } 15509 verifyBroadcastLocked(Intent intent)15510 final Intent verifyBroadcastLocked(Intent intent) { 15511 // Refuse possible leaked file descriptors 15512 if (intent != null && intent.hasFileDescriptors() == true) { 15513 throw new IllegalArgumentException("File descriptors passed in Intent"); 15514 } 15515 15516 int flags = intent.getFlags(); 15517 15518 if (!mProcessesReady) { 15519 // if the caller really truly claims to know what they're doing, go 15520 // ahead and allow the broadcast without launching any receivers 15521 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 15522 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed. 15523 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 15524 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 15525 + " before boot completion"); 15526 throw new IllegalStateException("Cannot broadcast before boot completed"); 15527 } 15528 } 15529 15530 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 15531 throw new IllegalArgumentException( 15532 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 15533 } 15534 15535 if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 15536 switch (Binder.getCallingUid()) { 15537 case ROOT_UID: 15538 case SHELL_UID: 15539 break; 15540 default: 15541 Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID " 15542 + Binder.getCallingUid()); 15543 intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL); 15544 break; 15545 } 15546 } 15547 15548 return intent; 15549 } 15550 broadcastIntent(IApplicationThread caller, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, boolean serialized, boolean sticky, int userId)15551 public final int broadcastIntent(IApplicationThread caller, 15552 Intent intent, String resolvedType, IIntentReceiver resultTo, 15553 int resultCode, String resultData, Bundle resultExtras, 15554 String[] requiredPermissions, int appOp, Bundle bOptions, 15555 boolean serialized, boolean sticky, int userId) { 15556 enforceNotIsolatedCaller("broadcastIntent"); 15557 synchronized(this) { 15558 intent = verifyBroadcastLocked(intent); 15559 15560 final ProcessRecord callerApp = getRecordForAppLocked(caller); 15561 final int callingPid = Binder.getCallingPid(); 15562 final int callingUid = Binder.getCallingUid(); 15563 15564 final long origId = Binder.clearCallingIdentity(); 15565 try { 15566 return broadcastIntentLocked(callerApp, 15567 callerApp != null ? callerApp.info.packageName : null, 15568 intent, resolvedType, resultTo, resultCode, resultData, resultExtras, 15569 requiredPermissions, appOp, bOptions, serialized, sticky, 15570 callingPid, callingUid, callingUid, callingPid, userId); 15571 } finally { 15572 Binder.restoreCallingIdentity(origId); 15573 } 15574 } 15575 } 15576 broadcastIntentInPackage(String packageName, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, boolean allowBackgroundActivityStarts)15577 int broadcastIntentInPackage(String packageName, int uid, int realCallingUid, 15578 int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, 15579 int resultCode, String resultData, Bundle resultExtras, 15580 String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, 15581 int userId, boolean allowBackgroundActivityStarts) { 15582 synchronized(this) { 15583 intent = verifyBroadcastLocked(intent); 15584 15585 final long origId = Binder.clearCallingIdentity(); 15586 String[] requiredPermissions = requiredPermission == null ? null 15587 : new String[] {requiredPermission}; 15588 try { 15589 return broadcastIntentLocked(null, packageName, intent, resolvedType, 15590 resultTo, resultCode, resultData, resultExtras, 15591 requiredPermissions, OP_NONE, bOptions, serialized, 15592 sticky, -1, uid, realCallingUid, realCallingPid, userId, 15593 allowBackgroundActivityStarts); 15594 } finally { 15595 Binder.restoreCallingIdentity(origId); 15596 } 15597 } 15598 } 15599 unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)15600 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 15601 // Refuse possible leaked file descriptors 15602 if (intent != null && intent.hasFileDescriptors() == true) { 15603 throw new IllegalArgumentException("File descriptors passed in Intent"); 15604 } 15605 15606 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 15607 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null); 15608 15609 synchronized(this) { 15610 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 15611 != PackageManager.PERMISSION_GRANTED) { 15612 String msg = "Permission Denial: unbroadcastIntent() from pid=" 15613 + Binder.getCallingPid() 15614 + ", uid=" + Binder.getCallingUid() 15615 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 15616 Slog.w(TAG, msg); 15617 throw new SecurityException(msg); 15618 } 15619 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 15620 if (stickies != null) { 15621 ArrayList<Intent> list = stickies.get(intent.getAction()); 15622 if (list != null) { 15623 int N = list.size(); 15624 int i; 15625 for (i=0; i<N; i++) { 15626 if (intent.filterEquals(list.get(i))) { 15627 list.remove(i); 15628 break; 15629 } 15630 } 15631 if (list.size() <= 0) { 15632 stickies.remove(intent.getAction()); 15633 } 15634 } 15635 if (stickies.size() <= 0) { 15636 mStickyBroadcasts.remove(userId); 15637 } 15638 } 15639 } 15640 } 15641 backgroundServicesFinishedLocked(int userId)15642 void backgroundServicesFinishedLocked(int userId) { 15643 for (BroadcastQueue queue : mBroadcastQueues) { 15644 queue.backgroundServicesFinishedLocked(userId); 15645 } 15646 } 15647 finishReceiver(IBinder who, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)15648 public void finishReceiver(IBinder who, int resultCode, String resultData, 15649 Bundle resultExtras, boolean resultAbort, int flags) { 15650 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who); 15651 15652 // Refuse possible leaked file descriptors 15653 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 15654 throw new IllegalArgumentException("File descriptors passed in Bundle"); 15655 } 15656 15657 final long origId = Binder.clearCallingIdentity(); 15658 try { 15659 boolean doNext = false; 15660 BroadcastRecord r; 15661 BroadcastQueue queue; 15662 15663 synchronized(this) { 15664 if (isOnOffloadQueue(flags)) { 15665 queue = mOffloadBroadcastQueue; 15666 } else { 15667 queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0 15668 ? mFgBroadcastQueue : mBgBroadcastQueue; 15669 } 15670 15671 r = queue.getMatchingOrderedReceiver(who); 15672 if (r != null) { 15673 doNext = r.queue.finishReceiverLocked(r, resultCode, 15674 resultData, resultExtras, resultAbort, true); 15675 } 15676 if (doNext) { 15677 r.queue.processNextBroadcastLocked(/*fromMsg=*/ false, /*skipOomAdj=*/ true); 15678 } 15679 // updateOomAdjLocked() will be done here 15680 trimApplicationsLocked(OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER); 15681 } 15682 15683 } finally { 15684 Binder.restoreCallingIdentity(origId); 15685 } 15686 } 15687 15688 // ========================================================= 15689 // INSTRUMENTATION 15690 // ========================================================= 15691 startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)15692 public boolean startInstrumentation(ComponentName className, 15693 String profileFile, int flags, Bundle arguments, 15694 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 15695 int userId, String abiOverride) { 15696 enforceNotIsolatedCaller("startInstrumentation"); 15697 final int callingUid = Binder.getCallingUid(); 15698 final int callingPid = Binder.getCallingPid(); 15699 userId = mUserController.handleIncomingUser(callingPid, callingUid, 15700 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 15701 // Refuse possible leaked file descriptors 15702 if (arguments != null && arguments.hasFileDescriptors()) { 15703 throw new IllegalArgumentException("File descriptors passed in Bundle"); 15704 } 15705 15706 synchronized(this) { 15707 InstrumentationInfo ii = null; 15708 ApplicationInfo ai = null; 15709 try { 15710 ii = mContext.getPackageManager().getInstrumentationInfo( 15711 className, STOCK_PM_FLAGS); 15712 ai = AppGlobals.getPackageManager().getApplicationInfo( 15713 ii.targetPackage, STOCK_PM_FLAGS, userId); 15714 } catch (PackageManager.NameNotFoundException e) { 15715 } catch (RemoteException e) { 15716 } 15717 if (ii == null) { 15718 reportStartInstrumentationFailureLocked(watcher, className, 15719 "Unable to find instrumentation info for: " + className); 15720 return false; 15721 } 15722 if (ai == null) { 15723 reportStartInstrumentationFailureLocked(watcher, className, 15724 "Unable to find instrumentation target package: " + ii.targetPackage); 15725 return false; 15726 } 15727 if (!ai.hasCode()) { 15728 reportStartInstrumentationFailureLocked(watcher, className, 15729 "Instrumentation target has no code: " + ii.targetPackage); 15730 return false; 15731 } 15732 15733 int match = mContext.getPackageManager().checkSignatures( 15734 ii.targetPackage, ii.packageName); 15735 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 15736 String msg = "Permission Denial: starting instrumentation " 15737 + className + " from pid=" 15738 + Binder.getCallingPid() 15739 + ", uid=" + Binder.getCallingPid() 15740 + " not allowed because package " + ii.packageName 15741 + " does not have a signature matching the target " 15742 + ii.targetPackage; 15743 reportStartInstrumentationFailureLocked(watcher, className, msg); 15744 throw new SecurityException(msg); 15745 } 15746 15747 ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); 15748 activeInstr.mClass = className; 15749 String defProcess = ai.processName;; 15750 if (ii.targetProcesses == null) { 15751 activeInstr.mTargetProcesses = new String[]{ai.processName}; 15752 } else if (ii.targetProcesses.equals("*")) { 15753 activeInstr.mTargetProcesses = new String[0]; 15754 } else { 15755 activeInstr.mTargetProcesses = ii.targetProcesses.split(","); 15756 defProcess = activeInstr.mTargetProcesses[0]; 15757 } 15758 activeInstr.mTargetInfo = ai; 15759 activeInstr.mProfileFile = profileFile; 15760 activeInstr.mArguments = arguments; 15761 activeInstr.mWatcher = watcher; 15762 activeInstr.mUiAutomationConnection = uiAutomationConnection; 15763 activeInstr.mResultClass = className; 15764 activeInstr.mHasBackgroundActivityStartsPermission = checkPermission( 15765 START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid) 15766 == PackageManager.PERMISSION_GRANTED; 15767 15768 boolean disableHiddenApiChecks = ai.usesNonSdkApi() 15769 || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0; 15770 if (disableHiddenApiChecks) { 15771 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS, 15772 "disable hidden API checks"); 15773 } 15774 final boolean mountExtStorageFull = isCallerShell() 15775 && (flags & INSTR_FLAG_MOUNT_EXTERNAL_STORAGE_FULL) != 0; 15776 15777 final long origId = Binder.clearCallingIdentity(); 15778 // Instrumentation can kill and relaunch even persistent processes 15779 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId, 15780 "start instr"); 15781 // Inform usage stats to make the target package active 15782 if (mUsageStatsService != null) { 15783 mUsageStatsService.reportEvent(ii.targetPackage, userId, 15784 UsageEvents.Event.SYSTEM_INTERACTION); 15785 } 15786 15787 ProcessRecord app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks, 15788 mountExtStorageFull, abiOverride); 15789 app.setActiveInstrumentation(activeInstr); 15790 activeInstr.mFinished = false; 15791 activeInstr.mRunningProcesses.add(app); 15792 if (!mActiveInstrumentation.contains(activeInstr)) { 15793 mActiveInstrumentation.add(activeInstr); 15794 } 15795 Binder.restoreCallingIdentity(origId); 15796 } 15797 15798 return true; 15799 } 15800 isCallerShell()15801 private boolean isCallerShell() { 15802 final int callingUid = Binder.getCallingUid(); 15803 return callingUid == SHELL_UID || callingUid == ROOT_UID; 15804 } 15805 15806 /** 15807 * Report errors that occur while attempting to start Instrumentation. Always writes the 15808 * error to the logs, but if somebody is watching, send the report there too. This enables 15809 * the "am" command to report errors with more information. 15810 * 15811 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 15812 * @param cn The component name of the instrumentation. 15813 * @param report The error report. 15814 */ reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)15815 private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, 15816 ComponentName cn, String report) { 15817 Slog.w(TAG, report); 15818 if (watcher != null) { 15819 Bundle results = new Bundle(); 15820 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 15821 results.putString("Error", report); 15822 mInstrumentationReporter.reportStatus(watcher, cn, -1, results); 15823 } 15824 } 15825 addInstrumentationResultsLocked(ProcessRecord app, Bundle results)15826 void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) { 15827 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 15828 if (instr == null) { 15829 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 15830 return; 15831 } 15832 15833 if (!instr.mFinished && results != null) { 15834 if (instr.mCurResults == null) { 15835 instr.mCurResults = new Bundle(results); 15836 } else { 15837 instr.mCurResults.putAll(results); 15838 } 15839 } 15840 } 15841 addInstrumentationResults(IApplicationThread target, Bundle results)15842 public void addInstrumentationResults(IApplicationThread target, Bundle results) { 15843 int userId = UserHandle.getCallingUserId(); 15844 // Refuse possible leaked file descriptors 15845 if (results != null && results.hasFileDescriptors()) { 15846 throw new IllegalArgumentException("File descriptors passed in Intent"); 15847 } 15848 15849 synchronized(this) { 15850 ProcessRecord app = getRecordForAppLocked(target); 15851 if (app == null) { 15852 Slog.w(TAG, "addInstrumentationResults: no app for " + target); 15853 return; 15854 } 15855 final long origId = Binder.clearCallingIdentity(); 15856 addInstrumentationResultsLocked(app, results); 15857 Binder.restoreCallingIdentity(origId); 15858 } 15859 } 15860 15861 @GuardedBy("this") finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)15862 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 15863 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 15864 if (instr == null) { 15865 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 15866 return; 15867 } 15868 15869 if (!instr.mFinished) { 15870 if (instr.mWatcher != null) { 15871 Bundle finalResults = instr.mCurResults; 15872 if (finalResults != null) { 15873 if (instr.mCurResults != null && results != null) { 15874 finalResults.putAll(results); 15875 } 15876 } else { 15877 finalResults = results; 15878 } 15879 mInstrumentationReporter.reportFinished(instr.mWatcher, 15880 instr.mClass, resultCode, finalResults); 15881 } 15882 15883 // Can't call out of the system process with a lock held, so post a message. 15884 if (instr.mUiAutomationConnection != null) { 15885 mAppOpsService.setAppOpsServiceDelegate(null); 15886 getPackageManagerInternalLocked().setCheckPermissionDelegate(null); 15887 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG, 15888 instr.mUiAutomationConnection).sendToTarget(); 15889 } 15890 instr.mFinished = true; 15891 } 15892 15893 instr.removeProcess(app); 15894 app.setActiveInstrumentation(null); 15895 15896 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId, 15897 "finished inst"); 15898 } 15899 finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)15900 public void finishInstrumentation(IApplicationThread target, 15901 int resultCode, Bundle results) { 15902 int userId = UserHandle.getCallingUserId(); 15903 // Refuse possible leaked file descriptors 15904 if (results != null && results.hasFileDescriptors()) { 15905 throw new IllegalArgumentException("File descriptors passed in Intent"); 15906 } 15907 15908 synchronized(this) { 15909 ProcessRecord app = getRecordForAppLocked(target); 15910 if (app == null) { 15911 Slog.w(TAG, "finishInstrumentation: no app for " + target); 15912 return; 15913 } 15914 final long origId = Binder.clearCallingIdentity(); 15915 finishInstrumentationLocked(app, resultCode, results); 15916 Binder.restoreCallingIdentity(origId); 15917 } 15918 } 15919 15920 @Override getFocusedStackInfo()15921 public StackInfo getFocusedStackInfo() throws RemoteException { 15922 return mActivityTaskManager.getFocusedStackInfo(); 15923 } 15924 15925 @Override getConfiguration()15926 public Configuration getConfiguration() { 15927 return mActivityTaskManager.getConfiguration(); 15928 } 15929 15930 @Override suppressResizeConfigChanges(boolean suppress)15931 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException { 15932 mActivityTaskManager.suppressResizeConfigChanges(suppress); 15933 } 15934 15935 @Override updatePersistentConfiguration(Configuration values)15936 public void updatePersistentConfiguration(Configuration values) { 15937 enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()"); 15938 enforceWriteSettingsPermission("updatePersistentConfiguration()"); 15939 if (values == null) { 15940 throw new NullPointerException("Configuration must not be null"); 15941 } 15942 15943 int userId = UserHandle.getCallingUserId(); 15944 15945 mActivityTaskManager.updatePersistentConfiguration(values, userId); 15946 } 15947 enforceWriteSettingsPermission(String func)15948 private void enforceWriteSettingsPermission(String func) { 15949 int uid = Binder.getCallingUid(); 15950 if (uid == ROOT_UID) { 15951 return; 15952 } 15953 15954 if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid, 15955 Settings.getPackageNameForUid(mContext, uid), false)) { 15956 return; 15957 } 15958 15959 String msg = "Permission Denial: " + func + " from pid=" 15960 + Binder.getCallingPid() 15961 + ", uid=" + uid 15962 + " requires " + android.Manifest.permission.WRITE_SETTINGS; 15963 Slog.w(TAG, msg); 15964 throw new SecurityException(msg); 15965 } 15966 15967 @Override updateConfiguration(Configuration values)15968 public boolean updateConfiguration(Configuration values) { 15969 return mActivityTaskManager.updateConfiguration(values); 15970 } 15971 15972 @Override getLaunchedFromUid(IBinder activityToken)15973 public int getLaunchedFromUid(IBinder activityToken) { 15974 return mActivityTaskManager.getLaunchedFromUid(activityToken); 15975 } 15976 getLaunchedFromPackage(IBinder activityToken)15977 public String getLaunchedFromPackage(IBinder activityToken) { 15978 return mActivityTaskManager.getLaunchedFromPackage(activityToken); 15979 } 15980 15981 // ========================================================= 15982 // LIFETIME MANAGEMENT 15983 // ========================================================= 15984 15985 // Returns whether the app is receiving broadcast. 15986 // If receiving, fetch all broadcast queues which the app is 15987 // the current [or imminent] receiver on. isReceivingBroadcastLocked(ProcessRecord app, ArraySet<BroadcastQueue> receivingQueues)15988 boolean isReceivingBroadcastLocked(ProcessRecord app, 15989 ArraySet<BroadcastQueue> receivingQueues) { 15990 final int N = app.curReceivers.size(); 15991 if (N > 0) { 15992 for (int i = 0; i < N; i++) { 15993 receivingQueues.add(app.curReceivers.valueAt(i).queue); 15994 } 15995 return true; 15996 } 15997 15998 // It's not the current receiver, but it might be starting up to become one 15999 for (BroadcastQueue queue : mBroadcastQueues) { 16000 final BroadcastRecord r = queue.mPendingBroadcast; 16001 if (r != null && r.curApp == app) { 16002 // found it; report which queue it's in 16003 receivingQueues.add(queue); 16004 } 16005 } 16006 16007 return !receivingQueues.isEmpty(); 16008 } 16009 startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16010 Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, 16011 int targetUid, long targetVersionCode, ComponentName targetComponent, 16012 String targetProcess) { 16013 if (!mTrackingAssociations) { 16014 return null; 16015 } 16016 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 16017 = mAssociations.get(targetUid); 16018 if (components == null) { 16019 components = new ArrayMap<>(); 16020 mAssociations.put(targetUid, components); 16021 } 16022 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 16023 if (sourceUids == null) { 16024 sourceUids = new SparseArray<>(); 16025 components.put(targetComponent, sourceUids); 16026 } 16027 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 16028 if (sourceProcesses == null) { 16029 sourceProcesses = new ArrayMap<>(); 16030 sourceUids.put(sourceUid, sourceProcesses); 16031 } 16032 Association ass = sourceProcesses.get(sourceProcess); 16033 if (ass == null) { 16034 ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent, 16035 targetProcess); 16036 sourceProcesses.put(sourceProcess, ass); 16037 } 16038 ass.mCount++; 16039 ass.mNesting++; 16040 if (ass.mNesting == 1) { 16041 ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis(); 16042 ass.mLastState = sourceState; 16043 } 16044 return ass; 16045 } 16046 stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16047 void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, 16048 long targetVersionCode, ComponentName targetComponent, String targetProcess) { 16049 if (!mTrackingAssociations) { 16050 return; 16051 } 16052 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 16053 = mAssociations.get(targetUid); 16054 if (components == null) { 16055 return; 16056 } 16057 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 16058 if (sourceUids == null) { 16059 return; 16060 } 16061 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 16062 if (sourceProcesses == null) { 16063 return; 16064 } 16065 Association ass = sourceProcesses.get(sourceProcess); 16066 if (ass == null || ass.mNesting <= 0) { 16067 return; 16068 } 16069 ass.mNesting--; 16070 if (ass.mNesting == 0) { 16071 long uptime = SystemClock.uptimeMillis(); 16072 ass.mTime += uptime - ass.mStartTime; 16073 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 16074 += uptime - ass.mLastStateUptime; 16075 ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2; 16076 } 16077 } 16078 noteUidProcessState(final int uid, final int state)16079 void noteUidProcessState(final int uid, final int state) { 16080 mBatteryStatsService.noteUidProcessState(uid, state); 16081 mAppOpsService.updateUidProcState(uid, state); 16082 if (mTrackingAssociations) { 16083 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 16084 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 16085 = mAssociations.valueAt(i1); 16086 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 16087 SparseArray<ArrayMap<String, Association>> sourceUids 16088 = targetComponents.valueAt(i2); 16089 ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid); 16090 if (sourceProcesses != null) { 16091 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 16092 Association ass = sourceProcesses.valueAt(i4); 16093 if (ass.mNesting >= 1) { 16094 // currently associated 16095 long uptime = SystemClock.uptimeMillis(); 16096 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 16097 += uptime - ass.mLastStateUptime; 16098 ass.mLastState = state; 16099 ass.mLastStateUptime = uptime; 16100 } 16101 } 16102 } 16103 } 16104 } 16105 } 16106 } 16107 16108 private static final class RecordPssRunnable implements Runnable { 16109 private final ActivityManagerService mService; 16110 private final ProcessRecord mProc; 16111 private final File mHeapdumpFile; 16112 RecordPssRunnable(ActivityManagerService service, ProcessRecord proc, File heapdumpFile)16113 RecordPssRunnable(ActivityManagerService service, ProcessRecord proc, File heapdumpFile) { 16114 this.mService = service; 16115 this.mProc = proc; 16116 this.mHeapdumpFile = heapdumpFile; 16117 } 16118 16119 @Override run()16120 public void run() { 16121 mService.revokeUriPermission(ActivityThread.currentActivityThread() 16122 .getApplicationThread(), 16123 null, DumpHeapActivity.JAVA_URI, 16124 Intent.FLAG_GRANT_READ_URI_PERMISSION 16125 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 16126 UserHandle.myUserId()); 16127 ParcelFileDescriptor fd = null; 16128 try { 16129 mHeapdumpFile.delete(); 16130 fd = ParcelFileDescriptor.open(mHeapdumpFile, 16131 ParcelFileDescriptor.MODE_CREATE 16132 | ParcelFileDescriptor.MODE_TRUNCATE 16133 | ParcelFileDescriptor.MODE_WRITE_ONLY 16134 | ParcelFileDescriptor.MODE_APPEND); 16135 IApplicationThread thread = mProc.thread; 16136 if (thread != null) { 16137 try { 16138 if (DEBUG_PSS) { 16139 Slog.d(TAG_PSS, "Requesting dump heap from " 16140 + mProc + " to " + mHeapdumpFile); 16141 } 16142 thread.dumpHeap(/* managed= */ true, 16143 /* mallocInfo= */ false, /* runGc= */ false, 16144 mHeapdumpFile.toString(), fd, 16145 /* finishCallback= */ null); 16146 } catch (RemoteException e) { 16147 } 16148 } 16149 } catch (FileNotFoundException e) { 16150 e.printStackTrace(); 16151 } finally { 16152 if (fd != null) { 16153 try { 16154 fd.close(); 16155 } catch (IOException e) { 16156 } 16157 } 16158 } 16159 } 16160 } 16161 16162 /** 16163 * Record new PSS sample for a process. 16164 */ recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss, long rss, int statType, long pssDuration, long now)16165 void recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss, 16166 long rss, int statType, long pssDuration, long now) { 16167 EventLogTags.writeAmPss(proc.pid, proc.uid, proc.processName, pss * 1024, uss * 1024, 16168 swapPss * 1024, rss * 1024, statType, procState, pssDuration); 16169 proc.lastPssTime = now; 16170 proc.baseProcessTracker.addPss( 16171 pss, uss, rss, true, statType, pssDuration, proc.pkgList.mPkgList); 16172 for (int ipkg = proc.pkgList.mPkgList.size() - 1; ipkg >= 0; ipkg--) { 16173 ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg); 16174 StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED, 16175 proc.info.uid, 16176 holder.state.getName(), 16177 holder.state.getPackage(), 16178 pss, uss, rss, statType, pssDuration, 16179 holder.appVersion); 16180 } 16181 if (DEBUG_PSS) Slog.d(TAG_PSS, 16182 "pss of " + proc.toShortString() + ": " + pss + " lastPss=" + proc.lastPss 16183 + " state=" + ProcessList.makeProcStateString(procState)); 16184 if (proc.initialIdlePss == 0) { 16185 proc.initialIdlePss = pss; 16186 } 16187 proc.lastPss = pss; 16188 proc.lastSwapPss = swapPss; 16189 if (procState >= ActivityManager.PROCESS_STATE_HOME) { 16190 proc.lastCachedPss = pss; 16191 proc.lastCachedSwapPss = swapPss; 16192 } 16193 16194 final SparseArray<Pair<Long, String>> watchUids 16195 = mMemWatchProcesses.getMap().get(proc.processName); 16196 Long check = null; 16197 if (watchUids != null) { 16198 Pair<Long, String> val = watchUids.get(proc.uid); 16199 if (val == null) { 16200 val = watchUids.get(0); 16201 } 16202 if (val != null) { 16203 check = val.first; 16204 } 16205 } 16206 if (check != null) { 16207 if ((pss * 1024) >= check && proc.thread != null && mMemWatchDumpProcName == null) { 16208 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 16209 if (!isDebuggable) { 16210 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 16211 isDebuggable = true; 16212 } 16213 } 16214 if (isDebuggable) { 16215 Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check + "; reporting"); 16216 startHeapDumpLocked(proc, false); 16217 } else { 16218 Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check 16219 + ", but debugging not enabled"); 16220 } 16221 } 16222 } 16223 } 16224 startHeapDumpLocked(ProcessRecord proc, boolean isUserInitiated)16225 private void startHeapDumpLocked(ProcessRecord proc, boolean isUserInitiated) { 16226 final File heapdumpFile = DumpHeapProvider.getJavaFile(); 16227 mMemWatchDumpProcName = proc.processName; 16228 mMemWatchDumpFile = heapdumpFile.toString(); 16229 mMemWatchDumpPid = proc.pid; 16230 mMemWatchDumpUid = proc.uid; 16231 mMemWatchIsUserInitiated = isUserInitiated; 16232 BackgroundThread.getHandler().post(new RecordPssRunnable(this, proc, heapdumpFile)); 16233 } 16234 16235 /** 16236 * Schedule PSS collection of a process. 16237 */ requestPssLocked(ProcessRecord proc, int procState)16238 boolean requestPssLocked(ProcessRecord proc, int procState) { 16239 if (mPendingPssProcesses.contains(proc)) { 16240 return false; 16241 } 16242 if (mPendingPssProcesses.size() == 0) { 16243 final long deferral = (mPssDeferralTime > 0 && mActivityStartingNesting.get() > 0) 16244 ? mPssDeferralTime : 0; 16245 if (DEBUG_PSS && deferral > 0) { 16246 Slog.d(TAG_PSS, "requestPssLocked() deferring PSS request by " 16247 + deferral + " ms"); 16248 } 16249 mBgHandler.sendEmptyMessageDelayed(COLLECT_PSS_BG_MSG, deferral); 16250 } 16251 if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of: " + proc); 16252 proc.pssProcState = procState; 16253 proc.pssStatType = ProcessStats.ADD_PSS_INTERNAL_SINGLE; 16254 mPendingPssProcesses.add(proc); 16255 return true; 16256 } 16257 16258 /** 16259 * Re-defer a posted PSS collection pass, if one exists. Assumes deferral is 16260 * currently active policy when called. 16261 */ deferPssIfNeededLocked()16262 private void deferPssIfNeededLocked() { 16263 if (mPendingPssProcesses.size() > 0) { 16264 mBgHandler.removeMessages(COLLECT_PSS_BG_MSG); 16265 mBgHandler.sendEmptyMessageDelayed(COLLECT_PSS_BG_MSG, mPssDeferralTime); 16266 } 16267 } 16268 deferPssForActivityStart()16269 private void deferPssForActivityStart() { 16270 synchronized (ActivityManagerService.this) { 16271 if (mPssDeferralTime > 0) { 16272 if (DEBUG_PSS) { 16273 Slog.d(TAG_PSS, "Deferring PSS collection for activity start"); 16274 } 16275 deferPssIfNeededLocked(); 16276 mActivityStartingNesting.getAndIncrement(); 16277 mBgHandler.sendEmptyMessageDelayed(STOP_DEFERRING_PSS_MSG, mPssDeferralTime); 16278 } 16279 } 16280 } 16281 16282 /** 16283 * Schedule PSS collection of all processes. 16284 */ requestPssAllProcsLocked(long now, boolean always, boolean memLowered)16285 void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) { 16286 if (!always) { 16287 if (now < (mLastFullPssTime + 16288 (memLowered ? mConstants.FULL_PSS_LOWERED_INTERVAL 16289 : mConstants.FULL_PSS_MIN_INTERVAL))) { 16290 return; 16291 } 16292 } 16293 if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of all procs! memLowered=" + memLowered); 16294 mLastFullPssTime = now; 16295 mFullPssPending = true; 16296 for (int i = mPendingPssProcesses.size() - 1; i >= 0; i--) { 16297 ProcessList.abortNextPssTime(mPendingPssProcesses.get(i).procStateMemTracker);; 16298 } 16299 mPendingPssProcesses.ensureCapacity(mProcessList.getLruSizeLocked()); 16300 mPendingPssProcesses.clear(); 16301 for (int i = mProcessList.getLruSizeLocked() - 1; i >= 0; i--) { 16302 ProcessRecord app = mProcessList.mLruProcesses.get(i); 16303 if (app.thread == null || app.getCurProcState() == PROCESS_STATE_NONEXISTENT) { 16304 continue; 16305 } 16306 if (memLowered || (always && now > 16307 app.lastStateTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE) 16308 || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) { 16309 app.pssProcState = app.setProcState; 16310 app.pssStatType = always ? ProcessStats.ADD_PSS_INTERNAL_ALL_POLL 16311 : ProcessStats.ADD_PSS_INTERNAL_ALL_MEM; 16312 app.nextPssTime = ProcessList.computeNextPssTime(app.getCurProcState(), 16313 app.procStateMemTracker, mTestPssMode, mAtmInternal.isSleeping(), now); 16314 mPendingPssProcesses.add(app); 16315 } 16316 } 16317 if (!mBgHandler.hasMessages(COLLECT_PSS_BG_MSG)) { 16318 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 16319 } 16320 } 16321 setTestPssMode(boolean enabled)16322 public void setTestPssMode(boolean enabled) { 16323 synchronized (this) { 16324 mTestPssMode = enabled; 16325 if (enabled) { 16326 // Whenever we enable the mode, we want to take a snapshot all of current 16327 // process mem use. 16328 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, true); 16329 } 16330 } 16331 } 16332 16333 /** 16334 * Ask a given process to GC right now. 16335 */ performAppGcLocked(ProcessRecord app)16336 final void performAppGcLocked(ProcessRecord app) { 16337 try { 16338 app.lastRequestedGc = SystemClock.uptimeMillis(); 16339 if (app.thread != null) { 16340 if (app.reportLowMemory) { 16341 app.reportLowMemory = false; 16342 app.thread.scheduleLowMemory(); 16343 } else { 16344 app.thread.processInBackground(); 16345 } 16346 } 16347 } catch (Exception e) { 16348 // whatever. 16349 } 16350 } 16351 16352 /** 16353 * Returns true if things are idle enough to perform GCs. 16354 */ canGcNowLocked()16355 private final boolean canGcNowLocked() { 16356 for (BroadcastQueue q : mBroadcastQueues) { 16357 if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isEmpty()) { 16358 return false; 16359 } 16360 } 16361 return mAtmInternal.canGcNow(); 16362 } 16363 16364 /** 16365 * Perform GCs on all processes that are waiting for it, but only 16366 * if things are idle. 16367 */ performAppGcsLocked()16368 final void performAppGcsLocked() { 16369 final int N = mProcessesToGc.size(); 16370 if (N <= 0) { 16371 return; 16372 } 16373 if (canGcNowLocked()) { 16374 while (mProcessesToGc.size() > 0) { 16375 ProcessRecord proc = mProcessesToGc.remove(0); 16376 if (proc.getCurRawAdj() > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) { 16377 if ((proc.lastRequestedGc+mConstants.GC_MIN_INTERVAL) 16378 <= SystemClock.uptimeMillis()) { 16379 // To avoid spamming the system, we will GC processes one 16380 // at a time, waiting a few seconds between each. 16381 performAppGcLocked(proc); 16382 scheduleAppGcsLocked(); 16383 return; 16384 } else { 16385 // It hasn't been long enough since we last GCed this 16386 // process... put it in the list to wait for its time. 16387 addProcessToGcListLocked(proc); 16388 break; 16389 } 16390 } 16391 } 16392 16393 scheduleAppGcsLocked(); 16394 } 16395 } 16396 16397 /** 16398 * If all looks good, perform GCs on all processes waiting for them. 16399 */ performAppGcsIfAppropriateLocked()16400 final void performAppGcsIfAppropriateLocked() { 16401 if (canGcNowLocked()) { 16402 performAppGcsLocked(); 16403 return; 16404 } 16405 // Still not idle, wait some more. 16406 scheduleAppGcsLocked(); 16407 } 16408 16409 /** 16410 * Schedule the execution of all pending app GCs. 16411 */ scheduleAppGcsLocked()16412 final void scheduleAppGcsLocked() { 16413 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG); 16414 16415 if (mProcessesToGc.size() > 0) { 16416 // Schedule a GC for the time to the next process. 16417 ProcessRecord proc = mProcessesToGc.get(0); 16418 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG); 16419 16420 long when = proc.lastRequestedGc + mConstants.GC_MIN_INTERVAL; 16421 long now = SystemClock.uptimeMillis(); 16422 if (when < (now+mConstants.GC_TIMEOUT)) { 16423 when = now + mConstants.GC_TIMEOUT; 16424 } 16425 mHandler.sendMessageAtTime(msg, when); 16426 } 16427 } 16428 16429 /** 16430 * Add a process to the array of processes waiting to be GCed. Keeps the 16431 * list in sorted order by the last GC time. The process can't already be 16432 * on the list. 16433 */ addProcessToGcListLocked(ProcessRecord proc)16434 final void addProcessToGcListLocked(ProcessRecord proc) { 16435 boolean added = false; 16436 for (int i=mProcessesToGc.size()-1; i>=0; i--) { 16437 if (mProcessesToGc.get(i).lastRequestedGc < 16438 proc.lastRequestedGc) { 16439 added = true; 16440 mProcessesToGc.add(i+1, proc); 16441 break; 16442 } 16443 } 16444 if (!added) { 16445 mProcessesToGc.add(0, proc); 16446 } 16447 } 16448 16449 /** 16450 * Set up to ask a process to GC itself. This will either do it 16451 * immediately, or put it on the list of processes to gc the next 16452 * time things are idle. 16453 */ scheduleAppGcLocked(ProcessRecord app)16454 final void scheduleAppGcLocked(ProcessRecord app) { 16455 long now = SystemClock.uptimeMillis(); 16456 if ((app.lastRequestedGc+mConstants.GC_MIN_INTERVAL) > now) { 16457 return; 16458 } 16459 if (!mProcessesToGc.contains(app)) { 16460 addProcessToGcListLocked(app); 16461 scheduleAppGcsLocked(); 16462 } 16463 } 16464 checkExcessivePowerUsageLocked()16465 final void checkExcessivePowerUsageLocked() { 16466 updateCpuStatsNow(); 16467 16468 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 16469 boolean doCpuKills = true; 16470 if (mLastPowerCheckUptime == 0) { 16471 doCpuKills = false; 16472 } 16473 final long curUptime = SystemClock.uptimeMillis(); 16474 final long uptimeSince = curUptime - mLastPowerCheckUptime; 16475 mLastPowerCheckUptime = curUptime; 16476 int i = mProcessList.mLruProcesses.size(); 16477 while (i > 0) { 16478 i--; 16479 ProcessRecord app = mProcessList.mLruProcesses.get(i); 16480 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 16481 if (app.lastCpuTime <= 0) { 16482 continue; 16483 } 16484 long cputimeUsed = app.curCpuTime - app.lastCpuTime; 16485 if (DEBUG_POWER) { 16486 StringBuilder sb = new StringBuilder(128); 16487 sb.append("CPU for "); 16488 app.toShortString(sb); 16489 sb.append(": over "); 16490 TimeUtils.formatDuration(uptimeSince, sb); 16491 sb.append(" used "); 16492 TimeUtils.formatDuration(cputimeUsed, sb); 16493 sb.append(" ("); 16494 sb.append((cputimeUsed*100)/uptimeSince); 16495 sb.append("%)"); 16496 Slog.i(TAG_POWER, sb.toString()); 16497 } 16498 // If the process has used too much CPU over the last duration, the 16499 // user probably doesn't want this, so kill! 16500 if (doCpuKills && uptimeSince > 0) { 16501 // What is the limit for this process? 16502 int cpuLimit; 16503 long checkDur = curUptime - app.getWhenUnimportant(); 16504 if (checkDur <= mConstants.POWER_CHECK_INTERVAL) { 16505 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1; 16506 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*2) 16507 || app.setProcState <= ActivityManager.PROCESS_STATE_HOME) { 16508 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2; 16509 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*3)) { 16510 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3; 16511 } else { 16512 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4; 16513 } 16514 if (((cputimeUsed*100)/uptimeSince) >= cpuLimit) { 16515 synchronized (stats) { 16516 stats.reportExcessiveCpuLocked(app.info.uid, app.processName, 16517 uptimeSince, cputimeUsed); 16518 } 16519 app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince 16520 + " dur=" + checkDur + " limit=" + cpuLimit, true); 16521 app.baseProcessTracker.reportExcessiveCpu(app.pkgList.mPkgList); 16522 for (int ipkg = app.pkgList.size() - 1; ipkg >= 0; ipkg--) { 16523 ProcessStats.ProcessStateHolder holder = app.pkgList.valueAt(ipkg); 16524 StatsLog.write(StatsLog.EXCESSIVE_CPU_USAGE_REPORTED, 16525 app.info.uid, 16526 holder.state.getName(), 16527 holder.state.getPackage(), 16528 holder.appVersion); 16529 } 16530 } 16531 } 16532 app.lastCpuTime = app.curCpuTime; 16533 } 16534 } 16535 } 16536 isEphemeralLocked(int uid)16537 private boolean isEphemeralLocked(int uid) { 16538 String packages[] = mContext.getPackageManager().getPackagesForUid(uid); 16539 if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid 16540 return false; 16541 } 16542 return getPackageManagerInternalLocked().isPackageEphemeral(UserHandle.getUserId(uid), 16543 packages[0]); 16544 } 16545 16546 @VisibleForTesting enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)16547 final void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) { 16548 final UidRecord.ChangeItem pendingChange; 16549 if (uidRec == null || uidRec.pendingChange == null) { 16550 if (mPendingUidChanges.size() == 0) { 16551 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 16552 "*** Enqueueing dispatch uid changed!"); 16553 mUiHandler.obtainMessage(DISPATCH_UIDS_CHANGED_UI_MSG).sendToTarget(); 16554 } 16555 final int NA = mAvailUidChanges.size(); 16556 if (NA > 0) { 16557 pendingChange = mAvailUidChanges.remove(NA-1); 16558 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 16559 "Retrieving available item: " + pendingChange); 16560 } else { 16561 pendingChange = new UidRecord.ChangeItem(); 16562 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 16563 "Allocating new item: " + pendingChange); 16564 } 16565 if (uidRec != null) { 16566 uidRec.pendingChange = pendingChange; 16567 if ((change & UidRecord.CHANGE_GONE) != 0 && !uidRec.idle) { 16568 // If this uid is going away, and we haven't yet reported it is gone, 16569 // then do so now. 16570 change |= UidRecord.CHANGE_IDLE; 16571 } 16572 } else if (uid < 0) { 16573 throw new IllegalArgumentException("No UidRecord or uid"); 16574 } 16575 pendingChange.uidRecord = uidRec; 16576 pendingChange.uid = uidRec != null ? uidRec.uid : uid; 16577 mPendingUidChanges.add(pendingChange); 16578 } else { 16579 pendingChange = uidRec.pendingChange; 16580 // If there is no change in idle or active state, then keep whatever was pending. 16581 if ((change & (UidRecord.CHANGE_IDLE | UidRecord.CHANGE_ACTIVE)) == 0) { 16582 change |= (pendingChange.change & (UidRecord.CHANGE_IDLE 16583 | UidRecord.CHANGE_ACTIVE)); 16584 } 16585 // If there is no change in cached or uncached state, then keep whatever was pending. 16586 if ((change & (UidRecord.CHANGE_CACHED | UidRecord.CHANGE_UNCACHED)) == 0) { 16587 change |= (pendingChange.change & (UidRecord.CHANGE_CACHED 16588 | UidRecord.CHANGE_UNCACHED)); 16589 } 16590 // If this is a report of the UID being gone, then we shouldn't keep any previous 16591 // report of it being active or cached. (That is, a gone uid is never active, 16592 // and never cached.) 16593 if ((change & UidRecord.CHANGE_GONE) != 0) { 16594 change &= ~(UidRecord.CHANGE_ACTIVE | UidRecord.CHANGE_CACHED); 16595 if (!uidRec.idle) { 16596 // If this uid is going away, and we haven't yet reported it is gone, 16597 // then do so now. 16598 change |= UidRecord.CHANGE_IDLE; 16599 } 16600 } 16601 } 16602 pendingChange.change = change; 16603 pendingChange.processState = uidRec != null ? uidRec.setProcState : PROCESS_STATE_NONEXISTENT; 16604 pendingChange.ephemeral = uidRec != null ? uidRec.ephemeral : isEphemeralLocked(uid); 16605 pendingChange.procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0; 16606 if (uidRec != null) { 16607 uidRec.lastReportedChange = change; 16608 uidRec.updateLastDispatchedProcStateSeq(change); 16609 } 16610 16611 // Directly update the power manager, since we sit on top of it and it is critical 16612 // it be kept in sync (so wake locks will be held as soon as appropriate). 16613 if (mLocalPowerManager != null) { 16614 // TO DO: dispatch cached/uncached changes here, so we don't need to report 16615 // all proc state changes. 16616 if ((change & UidRecord.CHANGE_ACTIVE) != 0) { 16617 mLocalPowerManager.uidActive(pendingChange.uid); 16618 } 16619 if ((change & UidRecord.CHANGE_IDLE) != 0) { 16620 mLocalPowerManager.uidIdle(pendingChange.uid); 16621 } 16622 if ((change & UidRecord.CHANGE_GONE) != 0) { 16623 mLocalPowerManager.uidGone(pendingChange.uid); 16624 } else { 16625 mLocalPowerManager.updateUidProcState(pendingChange.uid, 16626 pendingChange.processState); 16627 } 16628 } 16629 } 16630 maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, String authority)16631 private void maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, 16632 String authority) { 16633 if (app == null) return; 16634 if (app.getCurProcState() <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { 16635 UserState userState = mUserController.getStartedUserState(app.userId); 16636 if (userState == null) return; 16637 final long now = SystemClock.elapsedRealtime(); 16638 Long lastReported = userState.mProviderLastReportedFg.get(authority); 16639 if (lastReported == null || lastReported < now - 60 * 1000L) { 16640 if (mSystemReady) { 16641 // Cannot touch the user stats if not system ready 16642 mUsageStatsService.reportContentProviderUsage( 16643 authority, providerPkgName, app.userId); 16644 } 16645 userState.mProviderLastReportedFg.put(authority, now); 16646 } 16647 } 16648 } 16649 setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now)16650 final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) { 16651 if (proc.thread != null && proc.baseProcessTracker != null) { 16652 proc.baseProcessTracker.setState( 16653 proc.getReportedProcState(), memFactor, now, proc.pkgList.mPkgList); 16654 } 16655 } 16656 16657 @GuardedBy("this") updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean oomAdj)16658 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 16659 int fgServiceTypes, boolean oomAdj) { 16660 16661 if (isForeground != proc.hasForegroundServices() 16662 || proc.getForegroundServiceTypes() != fgServiceTypes) { 16663 proc.setHasForegroundServices(isForeground, fgServiceTypes); 16664 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 16665 proc.info.uid); 16666 if (isForeground) { 16667 if (curProcs == null) { 16668 curProcs = new ArrayList<ProcessRecord>(); 16669 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 16670 } 16671 if (!curProcs.contains(proc)) { 16672 curProcs.add(proc); 16673 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 16674 proc.info.packageName, proc.info.uid); 16675 } 16676 } else { 16677 if (curProcs != null) { 16678 if (curProcs.remove(proc)) { 16679 mBatteryStatsService.noteEvent( 16680 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 16681 proc.info.packageName, proc.info.uid); 16682 if (curProcs.size() <= 0) { 16683 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 16684 } 16685 } 16686 } 16687 } 16688 16689 proc.setReportedForegroundServiceTypes(fgServiceTypes); 16690 ProcessChangeItem item = enqueueProcessChangeItemLocked(proc.pid, proc.info.uid); 16691 item.changes = ProcessChangeItem.CHANGE_FOREGROUND_SERVICES; 16692 item.foregroundServiceTypes = fgServiceTypes; 16693 16694 if (oomAdj) { 16695 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 16696 } 16697 } 16698 } 16699 16700 // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update 16701 // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities getTopAppLocked()16702 ProcessRecord getTopAppLocked() { 16703 final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null; 16704 final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null; 16705 String pkg; 16706 int uid; 16707 if (r != null) { 16708 pkg = r.processName; 16709 uid = r.info.uid; 16710 } else { 16711 pkg = null; 16712 uid = -1; 16713 } 16714 // Has the UID or resumed package name changed? 16715 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 16716 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 16717 16718 final long identity = Binder.clearCallingIdentity(); 16719 try { 16720 if (mCurResumedPackage != null) { 16721 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 16722 mCurResumedPackage, mCurResumedUid); 16723 } 16724 mCurResumedPackage = pkg; 16725 mCurResumedUid = uid; 16726 if (mCurResumedPackage != null) { 16727 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 16728 mCurResumedPackage, mCurResumedUid); 16729 } 16730 } finally { 16731 Binder.restoreCallingIdentity(identity); 16732 } 16733 16734 } 16735 return r; 16736 } 16737 16738 /** 16739 * Update OomAdj for a specific process. 16740 * @param app The process to update 16741 * @param oomAdjAll If it's ok to call updateOomAdjLocked() for all running apps 16742 * if necessary, or skip. 16743 * @param oomAdjReason 16744 * @return whether updateOomAdjLocked(app) was successful. 16745 */ 16746 @GuardedBy("this") updateOomAdjLocked(ProcessRecord app, boolean oomAdjAll, String oomAdjReason)16747 final boolean updateOomAdjLocked(ProcessRecord app, boolean oomAdjAll, 16748 String oomAdjReason) { 16749 return mOomAdjuster.updateOomAdjLocked(app, oomAdjAll, oomAdjReason); 16750 } 16751 16752 static final class ProcStatsRunnable implements Runnable { 16753 private final ActivityManagerService mService; 16754 private final ProcessStatsService mProcessStats; 16755 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)16756 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) { 16757 this.mService = service; 16758 this.mProcessStats = mProcessStats; 16759 } 16760 run()16761 @Override public void run() { 16762 synchronized (mService) { 16763 mProcessStats.writeStateAsyncLocked(); 16764 } 16765 } 16766 } 16767 16768 @GuardedBy("this") updateLowMemStateLocked(int numCached, int numEmpty, int numTrimming)16769 final boolean updateLowMemStateLocked(int numCached, int numEmpty, int numTrimming) { 16770 final int N = mProcessList.getLruSizeLocked(); 16771 final long now = SystemClock.uptimeMillis(); 16772 int memFactor; 16773 if (mLowMemDetector != null && mLowMemDetector.isAvailable()) { 16774 memFactor = mLowMemDetector.getMemFactor(); 16775 } else { 16776 // Now determine the memory trimming level of background processes. 16777 // Unfortunately we need to start at the back of the list to do this 16778 // properly. We only do this if the number of background apps we 16779 // are managing to keep around is less than half the maximum we desire; 16780 // if we are keeping a good number around, we'll let them use whatever 16781 // memory they want. 16782 if (numCached <= mConstants.CUR_TRIM_CACHED_PROCESSES 16783 && numEmpty <= mConstants.CUR_TRIM_EMPTY_PROCESSES) { 16784 final int numCachedAndEmpty = numCached + numEmpty; 16785 if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) { 16786 memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL; 16787 } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) { 16788 memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW; 16789 } else { 16790 memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE; 16791 } 16792 } else { 16793 memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 16794 } 16795 } 16796 // We always allow the memory level to go up (better). We only allow it to go 16797 // down if we are in a state where that is allowed, *and* the total number of processes 16798 // has gone down since last time. 16799 if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "oom: memFactor=" + memFactor 16800 + " last=" + mLastMemoryLevel + " allowLow=" + mAllowLowerMemLevel 16801 + " numProcs=" + mProcessList.getLruSizeLocked() + " last=" + mLastNumProcesses); 16802 if (memFactor > mLastMemoryLevel) { 16803 if (!mAllowLowerMemLevel || mProcessList.getLruSizeLocked() >= mLastNumProcesses) { 16804 memFactor = mLastMemoryLevel; 16805 if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "Keeping last mem factor!"); 16806 } 16807 } 16808 if (memFactor != mLastMemoryLevel) { 16809 EventLogTags.writeAmMemFactor(memFactor, mLastMemoryLevel); 16810 StatsLog.write(StatsLog.MEMORY_FACTOR_STATE_CHANGED, memFactor); 16811 } 16812 mLastMemoryLevel = memFactor; 16813 mLastNumProcesses = mProcessList.getLruSizeLocked(); 16814 boolean allChanged = mProcessStats.setMemFactorLocked( 16815 memFactor, mAtmInternal != null ? !mAtmInternal.isSleeping() : true, now); 16816 final int trackerMemFactor = mProcessStats.getMemFactorLocked(); 16817 if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) { 16818 if (mLowRamStartTime == 0) { 16819 mLowRamStartTime = now; 16820 } 16821 int step = 0; 16822 int fgTrimLevel; 16823 switch (memFactor) { 16824 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 16825 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL; 16826 break; 16827 case ProcessStats.ADJ_MEM_FACTOR_LOW: 16828 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW; 16829 break; 16830 default: 16831 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE; 16832 break; 16833 } 16834 int factor = numTrimming/3; 16835 int minFactor = 2; 16836 if (mAtmInternal.getHomeProcess() != null) minFactor++; 16837 if (mAtmInternal.getPreviousProcess() != null) minFactor++; 16838 if (factor < minFactor) factor = minFactor; 16839 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE; 16840 for (int i=N-1; i>=0; i--) { 16841 ProcessRecord app = mProcessList.mLruProcesses.get(i); 16842 if (allChanged || app.procStateChanged) { 16843 setProcessTrackerStateLocked(app, trackerMemFactor, now); 16844 app.procStateChanged = false; 16845 } 16846 if (app.getCurProcState() >= ActivityManager.PROCESS_STATE_HOME 16847 && !app.killedByAm) { 16848 if (app.trimMemoryLevel < curLevel && app.thread != null) { 16849 try { 16850 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 16851 "Trimming memory of " + app.processName + " to " + curLevel); 16852 app.thread.scheduleTrimMemory(curLevel); 16853 } catch (RemoteException e) { 16854 } 16855 } 16856 app.trimMemoryLevel = curLevel; 16857 step++; 16858 if (step >= factor) { 16859 step = 0; 16860 switch (curLevel) { 16861 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE: 16862 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE; 16863 break; 16864 case ComponentCallbacks2.TRIM_MEMORY_MODERATE: 16865 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 16866 break; 16867 } 16868 } 16869 } else if (app.getCurProcState() == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT 16870 && !app.killedByAm) { 16871 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND 16872 && app.thread != null) { 16873 try { 16874 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 16875 "Trimming memory of heavy-weight " + app.processName 16876 + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 16877 app.thread.scheduleTrimMemory( 16878 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 16879 } catch (RemoteException e) { 16880 } 16881 } 16882 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 16883 } else { 16884 if ((app.getCurProcState() >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 16885 || app.systemNoUi) && app.hasPendingUiClean()) { 16886 // If this application is now in the background and it 16887 // had done UI, then give it the special trim level to 16888 // have it free UI resources. 16889 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN; 16890 if (app.trimMemoryLevel < level && app.thread != null) { 16891 try { 16892 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 16893 "Trimming memory of bg-ui " + app.processName 16894 + " to " + level); 16895 app.thread.scheduleTrimMemory(level); 16896 } catch (RemoteException e) { 16897 } 16898 } 16899 app.setPendingUiClean(false); 16900 } 16901 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) { 16902 try { 16903 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 16904 "Trimming memory of fg " + app.processName 16905 + " to " + fgTrimLevel); 16906 app.thread.scheduleTrimMemory(fgTrimLevel); 16907 } catch (RemoteException e) { 16908 } 16909 } 16910 app.trimMemoryLevel = fgTrimLevel; 16911 } 16912 } 16913 } else { 16914 if (mLowRamStartTime != 0) { 16915 mLowRamTimeSinceLastIdle += now - mLowRamStartTime; 16916 mLowRamStartTime = 0; 16917 } 16918 for (int i=N-1; i>=0; i--) { 16919 ProcessRecord app = mProcessList.mLruProcesses.get(i); 16920 if (allChanged || app.procStateChanged) { 16921 setProcessTrackerStateLocked(app, trackerMemFactor, now); 16922 app.procStateChanged = false; 16923 } 16924 if ((app.getCurProcState() >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 16925 || app.systemNoUi) && app.hasPendingUiClean()) { 16926 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN 16927 && app.thread != null) { 16928 try { 16929 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 16930 "Trimming memory of ui hidden " + app.processName 16931 + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 16932 app.thread.scheduleTrimMemory( 16933 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 16934 } catch (RemoteException e) { 16935 } 16936 } 16937 app.setPendingUiClean(false); 16938 } 16939 app.trimMemoryLevel = 0; 16940 } 16941 } 16942 return allChanged; 16943 } 16944 16945 @GuardedBy("this") updateOomAdjLocked(String oomAdjReason)16946 final void updateOomAdjLocked(String oomAdjReason) { 16947 mOomAdjuster.updateOomAdjLocked(oomAdjReason); 16948 } 16949 16950 @Override makePackageIdle(String packageName, int userId)16951 public void makePackageIdle(String packageName, int userId) { 16952 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 16953 != PackageManager.PERMISSION_GRANTED) { 16954 String msg = "Permission Denial: makePackageIdle() from pid=" 16955 + Binder.getCallingPid() 16956 + ", uid=" + Binder.getCallingUid() 16957 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 16958 Slog.w(TAG, msg); 16959 throw new SecurityException(msg); 16960 } 16961 final int callingPid = Binder.getCallingPid(); 16962 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 16963 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null); 16964 long callingId = Binder.clearCallingIdentity(); 16965 synchronized(this) { 16966 try { 16967 IPackageManager pm = AppGlobals.getPackageManager(); 16968 int pkgUid = -1; 16969 try { 16970 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES 16971 | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM); 16972 } catch (RemoteException e) { 16973 } 16974 if (pkgUid == -1) { 16975 throw new IllegalArgumentException("Unknown package name " + packageName); 16976 } 16977 16978 if (mLocalPowerManager != null) { 16979 mLocalPowerManager.startUidChanges(); 16980 } 16981 final int appId = UserHandle.getAppId(pkgUid); 16982 final int N = mProcessList.mActiveUids.size(); 16983 for (int i = N - 1; i >= 0; i--) { 16984 final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i); 16985 final long bgTime = uidRec.lastBackgroundTime; 16986 if (bgTime > 0 && !uidRec.idle) { 16987 if (UserHandle.getAppId(uidRec.uid) == appId) { 16988 if (userId == UserHandle.USER_ALL || 16989 userId == UserHandle.getUserId(uidRec.uid)) { 16990 EventLogTags.writeAmUidIdle(uidRec.uid); 16991 uidRec.idle = true; 16992 uidRec.setIdle = true; 16993 Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uidRec.uid) 16994 + " from package " + packageName + " user " + userId); 16995 doStopUidLocked(uidRec.uid, uidRec); 16996 } 16997 } 16998 } 16999 } 17000 } finally { 17001 if (mLocalPowerManager != null) { 17002 mLocalPowerManager.finishUidChanges(); 17003 } 17004 Binder.restoreCallingIdentity(callingId); 17005 } 17006 } 17007 } 17008 17009 /** Make the currently active UIDs idle after a certain grace period. */ idleUids()17010 final void idleUids() { 17011 synchronized (this) { 17012 mOomAdjuster.idleUidsLocked(); 17013 } 17014 } 17015 17016 /** 17017 * Checks if any uid is coming from background to foreground or vice versa and if so, increments 17018 * the {@link UidRecord#curProcStateSeq} corresponding to that uid using global seq counter 17019 * {@link ProcessList#mProcStateSeqCounter} and notifies the app if it needs to block. 17020 */ 17021 @VisibleForTesting 17022 @GuardedBy("this") incrementProcStateSeqAndNotifyAppsLocked()17023 void incrementProcStateSeqAndNotifyAppsLocked() { 17024 if (mWaitForNetworkTimeoutMs <= 0) { 17025 return; 17026 } 17027 // Used for identifying which uids need to block for network. 17028 ArrayList<Integer> blockingUids = null; 17029 for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; --i) { 17030 final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i); 17031 // If the network is not restricted for uid, then nothing to do here. 17032 if (!mInjector.isNetworkRestrictedForUid(uidRec.uid)) { 17033 continue; 17034 } 17035 if (!UserHandle.isApp(uidRec.uid) || !uidRec.hasInternetPermission) { 17036 continue; 17037 } 17038 // If process state is not changed, then there's nothing to do. 17039 if (uidRec.setProcState == uidRec.getCurProcState()) { 17040 continue; 17041 } 17042 final int blockState = getBlockStateForUid(uidRec); 17043 // No need to inform the app when the blockState is NETWORK_STATE_NO_CHANGE as 17044 // there's nothing the app needs to do in this scenario. 17045 if (blockState == NETWORK_STATE_NO_CHANGE) { 17046 continue; 17047 } 17048 synchronized (uidRec.networkStateLock) { 17049 uidRec.curProcStateSeq = ++mProcessList.mProcStateSeqCounter; // TODO: use method 17050 if (blockState == NETWORK_STATE_BLOCK) { 17051 if (blockingUids == null) { 17052 blockingUids = new ArrayList<>(); 17053 } 17054 blockingUids.add(uidRec.uid); 17055 } else { 17056 if (DEBUG_NETWORK) { 17057 Slog.d(TAG_NETWORK, "uid going to background, notifying all blocking" 17058 + " threads for uid: " + uidRec); 17059 } 17060 if (uidRec.waitingForNetwork) { 17061 uidRec.networkStateLock.notifyAll(); 17062 } 17063 } 17064 } 17065 } 17066 17067 // There are no uids that need to block, so nothing more to do. 17068 if (blockingUids == null) { 17069 return; 17070 } 17071 17072 for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; --i) { 17073 final ProcessRecord app = mProcessList.mLruProcesses.get(i); 17074 if (!blockingUids.contains(app.uid)) { 17075 continue; 17076 } 17077 if (!app.killedByAm && app.thread != null) { 17078 final UidRecord uidRec = mProcessList.getUidRecordLocked(app.uid); 17079 try { 17080 if (DEBUG_NETWORK) { 17081 Slog.d(TAG_NETWORK, "Informing app thread that it needs to block: " 17082 + uidRec); 17083 } 17084 if (uidRec != null) { 17085 app.thread.setNetworkBlockSeq(uidRec.curProcStateSeq); 17086 } 17087 } catch (RemoteException ignored) { 17088 } 17089 } 17090 } 17091 } 17092 17093 /** 17094 * Checks if the uid is coming from background to foreground or vice versa and returns 17095 * appropriate block state based on this. 17096 * 17097 * @return blockState based on whether the uid is coming from background to foreground or 17098 * vice versa. If bg->fg or fg->bg, then {@link #NETWORK_STATE_BLOCK} or 17099 * {@link #NETWORK_STATE_UNBLOCK} respectively, otherwise 17100 * {@link #NETWORK_STATE_NO_CHANGE}. 17101 */ 17102 @VisibleForTesting getBlockStateForUid(UidRecord uidRec)17103 int getBlockStateForUid(UidRecord uidRec) { 17104 // Denotes whether uid's process state is currently allowed network access. 17105 final boolean isAllowed = 17106 isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.getCurProcState()) 17107 || isProcStateAllowedWhileOnRestrictBackground(uidRec.getCurProcState()); 17108 // Denotes whether uid's process state was previously allowed network access. 17109 final boolean wasAllowed = isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.setProcState) 17110 || isProcStateAllowedWhileOnRestrictBackground(uidRec.setProcState); 17111 17112 // When the uid is coming to foreground, AMS should inform the app thread that it should 17113 // block for the network rules to get updated before launching an activity. 17114 if (!wasAllowed && isAllowed) { 17115 return NETWORK_STATE_BLOCK; 17116 } 17117 // When the uid is going to background, AMS should inform the app thread that if an 17118 // activity launch is blocked for the network rules to get updated, it should be unblocked. 17119 if (wasAllowed && !isAllowed) { 17120 return NETWORK_STATE_UNBLOCK; 17121 } 17122 return NETWORK_STATE_NO_CHANGE; 17123 } 17124 runInBackgroundDisabled(int uid)17125 final void runInBackgroundDisabled(int uid) { 17126 synchronized (this) { 17127 UidRecord uidRec = mProcessList.getUidRecordLocked(uid); 17128 if (uidRec != null) { 17129 // This uid is actually running... should it be considered background now? 17130 if (uidRec.idle) { 17131 doStopUidLocked(uidRec.uid, uidRec); 17132 } 17133 } else { 17134 // This uid isn't actually running... still send a report about it being "stopped". 17135 doStopUidLocked(uid, null); 17136 } 17137 } 17138 } 17139 17140 @GuardedBy("this") doStopUidLocked(int uid, final UidRecord uidRec)17141 final void doStopUidLocked(int uid, final UidRecord uidRec) { 17142 mServices.stopInBackgroundLocked(uid); 17143 enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE); 17144 } 17145 17146 /** 17147 * Whitelists {@code targetUid} to temporarily bypass Power Save mode. 17148 */ 17149 @GuardedBy("this") tempWhitelistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, String tag)17150 void tempWhitelistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, 17151 long duration, String tag) { 17152 if (DEBUG_WHITELISTS) { 17153 Slog.d(TAG, "tempWhitelistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", " 17154 + targetUid + ", " + duration + ")"); 17155 } 17156 17157 synchronized (mPidsSelfLocked) { 17158 final ProcessRecord pr = mPidsSelfLocked.get(callerPid); 17159 if (pr == null) { 17160 Slog.w(TAG, "tempWhitelistForPendingIntentLocked() no ProcessRecord for pid " 17161 + callerPid); 17162 return; 17163 } 17164 if (!pr.whitelistManager) { 17165 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid) 17166 != PackageManager.PERMISSION_GRANTED) { 17167 if (DEBUG_WHITELISTS) { 17168 Slog.d(TAG, "tempWhitelistForPendingIntentLocked() for target " + targetUid 17169 + ": pid " + callerPid + " is not allowed"); 17170 } 17171 return; 17172 } 17173 } 17174 } 17175 17176 tempWhitelistUidLocked(targetUid, duration, tag); 17177 } 17178 17179 /** 17180 * Whitelists {@code targetUid} to temporarily bypass Power Save mode. 17181 */ 17182 @GuardedBy("this") tempWhitelistUidLocked(int targetUid, long duration, String tag)17183 void tempWhitelistUidLocked(int targetUid, long duration, String tag) { 17184 mPendingTempWhitelist.put(targetUid, new PendingTempWhitelist(targetUid, duration, tag)); 17185 setUidTempWhitelistStateLocked(targetUid, true); 17186 mUiHandler.obtainMessage(PUSH_TEMP_WHITELIST_UI_MSG).sendToTarget(); 17187 } 17188 pushTempWhitelist()17189 void pushTempWhitelist() { 17190 final int N; 17191 final PendingTempWhitelist[] list; 17192 17193 // First copy out the pending changes... we need to leave them in the map for now, 17194 // in case someone needs to check what is coming up while we don't have the lock held. 17195 synchronized(this) { 17196 N = mPendingTempWhitelist.size(); 17197 list = new PendingTempWhitelist[N]; 17198 for (int i = 0; i < N; i++) { 17199 list[i] = mPendingTempWhitelist.valueAt(i); 17200 } 17201 } 17202 17203 // Now safely dispatch changes to device idle controller. 17204 for (int i = 0; i < N; i++) { 17205 PendingTempWhitelist ptw = list[i]; 17206 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid, 17207 ptw.duration, true, ptw.tag); 17208 } 17209 17210 // And now we can safely remove them from the map. 17211 synchronized(this) { 17212 for (int i = 0; i < N; i++) { 17213 PendingTempWhitelist ptw = list[i]; 17214 int index = mPendingTempWhitelist.indexOfKey(ptw.targetUid); 17215 if (index >= 0 && mPendingTempWhitelist.valueAt(index) == ptw) { 17216 mPendingTempWhitelist.removeAt(index); 17217 } 17218 } 17219 } 17220 } 17221 17222 @GuardedBy("this") setAppIdTempWhitelistStateLocked(int appId, boolean onWhitelist)17223 final void setAppIdTempWhitelistStateLocked(int appId, boolean onWhitelist) { 17224 mOomAdjuster.setAppIdTempWhitelistStateLocked(appId, onWhitelist); 17225 } 17226 17227 @GuardedBy("this") setUidTempWhitelistStateLocked(int uid, boolean onWhitelist)17228 final void setUidTempWhitelistStateLocked(int uid, boolean onWhitelist) { 17229 mOomAdjuster.setUidTempWhitelistStateLocked(uid, onWhitelist); 17230 } 17231 trimApplications(String oomAdjReason)17232 final void trimApplications(String oomAdjReason) { 17233 synchronized (this) { 17234 trimApplicationsLocked(oomAdjReason); 17235 } 17236 } 17237 17238 @GuardedBy("this") trimApplicationsLocked(String oomAdjReason)17239 final void trimApplicationsLocked(String oomAdjReason) { 17240 // First remove any unused application processes whose package 17241 // has been removed. 17242 for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) { 17243 final ProcessRecord app = mProcessList.mRemovedProcesses.get(i); 17244 if (!app.hasActivitiesOrRecentTasks() 17245 && app.curReceivers.isEmpty() && app.services.size() == 0) { 17246 Slog.i( 17247 TAG, "Exiting empty application process " 17248 + app.toShortString() + " (" 17249 + (app.thread != null ? app.thread.asBinder() : null) 17250 + ")\n"); 17251 if (app.pid > 0 && app.pid != MY_PID) { 17252 app.kill("empty", false); 17253 } else if (app.thread != null) { 17254 try { 17255 app.thread.scheduleExit(); 17256 } catch (Exception e) { 17257 // Ignore exceptions. 17258 } 17259 } 17260 cleanUpApplicationRecordLocked(app, false, true, -1, false /*replacingPid*/); 17261 mProcessList.mRemovedProcesses.remove(i); 17262 17263 if (app.isPersistent()) { 17264 addAppLocked(app.info, null, false, null /* ABI override */); 17265 } 17266 } 17267 } 17268 17269 // Now update the oom adj for all processes. Don't skip this, since other callers 17270 // might be depending on it. 17271 updateOomAdjLocked(oomAdjReason); 17272 } 17273 17274 /** This method sends the specified signal to each of the persistent apps */ signalPersistentProcesses(int sig)17275 public void signalPersistentProcesses(int sig) throws RemoteException { 17276 if (sig != SIGNAL_USR1) { 17277 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 17278 } 17279 17280 synchronized (this) { 17281 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 17282 != PackageManager.PERMISSION_GRANTED) { 17283 throw new SecurityException("Requires permission " 17284 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 17285 } 17286 17287 for (int i = mProcessList.mLruProcesses.size() - 1 ; i >= 0 ; i--) { 17288 ProcessRecord r = mProcessList.mLruProcesses.get(i); 17289 if (r.thread != null && r.isPersistent()) { 17290 sendSignal(r.pid, sig); 17291 } 17292 } 17293 } 17294 } 17295 stopProfilerLocked(ProcessRecord proc, int profileType)17296 private void stopProfilerLocked(ProcessRecord proc, int profileType) { 17297 if (proc == null || proc == mProfileData.getProfileProc()) { 17298 proc = mProfileData.getProfileProc(); 17299 profileType = mProfileType; 17300 clearProfilerLocked(); 17301 } 17302 if (proc == null) { 17303 return; 17304 } 17305 try { 17306 proc.thread.profilerControl(false, null, profileType); 17307 } catch (RemoteException e) { 17308 throw new IllegalStateException("Process disappeared"); 17309 } 17310 } 17311 clearProfilerLocked()17312 void clearProfilerLocked() { 17313 if (mProfileData.getProfilerInfo() != null 17314 && mProfileData.getProfilerInfo().profileFd != null) { 17315 try { 17316 mProfileData.getProfilerInfo().profileFd.close(); 17317 } catch (IOException e) { 17318 } 17319 } 17320 mProfileData.setProfileApp(null); 17321 mProfileData.setProfileProc(null); 17322 mProfileData.setProfilerInfo(null); 17323 } 17324 profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)17325 public boolean profileControl(String process, int userId, boolean start, 17326 ProfilerInfo profilerInfo, int profileType) throws RemoteException { 17327 17328 try { 17329 synchronized (this) { 17330 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 17331 // its own permission. 17332 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17333 != PackageManager.PERMISSION_GRANTED) { 17334 throw new SecurityException("Requires permission " 17335 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17336 } 17337 17338 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) { 17339 throw new IllegalArgumentException("null profile info or fd"); 17340 } 17341 17342 ProcessRecord proc = null; 17343 if (process != null) { 17344 proc = findProcessLocked(process, userId, "profileControl"); 17345 } 17346 17347 if (start && (proc == null || proc.thread == null)) { 17348 throw new IllegalArgumentException("Unknown process: " + process); 17349 } 17350 17351 if (start) { 17352 stopProfilerLocked(null, 0); 17353 setProfileApp(proc.info, proc.processName, profilerInfo); 17354 mProfileData.setProfileProc(proc); 17355 mProfileType = profileType; 17356 ParcelFileDescriptor fd = profilerInfo.profileFd; 17357 try { 17358 fd = fd.dup(); 17359 } catch (IOException e) { 17360 fd = null; 17361 } 17362 profilerInfo.profileFd = fd; 17363 proc.thread.profilerControl(start, profilerInfo, profileType); 17364 fd = null; 17365 try { 17366 mProfileData.getProfilerInfo().profileFd.close(); 17367 } catch (IOException e) { 17368 } 17369 mProfileData.getProfilerInfo().profileFd = null; 17370 17371 if (proc.pid == MY_PID) { 17372 // When profiling the system server itself, avoid closing the file 17373 // descriptor, as profilerControl will not create a copy. 17374 // Note: it is also not correct to just set profileFd to null, as the 17375 // whole ProfilerInfo instance is passed down! 17376 profilerInfo = null; 17377 } 17378 } else { 17379 stopProfilerLocked(proc, profileType); 17380 if (profilerInfo != null && profilerInfo.profileFd != null) { 17381 try { 17382 profilerInfo.profileFd.close(); 17383 } catch (IOException e) { 17384 } 17385 } 17386 } 17387 17388 return true; 17389 } 17390 } catch (RemoteException e) { 17391 throw new IllegalStateException("Process disappeared"); 17392 } finally { 17393 if (profilerInfo != null && profilerInfo.profileFd != null) { 17394 try { 17395 profilerInfo.profileFd.close(); 17396 } catch (IOException e) { 17397 } 17398 } 17399 } 17400 } 17401 findProcessLocked(String process, int userId, String callName)17402 private ProcessRecord findProcessLocked(String process, int userId, String callName) { 17403 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 17404 userId, true, ALLOW_FULL_ONLY, callName, null); 17405 ProcessRecord proc = null; 17406 try { 17407 int pid = Integer.parseInt(process); 17408 synchronized (mPidsSelfLocked) { 17409 proc = mPidsSelfLocked.get(pid); 17410 } 17411 } catch (NumberFormatException e) { 17412 } 17413 17414 if (proc == null) { 17415 ArrayMap<String, SparseArray<ProcessRecord>> all 17416 = mProcessList.mProcessNames.getMap(); 17417 SparseArray<ProcessRecord> procs = all.get(process); 17418 if (procs != null && procs.size() > 0) { 17419 proc = procs.valueAt(0); 17420 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 17421 for (int i=1; i<procs.size(); i++) { 17422 ProcessRecord thisProc = procs.valueAt(i); 17423 if (thisProc.userId == userId) { 17424 proc = thisProc; 17425 break; 17426 } 17427 } 17428 } 17429 } 17430 } 17431 17432 return proc; 17433 } 17434 17435 @Override dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)17436 public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, 17437 boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) { 17438 17439 try { 17440 synchronized (this) { 17441 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 17442 // its own permission (same as profileControl). 17443 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17444 != PackageManager.PERMISSION_GRANTED) { 17445 throw new SecurityException("Requires permission " 17446 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17447 } 17448 17449 if (fd == null) { 17450 throw new IllegalArgumentException("null fd"); 17451 } 17452 17453 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap"); 17454 if (proc == null || proc.thread == null) { 17455 throw new IllegalArgumentException("Unknown process: " + process); 17456 } 17457 17458 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 17459 if (!isDebuggable) { 17460 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 17461 throw new SecurityException("Process not debuggable: " + proc); 17462 } 17463 } 17464 17465 proc.thread.dumpHeap(managed, mallocInfo, runGc, path, fd, finishCallback); 17466 fd = null; 17467 return true; 17468 } 17469 } catch (RemoteException e) { 17470 throw new IllegalStateException("Process disappeared"); 17471 } finally { 17472 if (fd != null) { 17473 try { 17474 fd.close(); 17475 } catch (IOException e) { 17476 } 17477 } 17478 } 17479 } 17480 17481 @Override setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)17482 public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, 17483 String reportPackage) { 17484 if (processName != null) { 17485 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 17486 "setDumpHeapDebugLimit()"); 17487 } else { 17488 synchronized (mPidsSelfLocked) { 17489 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid()); 17490 if (proc == null) { 17491 throw new SecurityException("No process found for calling pid " 17492 + Binder.getCallingPid()); 17493 } 17494 if (!Build.IS_DEBUGGABLE 17495 && (proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 17496 throw new SecurityException("Not running a debuggable build"); 17497 } 17498 processName = proc.processName; 17499 uid = proc.uid; 17500 if (reportPackage != null && !proc.pkgList.containsKey(reportPackage)) { 17501 throw new SecurityException("Package " + reportPackage + " is not running in " 17502 + proc); 17503 } 17504 } 17505 } 17506 synchronized (this) { 17507 if (maxMemSize > 0) { 17508 mMemWatchProcesses.put(processName, uid, new Pair(maxMemSize, reportPackage)); 17509 } else { 17510 if (uid != 0) { 17511 mMemWatchProcesses.remove(processName, uid); 17512 } else { 17513 mMemWatchProcesses.getMap().remove(processName); 17514 } 17515 } 17516 } 17517 } 17518 17519 @Override dumpHeapFinished(String path)17520 public void dumpHeapFinished(String path) { 17521 synchronized (this) { 17522 if (Binder.getCallingPid() != mMemWatchDumpPid) { 17523 Slog.w(TAG, "dumpHeapFinished: Calling pid " + Binder.getCallingPid() 17524 + " does not match last pid " + mMemWatchDumpPid); 17525 return; 17526 } 17527 if (mMemWatchDumpFile == null || !mMemWatchDumpFile.equals(path)) { 17528 Slog.w(TAG, "dumpHeapFinished: Calling path " + path 17529 + " does not match last path " + mMemWatchDumpFile); 17530 return; 17531 } 17532 if (DEBUG_PSS) Slog.d(TAG_PSS, "Dump heap finished for " + path); 17533 mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG); 17534 17535 // Forced gc to clean up the remnant hprof fd. 17536 Runtime.getRuntime().gc(); 17537 } 17538 } 17539 17540 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ monitor()17541 public void monitor() { 17542 synchronized (this) { } 17543 } 17544 onCoreSettingsChange(Bundle settings)17545 void onCoreSettingsChange(Bundle settings) { 17546 synchronized (this) { 17547 mProcessList.updateCoreSettingsLocked(settings); 17548 } 17549 } 17550 17551 // Multi-user methods 17552 17553 /** 17554 * Start user, if its not already running, but don't bring it to foreground. 17555 */ 17556 @Override startUserInBackground(final int userId)17557 public boolean startUserInBackground(final int userId) { 17558 return startUserInBackgroundWithListener(userId, null); 17559 } 17560 17561 @Override startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17562 public boolean startUserInBackgroundWithListener(final int userId, 17563 @Nullable IProgressListener unlockListener) { 17564 return mUserController.startUser(userId, /* foreground */ false, unlockListener); 17565 } 17566 17567 @Override startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17568 public boolean startUserInForegroundWithListener(final int userId, 17569 @Nullable IProgressListener unlockListener) { 17570 // Permission check done inside UserController. 17571 return mUserController.startUser(userId, /* foreground */ true, unlockListener); 17572 } 17573 17574 @Override unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener)17575 public boolean unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener) { 17576 return mUserController.unlockUser(userId, token, secret, listener); 17577 } 17578 17579 @Override switchUser(final int targetUserId)17580 public boolean switchUser(final int targetUserId) { 17581 return mUserController.switchUser(targetUserId); 17582 } 17583 17584 @Override stopUser(final int userId, boolean force, final IStopUserCallback callback)17585 public int stopUser(final int userId, boolean force, final IStopUserCallback callback) { 17586 return mUserController.stopUser(userId, force, callback, null /* keyEvictedCallback */); 17587 } 17588 17589 @Override getCurrentUser()17590 public UserInfo getCurrentUser() { 17591 return mUserController.getCurrentUser(); 17592 } 17593 getStartedUserState(int userId)17594 String getStartedUserState(int userId) { 17595 final UserState userState = mUserController.getStartedUserState(userId); 17596 return UserState.stateToString(userState.state); 17597 } 17598 17599 @Override isUserRunning(int userId, int flags)17600 public boolean isUserRunning(int userId, int flags) { 17601 if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId()) 17602 && checkCallingPermission(INTERACT_ACROSS_USERS) 17603 != PackageManager.PERMISSION_GRANTED) { 17604 String msg = "Permission Denial: isUserRunning() from pid=" 17605 + Binder.getCallingPid() 17606 + ", uid=" + Binder.getCallingUid() 17607 + " requires " + INTERACT_ACROSS_USERS; 17608 Slog.w(TAG, msg); 17609 throw new SecurityException(msg); 17610 } 17611 return mUserController.isUserRunning(userId, flags); 17612 } 17613 17614 @Override getRunningUserIds()17615 public int[] getRunningUserIds() { 17616 if (checkCallingPermission(INTERACT_ACROSS_USERS) 17617 != PackageManager.PERMISSION_GRANTED) { 17618 String msg = "Permission Denial: isUserRunning() from pid=" 17619 + Binder.getCallingPid() 17620 + ", uid=" + Binder.getCallingUid() 17621 + " requires " + INTERACT_ACROSS_USERS; 17622 Slog.w(TAG, msg); 17623 throw new SecurityException(msg); 17624 } 17625 return mUserController.getStartedUserArray(); 17626 } 17627 17628 @Override registerUserSwitchObserver(IUserSwitchObserver observer, String name)17629 public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) { 17630 mUserController.registerUserSwitchObserver(observer, name); 17631 } 17632 17633 @Override unregisterUserSwitchObserver(IUserSwitchObserver observer)17634 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 17635 mUserController.unregisterUserSwitchObserver(observer); 17636 } 17637 getAppInfoForUser(ApplicationInfo info, int userId)17638 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 17639 if (info == null) return null; 17640 ApplicationInfo newInfo = new ApplicationInfo(info); 17641 newInfo.initForUser(userId); 17642 return newInfo; 17643 } 17644 isUserStopped(int userId)17645 public boolean isUserStopped(int userId) { 17646 return mUserController.getStartedUserState(userId) == null; 17647 } 17648 getActivityInfoForUser(ActivityInfo aInfo, int userId)17649 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 17650 if (aInfo == null 17651 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 17652 return aInfo; 17653 } 17654 17655 ActivityInfo info = new ActivityInfo(aInfo); 17656 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 17657 return info; 17658 } 17659 processSanityChecksLocked(ProcessRecord process)17660 private boolean processSanityChecksLocked(ProcessRecord process) { 17661 if (process == null || process.thread == null) { 17662 return false; 17663 } 17664 17665 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 17666 if (!isDebuggable) { 17667 if ((process.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 17668 return false; 17669 } 17670 } 17671 17672 return true; 17673 } 17674 startBinderTracking()17675 public boolean startBinderTracking() throws RemoteException { 17676 synchronized (this) { 17677 mBinderTransactionTrackingEnabled = true; 17678 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 17679 // permission (same as profileControl). 17680 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17681 != PackageManager.PERMISSION_GRANTED) { 17682 throw new SecurityException("Requires permission " 17683 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17684 } 17685 17686 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) { 17687 ProcessRecord process = mProcessList.mLruProcesses.get(i); 17688 if (!processSanityChecksLocked(process)) { 17689 continue; 17690 } 17691 try { 17692 process.thread.startBinderTracking(); 17693 } catch (RemoteException e) { 17694 Log.v(TAG, "Process disappared"); 17695 } 17696 } 17697 return true; 17698 } 17699 } 17700 stopBinderTrackingAndDump(ParcelFileDescriptor fd)17701 public boolean stopBinderTrackingAndDump(ParcelFileDescriptor fd) throws RemoteException { 17702 try { 17703 synchronized (this) { 17704 mBinderTransactionTrackingEnabled = false; 17705 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 17706 // permission (same as profileControl). 17707 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17708 != PackageManager.PERMISSION_GRANTED) { 17709 throw new SecurityException("Requires permission " 17710 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17711 } 17712 17713 if (fd == null) { 17714 throw new IllegalArgumentException("null fd"); 17715 } 17716 17717 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor())); 17718 pw.println("Binder transaction traces for all processes.\n"); 17719 for (ProcessRecord process : mProcessList.mLruProcesses) { 17720 if (!processSanityChecksLocked(process)) { 17721 continue; 17722 } 17723 17724 pw.println("Traces for process: " + process.processName); 17725 pw.flush(); 17726 try { 17727 TransferPipe tp = new TransferPipe(); 17728 try { 17729 process.thread.stopBinderTrackingAndDump(tp.getWriteFd()); 17730 tp.go(fd.getFileDescriptor()); 17731 } finally { 17732 tp.kill(); 17733 } 17734 } catch (IOException e) { 17735 pw.println("Failure while dumping IPC traces from " + process + 17736 ". Exception: " + e); 17737 pw.flush(); 17738 } catch (RemoteException e) { 17739 pw.println("Got a RemoteException while dumping IPC traces from " + 17740 process + ". Exception: " + e); 17741 pw.flush(); 17742 } 17743 } 17744 fd = null; 17745 return true; 17746 } 17747 } finally { 17748 if (fd != null) { 17749 try { 17750 fd.close(); 17751 } catch (IOException e) { 17752 } 17753 } 17754 } 17755 } 17756 17757 @VisibleForTesting 17758 public final class LocalService extends ActivityManagerInternal { 17759 @Override checkContentProviderAccess(String authority, int userId)17760 public String checkContentProviderAccess(String authority, int userId) { 17761 return ActivityManagerService.this.checkContentProviderAccess(authority, userId); 17762 } 17763 17764 @Override onWakefulnessChanged(int wakefulness)17765 public void onWakefulnessChanged(int wakefulness) { 17766 ActivityManagerService.this.onWakefulnessChanged(wakefulness); 17767 } 17768 17769 @Override startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)17770 public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 17771 String processName, String abiOverride, int uid, Runnable crashHandler) { 17772 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 17773 processName, abiOverride, uid, crashHandler); 17774 } 17775 17776 @Override killForegroundAppsForUser(int userHandle)17777 public void killForegroundAppsForUser(int userHandle) { 17778 synchronized (ActivityManagerService.this) { 17779 final ArrayList<ProcessRecord> procs = new ArrayList<>(); 17780 final int NP = mProcessList.mProcessNames.getMap().size(); 17781 for (int ip = 0; ip < NP; ip++) { 17782 final SparseArray<ProcessRecord> apps = 17783 mProcessList.mProcessNames.getMap().valueAt(ip); 17784 final int NA = apps.size(); 17785 for (int ia = 0; ia < NA; ia++) { 17786 final ProcessRecord app = apps.valueAt(ia); 17787 if (app.isPersistent()) { 17788 // We don't kill persistent processes. 17789 continue; 17790 } 17791 if (app.removed 17792 || (app.userId == userHandle && app.hasForegroundActivities())) { 17793 procs.add(app); 17794 } 17795 } 17796 } 17797 17798 final int N = procs.size(); 17799 for (int i = 0; i < N; i++) { 17800 mProcessList.removeProcessLocked(procs.get(i), false, true, "kill all fg"); 17801 } 17802 } 17803 } 17804 17805 @Override setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken, long duration)17806 public void setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken, 17807 long duration) { 17808 mPendingIntentController.setPendingIntentWhitelistDuration(target, whitelistToken, 17809 duration); 17810 } 17811 17812 @Override setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken, int flags)17813 public void setPendingIntentAllowBgActivityStarts(IIntentSender target, 17814 IBinder whitelistToken, int flags) { 17815 if (!(target instanceof PendingIntentRecord)) { 17816 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():" 17817 + " not a PendingIntentRecord: " + target); 17818 return; 17819 } 17820 synchronized (ActivityManagerService.this) { 17821 ((PendingIntentRecord) target).setAllowBgActivityStarts(whitelistToken, flags); 17822 } 17823 } 17824 17825 @Override clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken)17826 public void clearPendingIntentAllowBgActivityStarts(IIntentSender target, 17827 IBinder whitelistToken) { 17828 if (!(target instanceof PendingIntentRecord)) { 17829 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():" 17830 + " not a PendingIntentRecord: " + target); 17831 return; 17832 } 17833 synchronized (ActivityManagerService.this) { 17834 ((PendingIntentRecord) target).clearAllowBgActivityStarts(whitelistToken); 17835 } 17836 } 17837 17838 @Override setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids)17839 public void setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids) { 17840 synchronized (ActivityManagerService.this) { 17841 mDeviceIdleWhitelist = allAppids; 17842 mDeviceIdleExceptIdleWhitelist = exceptIdleAppids; 17843 } 17844 } 17845 17846 @Override updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding)17847 public void updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding) { 17848 synchronized (ActivityManagerService.this) { 17849 mDeviceIdleTempWhitelist = appids; 17850 setAppIdTempWhitelistStateLocked(changingAppId, adding); 17851 } 17852 } 17853 17854 @Override getUidProcessState(int uid)17855 public int getUidProcessState(int uid) { 17856 return getUidState(uid); 17857 } 17858 17859 @Override isSystemReady()17860 public boolean isSystemReady() { 17861 // no need to synchronize(this) just to read & return the value 17862 return mSystemReady; 17863 } 17864 17865 /** 17866 * Sets if the given pid has an overlay UI or not. 17867 * 17868 * @param pid The pid we are setting overlay UI for. 17869 * @param hasOverlayUi True if the process has overlay UI. 17870 * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY 17871 */ 17872 @Override setHasOverlayUi(int pid, boolean hasOverlayUi)17873 public void setHasOverlayUi(int pid, boolean hasOverlayUi) { 17874 synchronized (ActivityManagerService.this) { 17875 final ProcessRecord pr; 17876 synchronized (mPidsSelfLocked) { 17877 pr = mPidsSelfLocked.get(pid); 17878 if (pr == null) { 17879 Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid); 17880 return; 17881 } 17882 } 17883 if (pr.hasOverlayUi() == hasOverlayUi) { 17884 return; 17885 } 17886 pr.setHasOverlayUi(hasOverlayUi); 17887 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid); 17888 updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 17889 } 17890 } 17891 17892 /** 17893 * Called after the network policy rules are updated by 17894 * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid} 17895 * and {@param procStateSeq}. 17896 */ 17897 @Override notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)17898 public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) { 17899 if (DEBUG_NETWORK) { 17900 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: " 17901 + uid + " seq: " + procStateSeq); 17902 } 17903 UidRecord record; 17904 synchronized (ActivityManagerService.this) { 17905 record = mProcessList.getUidRecordLocked(uid); 17906 if (record == null) { 17907 if (DEBUG_NETWORK) { 17908 Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid 17909 + " procStateSeq: " + procStateSeq); 17910 } 17911 return; 17912 } 17913 } 17914 synchronized (record.networkStateLock) { 17915 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 17916 if (DEBUG_NETWORK) { 17917 Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already" 17918 + " been handled for uid: " + uid); 17919 } 17920 return; 17921 } 17922 record.lastNetworkUpdatedProcStateSeq = procStateSeq; 17923 if (record.curProcStateSeq > procStateSeq) { 17924 if (DEBUG_NETWORK) { 17925 Slog.d(TAG_NETWORK, "No need to handle older seq no., Uid: " + uid 17926 + ", curProcstateSeq: " + record.curProcStateSeq 17927 + ", procStateSeq: " + procStateSeq); 17928 } 17929 return; 17930 } 17931 if (record.waitingForNetwork) { 17932 if (DEBUG_NETWORK) { 17933 Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid 17934 + ", procStateSeq: " + procStateSeq); 17935 } 17936 record.networkStateLock.notifyAll(); 17937 } 17938 } 17939 } 17940 17941 @Override isRuntimeRestarted()17942 public boolean isRuntimeRestarted() { 17943 return mSystemServiceManager.isRuntimeRestarted(); 17944 } 17945 17946 @Override canStartMoreUsers()17947 public boolean canStartMoreUsers() { 17948 return mUserController.canStartMoreUsers(); 17949 } 17950 17951 @Override setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)17952 public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) { 17953 mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage); 17954 } 17955 17956 @Override setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)17957 public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) { 17958 mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage); 17959 } 17960 17961 @Override getMaxRunningUsers()17962 public int getMaxRunningUsers() { 17963 return mUserController.mMaxRunningUsers; 17964 } 17965 17966 @Override isUidActive(int uid)17967 public boolean isUidActive(int uid) { 17968 synchronized (ActivityManagerService.this) { 17969 return isUidActiveLocked(uid); 17970 } 17971 } 17972 17973 @Override setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation)17974 public void setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation) { 17975 ActivityManagerService.this.setRunningRemoteAnimation(pid, runningRemoteAnimation); 17976 } 17977 17978 @Override getMemoryStateForProcesses()17979 public List<ProcessMemoryState> getMemoryStateForProcesses() { 17980 List<ProcessMemoryState> processMemoryStates = new ArrayList<>(); 17981 synchronized (mPidsSelfLocked) { 17982 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 17983 final ProcessRecord r = mPidsSelfLocked.valueAt(i); 17984 processMemoryStates.add( 17985 new ProcessMemoryState(r.uid, r.pid, r.processName, r.curAdj)); 17986 } 17987 } 17988 return processMemoryStates; 17989 } 17990 17991 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)17992 public int handleIncomingUser(int callingPid, int callingUid, int userId, 17993 boolean allowAll, int allowMode, String name, String callerPackage) { 17994 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 17995 allowMode, name, callerPackage); 17996 } 17997 17998 @Override enforceCallingPermission(String permission, String func)17999 public void enforceCallingPermission(String permission, String func) { 18000 ActivityManagerService.this.enforceCallingPermission(permission, func); 18001 } 18002 18003 @Override getCurrentUserId()18004 public int getCurrentUserId() { 18005 return mUserController.getCurrentUserIdLU(); 18006 } 18007 18008 @Override isUserRunning(int userId, int flags)18009 public boolean isUserRunning(int userId, int flags) { 18010 // Holding am lock isn't required to call into user controller. 18011 return mUserController.isUserRunning(userId, flags); 18012 } 18013 18014 @Override trimApplications()18015 public void trimApplications() { 18016 ActivityManagerService.this.trimApplications(OomAdjuster.OOM_ADJ_REASON_ACTIVITY); 18017 } 18018 killProcessesForRemovedTask(ArrayList<Object> procsToKill)18019 public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) { 18020 synchronized (ActivityManagerService.this) { 18021 for (int i = 0; i < procsToKill.size(); i++) { 18022 final WindowProcessController wpc = 18023 (WindowProcessController) procsToKill.get(i); 18024 final ProcessRecord pr = (ProcessRecord) wpc.mOwner; 18025 if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND 18026 && pr.curReceivers.isEmpty()) { 18027 pr.kill("remove task", true); 18028 } else { 18029 // We delay killing processes that are not in the background or running a 18030 // receiver. 18031 pr.waitingToKill = "remove task"; 18032 } 18033 } 18034 } 18035 } 18036 18037 @Override killProcess(String processName, int uid, String reason)18038 public void killProcess(String processName, int uid, String reason) { 18039 synchronized (ActivityManagerService.this) { 18040 final ProcessRecord proc = getProcessRecordLocked(processName, uid, 18041 true /* keepIfLarge */); 18042 if (proc != null) { 18043 mProcessList.removeProcessLocked(proc, false /* callerWillRestart */, 18044 true /* allowRestart */, reason); 18045 } 18046 } 18047 } 18048 18049 @Override hasRunningActivity(int uid, @Nullable String packageName)18050 public boolean hasRunningActivity(int uid, @Nullable String packageName) { 18051 if (packageName == null) return false; 18052 18053 synchronized (ActivityManagerService.this) { 18054 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) { 18055 final ProcessRecord pr = mProcessList.mLruProcesses.get(i); 18056 if (pr.uid != uid) { 18057 continue; 18058 } 18059 if (pr.getWindowProcessController().hasRunningActivity(packageName)) { 18060 return true; 18061 } 18062 } 18063 } 18064 return false; 18065 } 18066 18067 @Override updateOomAdj()18068 public void updateOomAdj() { 18069 synchronized (ActivityManagerService.this) { 18070 ActivityManagerService.this.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 18071 } 18072 } 18073 18074 @Override updateCpuStats()18075 public void updateCpuStats() { 18076 synchronized (ActivityManagerService.this) { 18077 ActivityManagerService.this.updateCpuStats(); 18078 } 18079 } 18080 18081 @Override updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)18082 public void updateBatteryStats(ComponentName activity, int uid, int userId, 18083 boolean resumed) { 18084 synchronized (ActivityManagerService.this) { 18085 ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed); 18086 } 18087 } 18088 18089 @Override updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)18090 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 18091 IBinder appToken, ComponentName taskRoot) { 18092 synchronized (ActivityManagerService.this) { 18093 ActivityManagerService.this.updateActivityUsageStats(activity, userId, event, 18094 appToken, taskRoot); 18095 } 18096 } 18097 18098 @Override updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)18099 public void updateForegroundTimeIfOnBattery( 18100 String packageName, int uid, long cpuTimeDiff) { 18101 synchronized (ActivityManagerService.this) { 18102 if (!mBatteryStatsService.isOnBattery()) { 18103 return; 18104 } 18105 final BatteryStatsImpl bsi = mBatteryStatsService.getActiveStatistics(); 18106 synchronized (bsi) { 18107 final BatteryStatsImpl.Uid.Proc ps = 18108 bsi.getProcessStatsLocked(uid, packageName); 18109 if (ps != null) { 18110 ps.addForegroundTimeLocked(cpuTimeDiff); 18111 } 18112 } 18113 } 18114 } 18115 18116 @Override sendForegroundProfileChanged(int userId)18117 public void sendForegroundProfileChanged(int userId) { 18118 mUserController.sendForegroundProfileChanged(userId); 18119 } 18120 18121 @Override shouldConfirmCredentials(int userId)18122 public boolean shouldConfirmCredentials(int userId) { 18123 return mUserController.shouldConfirmCredentials(userId); 18124 } 18125 18126 @Override getCurrentProfileIds()18127 public int[] getCurrentProfileIds() { 18128 return mUserController.getCurrentProfileIds(); 18129 } 18130 18131 @Override getCurrentUser()18132 public UserInfo getCurrentUser() { 18133 return mUserController.getCurrentUser(); 18134 } 18135 18136 @Override ensureNotSpecialUser(int userId)18137 public void ensureNotSpecialUser(int userId) { 18138 mUserController.ensureNotSpecialUser(userId); 18139 } 18140 18141 @Override isCurrentProfile(int userId)18142 public boolean isCurrentProfile(int userId) { 18143 return mUserController.isCurrentProfile(userId); 18144 } 18145 18146 @Override hasStartedUserState(int userId)18147 public boolean hasStartedUserState(int userId) { 18148 return mUserController.hasStartedUserState(userId); 18149 } 18150 18151 @Override finishUserSwitch(Object uss)18152 public void finishUserSwitch(Object uss) { 18153 mUserController.finishUserSwitch((UserState) uss); 18154 } 18155 18156 @Override scheduleAppGcs()18157 public void scheduleAppGcs() { 18158 synchronized (ActivityManagerService.this) { 18159 ActivityManagerService.this.scheduleAppGcsLocked(); 18160 } 18161 } 18162 18163 @Override getTaskIdForActivity(IBinder token, boolean onlyRoot)18164 public int getTaskIdForActivity(IBinder token, boolean onlyRoot) { 18165 synchronized (ActivityManagerService.this) { 18166 return ActivityManagerService.this.getTaskForActivity(token, onlyRoot); 18167 } 18168 } 18169 18170 @Override getActivityPresentationInfo(IBinder token)18171 public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) { 18172 int displayId = Display.INVALID_DISPLAY; 18173 try { 18174 displayId = mActivityTaskManager.getActivityDisplayId(token); 18175 } catch (RemoteException e) { 18176 } 18177 18178 return new ActivityPresentationInfo(mActivityTaskManager.getTaskForActivity(token, 18179 /*onlyRoot=*/ false), displayId, 18180 mActivityTaskManager.getActivityClassForToken(token)); 18181 } 18182 18183 @Override setBooting(boolean booting)18184 public void setBooting(boolean booting) { 18185 mBooting = booting; 18186 } 18187 18188 @Override isBooting()18189 public boolean isBooting() { 18190 return mBooting; 18191 } 18192 18193 @Override setBooted(boolean booted)18194 public void setBooted(boolean booted) { 18195 mBooted = booted; 18196 } 18197 18198 @Override isBooted()18199 public boolean isBooted() { 18200 return mBooted; 18201 } 18202 18203 @Override finishBooting()18204 public void finishBooting() { 18205 ActivityManagerService.this.finishBooting(); 18206 } 18207 18208 @Override tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, String tag)18209 public void tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid, 18210 long duration, String tag) { 18211 synchronized (ActivityManagerService.this) { 18212 ActivityManagerService.this.tempWhitelistForPendingIntentLocked( 18213 callerPid, callerUid, targetUid, duration, tag); 18214 } 18215 } 18216 18217 @Override broadcastIntentInPackage(String packageName, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, boolean allowBackgroundActivityStarts)18218 public int broadcastIntentInPackage(String packageName, int uid, int realCallingUid, 18219 int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, 18220 int resultCode, String resultData, Bundle resultExtras, String requiredPermission, 18221 Bundle bOptions, boolean serialized, boolean sticky, int userId, 18222 boolean allowBackgroundActivityStarts) { 18223 synchronized (ActivityManagerService.this) { 18224 return ActivityManagerService.this.broadcastIntentInPackage(packageName, uid, 18225 realCallingUid, realCallingPid, intent, resolvedType, resultTo, resultCode, 18226 resultData, resultExtras, requiredPermission, bOptions, serialized, sticky, 18227 userId, allowBackgroundActivityStarts); 18228 } 18229 } 18230 18231 @Override startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, int userId, boolean allowBackgroundActivityStarts)18232 public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType, 18233 boolean fgRequired, String callingPackage, int userId, 18234 boolean allowBackgroundActivityStarts) throws TransactionTooLargeException { 18235 synchronized(ActivityManagerService.this) { 18236 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 18237 "startServiceInPackage: " + service + " type=" + resolvedType); 18238 final long origId = Binder.clearCallingIdentity(); 18239 ComponentName res; 18240 try { 18241 res = mServices.startServiceLocked(null, service, 18242 resolvedType, -1, uid, fgRequired, callingPackage, userId, 18243 allowBackgroundActivityStarts); 18244 } finally { 18245 Binder.restoreCallingIdentity(origId); 18246 } 18247 return res; 18248 } 18249 } 18250 18251 // The arguments here are untyped because the base ActivityManagerInternal class 18252 // doesn't have compile-time visiblity into ActivityServiceConnectionHolder or 18253 // ConnectionRecord. 18254 @Override disconnectActivityFromServices(Object connectionHolder, Object conns)18255 public void disconnectActivityFromServices(Object connectionHolder, Object conns) { 18256 // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder 18257 // 'conns' is an untyped HashSet<ConnectionRecord> 18258 final ActivityServiceConnectionsHolder holder = 18259 (ActivityServiceConnectionsHolder) connectionHolder; 18260 final HashSet<ConnectionRecord> toDisconnect = (HashSet<ConnectionRecord>) conns; 18261 synchronized(ActivityManagerService.this) { 18262 for (ConnectionRecord cr : toDisconnect) { 18263 mServices.removeConnectionLocked(cr, null, holder); 18264 } 18265 } 18266 } 18267 cleanUpServices(int userId, ComponentName component, Intent baseIntent)18268 public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) { 18269 synchronized(ActivityManagerService.this) { 18270 mServices.cleanUpServices(userId, component, baseIntent); 18271 } 18272 } 18273 getActivityInfoForUser(ActivityInfo aInfo, int userId)18274 public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 18275 // Locked intentionally not held as it isn't needed for this case. 18276 return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId); 18277 } 18278 ensureBootCompleted()18279 public void ensureBootCompleted() { 18280 // Locked intentionally not held as it isn't needed for this case. 18281 ActivityManagerService.this.ensureBootCompleted(); 18282 } 18283 updateOomLevelsForDisplay(int displayId)18284 public void updateOomLevelsForDisplay(int displayId) { 18285 synchronized(ActivityManagerService.this) { 18286 if (mWindowManager != null) { 18287 mProcessList.applyDisplaySize(mWindowManager); 18288 } 18289 } 18290 } 18291 isActivityStartsLoggingEnabled()18292 public boolean isActivityStartsLoggingEnabled() { 18293 return mConstants.mFlagActivityStartsLoggingEnabled; 18294 } 18295 isBackgroundActivityStartsEnabled()18296 public boolean isBackgroundActivityStartsEnabled() { 18297 return mConstants.mFlagBackgroundActivityStartsEnabled; 18298 } 18299 reportCurKeyguardUsageEvent(boolean keyguardShowing)18300 public void reportCurKeyguardUsageEvent(boolean keyguardShowing) { 18301 synchronized(ActivityManagerService.this) { 18302 ActivityManagerService.this.reportGlobalUsageEventLocked(keyguardShowing 18303 ? UsageEvents.Event.KEYGUARD_SHOWN 18304 : UsageEvents.Event.KEYGUARD_HIDDEN); 18305 } 18306 } 18307 18308 @Override inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason)18309 public long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason) { 18310 synchronized (ActivityManagerService.this) { 18311 return ActivityManagerService.this.inputDispatchingTimedOut( 18312 pid, aboveSystem, reason); 18313 } 18314 } 18315 18316 @Override inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, String reason)18317 public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName, 18318 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, 18319 boolean aboveSystem, String reason) { 18320 return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc, 18321 activityShortComponentName, aInfo, parentShortComponentName, 18322 (WindowProcessController) parentProc, aboveSystem, reason); 18323 18324 } 18325 18326 @Override broadcastGlobalConfigurationChanged(int changes, boolean initLocale)18327 public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) { 18328 synchronized (ActivityManagerService.this) { 18329 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 18330 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18331 | Intent.FLAG_RECEIVER_REPLACE_PENDING 18332 | Intent.FLAG_RECEIVER_FOREGROUND 18333 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 18334 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 18335 OP_NONE, null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(), 18336 Binder.getCallingPid(), UserHandle.USER_ALL); 18337 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) { 18338 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 18339 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND 18340 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND 18341 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 18342 if (initLocale || !mProcessesReady) { 18343 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 18344 } 18345 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 18346 OP_NONE, null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(), 18347 Binder.getCallingPid(), UserHandle.USER_ALL); 18348 } 18349 18350 // Send a broadcast to PackageInstallers if the configuration change is interesting 18351 // for the purposes of installing additional splits. 18352 if (!initLocale && isSplitConfigurationChange(changes)) { 18353 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED); 18354 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING 18355 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 18356 18357 // Typically only app stores will have this permission. 18358 String[] permissions = 18359 new String[] { android.Manifest.permission.INSTALL_PACKAGES }; 18360 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, 18361 permissions, OP_NONE, null, false, false, MY_PID, SYSTEM_UID, 18362 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 18363 } 18364 } 18365 } 18366 18367 /** 18368 * Returns true if this configuration change is interesting enough to send an 18369 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast. 18370 */ isSplitConfigurationChange(int configDiff)18371 private boolean isSplitConfigurationChange(int configDiff) { 18372 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0; 18373 } 18374 18375 @Override broadcastCloseSystemDialogs(String reason)18376 public void broadcastCloseSystemDialogs(String reason) { 18377 synchronized (ActivityManagerService.this) { 18378 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 18379 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18380 | Intent.FLAG_RECEIVER_FOREGROUND); 18381 if (reason != null) { 18382 intent.putExtra("reason", reason); 18383 } 18384 18385 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 18386 OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(), 18387 Binder.getCallingPid(), UserHandle.USER_ALL); 18388 } 18389 } 18390 18391 @Override killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)18392 public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 18393 synchronized (ActivityManagerService.this) { 18394 ActivityManagerService.this.killAllBackgroundProcessesExcept( 18395 minTargetSdk, maxProcState); 18396 } 18397 } 18398 18399 @Override startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, String hostingType, ComponentName hostingName)18400 public void startProcess(String processName, ApplicationInfo info, 18401 boolean knownToBeDead, String hostingType, ComponentName hostingName) { 18402 try { 18403 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 18404 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:" 18405 + processName); 18406 } 18407 synchronized (ActivityManagerService.this) { 18408 startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */, 18409 new HostingRecord(hostingType, hostingName), 18410 false /* allowWhileBooting */, false /* isolated */, 18411 true /* keepIfLarge */); 18412 } 18413 } finally { 18414 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 18415 } 18416 } 18417 18418 @Override setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)18419 public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, 18420 ProfilerInfo profilerInfo, Object wmLock) { 18421 synchronized (ActivityManagerService.this) { 18422 /** 18423 * This function is called from the window manager context and needs to be executed 18424 * synchronously. To avoid deadlock, we pass a message to AMS to execute the 18425 * function and notify the passed in lock when it has been completed. 18426 */ 18427 synchronized (wmLock) { 18428 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) { 18429 setDebugApp(aInfo.processName, true, false); 18430 } 18431 18432 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) { 18433 setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName); 18434 } 18435 18436 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) { 18437 setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName); 18438 } 18439 18440 if (profilerInfo != null) { 18441 setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo); 18442 } 18443 wmLock.notify(); 18444 } 18445 } 18446 } 18447 18448 @Override getStorageMountMode(int pid, int uid)18449 public int getStorageMountMode(int pid, int uid) { 18450 if (uid == SHELL_UID || uid == ROOT_UID) { 18451 return Zygote.MOUNT_EXTERNAL_FULL; 18452 } 18453 synchronized (mPidsSelfLocked) { 18454 final ProcessRecord pr = mPidsSelfLocked.get(pid); 18455 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.mountMode; 18456 } 18457 } 18458 18459 @Override isAppForeground(int uid)18460 public boolean isAppForeground(int uid) { 18461 return ActivityManagerService.this.isAppForeground(uid); 18462 } 18463 18464 @Override isAppBad(ApplicationInfo info)18465 public boolean isAppBad(ApplicationInfo info) { 18466 return ActivityManagerService.this.isAppBad(info); 18467 } 18468 18469 @Override clearPendingBackup(int userId)18470 public void clearPendingBackup(int userId) { 18471 ActivityManagerService.this.clearPendingBackup(userId); 18472 } 18473 18474 /** 18475 * When power button is very long pressed, call this interface to do some pre-shutdown work 18476 * like persisting database etc. 18477 */ 18478 @Override prepareForPossibleShutdown()18479 public void prepareForPossibleShutdown() { 18480 ActivityManagerService.this.prepareForPossibleShutdown(); 18481 } 18482 18483 @Override hasRunningForegroundService(int uid, int foregroundServicetype)18484 public boolean hasRunningForegroundService(int uid, int foregroundServicetype) { 18485 synchronized (ActivityManagerService.this) { 18486 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) { 18487 final ProcessRecord pr = mProcessList.mLruProcesses.get(i); 18488 if (pr.uid != uid) { 18489 continue; 18490 } 18491 18492 if ((pr.getForegroundServiceTypes() & foregroundServicetype) != 0) { 18493 return true; 18494 } 18495 } 18496 } 18497 18498 return false; 18499 } 18500 18501 @Override registerProcessObserver(IProcessObserver processObserver)18502 public void registerProcessObserver(IProcessObserver processObserver) { 18503 ActivityManagerService.this.registerProcessObserver(processObserver); 18504 } 18505 18506 @Override unregisterProcessObserver(IProcessObserver processObserver)18507 public void unregisterProcessObserver(IProcessObserver processObserver) { 18508 ActivityManagerService.this.unregisterProcessObserver(processObserver); 18509 } 18510 } 18511 inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason)18512 long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) { 18513 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 18514 throw new SecurityException("Requires permission " + FILTER_EVENTS); 18515 } 18516 ProcessRecord proc; 18517 long timeout; 18518 synchronized (this) { 18519 synchronized (mPidsSelfLocked) { 18520 proc = mPidsSelfLocked.get(pid); 18521 } 18522 timeout = proc != null ? proc.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS; 18523 } 18524 18525 if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, reason)) { 18526 return -1; 18527 } 18528 18529 return timeout; 18530 } 18531 18532 /** 18533 * Handle input dispatching timeouts. 18534 * @return whether input dispatching should be aborted or not. 18535 */ inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, WindowProcessController parentProcess, boolean aboveSystem, String reason)18536 boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, 18537 ApplicationInfo aInfo, String parentShortComponentName, 18538 WindowProcessController parentProcess, boolean aboveSystem, String reason) { 18539 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 18540 throw new SecurityException("Requires permission " + FILTER_EVENTS); 18541 } 18542 18543 final String annotation; 18544 if (reason == null) { 18545 annotation = "Input dispatching timed out"; 18546 } else { 18547 annotation = "Input dispatching timed out (" + reason + ")"; 18548 } 18549 18550 if (proc != null) { 18551 synchronized (this) { 18552 if (proc.isDebugging()) { 18553 return false; 18554 } 18555 18556 if (proc.getActiveInstrumentation() != null) { 18557 Bundle info = new Bundle(); 18558 info.putString("shortMsg", "keyDispatchingTimedOut"); 18559 info.putString("longMsg", annotation); 18560 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 18561 return true; 18562 } 18563 } 18564 proc.appNotResponding(activityShortComponentName, aInfo, 18565 parentShortComponentName, parentProcess, aboveSystem, annotation); 18566 } 18567 18568 return true; 18569 } 18570 18571 /** 18572 * Called by app main thread to wait for the network policy rules to get updated. 18573 * 18574 * @param procStateSeq The sequence number indicating the process state change that the main 18575 * thread is interested in. 18576 */ 18577 @Override waitForNetworkStateUpdate(long procStateSeq)18578 public void waitForNetworkStateUpdate(long procStateSeq) { 18579 final int callingUid = Binder.getCallingUid(); 18580 if (DEBUG_NETWORK) { 18581 Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq); 18582 } 18583 UidRecord record; 18584 synchronized (this) { 18585 record = mProcessList.getUidRecordLocked(callingUid); 18586 if (record == null) { 18587 return; 18588 } 18589 } 18590 synchronized (record.networkStateLock) { 18591 if (record.lastDispatchedProcStateSeq < procStateSeq) { 18592 if (DEBUG_NETWORK) { 18593 Slog.d(TAG_NETWORK, "Uid state change for seq no. " + procStateSeq + " is not " 18594 + "dispatched to NPMS yet, so don't wait. Uid: " + callingUid 18595 + " lastProcStateSeqDispatchedToObservers: " 18596 + record.lastDispatchedProcStateSeq); 18597 } 18598 return; 18599 } 18600 if (record.curProcStateSeq > procStateSeq) { 18601 if (DEBUG_NETWORK) { 18602 Slog.d(TAG_NETWORK, "Ignore the wait requests for older seq numbers. Uid: " 18603 + callingUid + ", curProcStateSeq: " + record.curProcStateSeq 18604 + ", procStateSeq: " + procStateSeq); 18605 } 18606 return; 18607 } 18608 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 18609 if (DEBUG_NETWORK) { 18610 Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. " 18611 + procStateSeq + ", so no need to wait. Uid: " 18612 + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: " 18613 + record.lastNetworkUpdatedProcStateSeq); 18614 } 18615 return; 18616 } 18617 try { 18618 if (DEBUG_NETWORK) { 18619 Slog.d(TAG_NETWORK, "Starting to wait for the network rules update." 18620 + " Uid: " + callingUid + " procStateSeq: " + procStateSeq); 18621 } 18622 final long startTime = SystemClock.uptimeMillis(); 18623 record.waitingForNetwork = true; 18624 record.networkStateLock.wait(mWaitForNetworkTimeoutMs); 18625 record.waitingForNetwork = false; 18626 final long totalTime = SystemClock.uptimeMillis() - startTime; 18627 if (totalTime >= mWaitForNetworkTimeoutMs || DEBUG_NETWORK) { 18628 Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: " 18629 + totalTime + ". Uid: " + callingUid + " procStateSeq: " 18630 + procStateSeq + " UidRec: " + record 18631 + " validateUidRec: " + mValidateUids.get(callingUid)); 18632 } 18633 } catch (InterruptedException e) { 18634 Thread.currentThread().interrupt(); 18635 } 18636 } 18637 } 18638 waitForBroadcastIdle(PrintWriter pw)18639 public void waitForBroadcastIdle(PrintWriter pw) { 18640 enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()"); 18641 while (true) { 18642 boolean idle = true; 18643 synchronized (this) { 18644 for (BroadcastQueue queue : mBroadcastQueues) { 18645 if (!queue.isIdle()) { 18646 final String msg = "Waiting for queue " + queue + " to become idle..."; 18647 pw.println(msg); 18648 pw.println(queue.describeState()); 18649 pw.flush(); 18650 Slog.v(TAG, msg); 18651 queue.cancelDeferrals(); 18652 idle = false; 18653 } 18654 } 18655 } 18656 18657 if (idle) { 18658 final String msg = "All broadcast queues are idle!"; 18659 pw.println(msg); 18660 pw.flush(); 18661 Slog.v(TAG, msg); 18662 return; 18663 } else { 18664 SystemClock.sleep(1000); 18665 } 18666 } 18667 } 18668 18669 /** 18670 * Kill processes for the user with id userId and that depend on the package named packageName 18671 */ 18672 @Override killPackageDependents(String packageName, int userId)18673 public void killPackageDependents(String packageName, int userId) { 18674 enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()"); 18675 if (packageName == null) { 18676 throw new NullPointerException( 18677 "Cannot kill the dependents of a package without its name."); 18678 } 18679 18680 long callingId = Binder.clearCallingIdentity(); 18681 IPackageManager pm = AppGlobals.getPackageManager(); 18682 int pkgUid = -1; 18683 try { 18684 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 18685 } catch (RemoteException e) { 18686 } 18687 if (userId != UserHandle.USER_ALL && pkgUid == -1) { 18688 throw new IllegalArgumentException( 18689 "Cannot kill dependents of non-existing package " + packageName); 18690 } 18691 try { 18692 synchronized(this) { 18693 mProcessList.killPackageProcessesLocked(packageName, UserHandle.getAppId(pkgUid), 18694 userId, ProcessList.FOREGROUND_APP_ADJ, "dep: " + packageName); 18695 } 18696 } finally { 18697 Binder.restoreCallingIdentity(callingId); 18698 } 18699 } 18700 18701 @Override restartUserInBackground(final int userId)18702 public int restartUserInBackground(final int userId) { 18703 return mUserController.restartUser(userId, /* foreground */ false); 18704 } 18705 18706 @Override scheduleApplicationInfoChanged(List<String> packageNames, int userId)18707 public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) { 18708 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 18709 "scheduleApplicationInfoChanged()"); 18710 18711 synchronized (this) { 18712 final long origId = Binder.clearCallingIdentity(); 18713 try { 18714 updateApplicationInfoLocked(packageNames, userId); 18715 } finally { 18716 Binder.restoreCallingIdentity(origId); 18717 } 18718 } 18719 } 18720 18721 /** 18722 * Synchronously update the system ActivityThread, bypassing any deferred threading so any 18723 * resources and overlaid values are available immediately. 18724 */ updateSystemUiContext()18725 public void updateSystemUiContext() { 18726 PackageManagerInternal packageManagerInternal; 18727 synchronized (this) { 18728 packageManagerInternal = getPackageManagerInternalLocked(); 18729 } 18730 18731 ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android", 18732 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM); 18733 ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai); 18734 } 18735 updateApplicationInfoLocked(@onNull List<String> packagesToUpdate, int userId)18736 void updateApplicationInfoLocked(@NonNull List<String> packagesToUpdate, int userId) { 18737 final boolean updateFrameworkRes = packagesToUpdate.contains("android"); 18738 if (updateFrameworkRes) { 18739 PackageParser.readConfigUseRoundIcon(null); 18740 } 18741 mProcessList.updateApplicationInfoLocked(packagesToUpdate, userId, updateFrameworkRes); 18742 18743 if (updateFrameworkRes) { 18744 // Update system server components that need to know about changed overlays. Because the 18745 // overlay is applied in ActivityThread, we need to serialize through its thread too. 18746 final Executor executor = ActivityThread.currentActivityThread().getExecutor(); 18747 final DisplayManagerInternal display = 18748 LocalServices.getService(DisplayManagerInternal.class); 18749 if (display != null) { 18750 executor.execute(display::onOverlayChanged); 18751 } 18752 if (mWindowManager != null) { 18753 executor.execute(mWindowManager::onOverlayChanged); 18754 } 18755 } 18756 } 18757 18758 /** 18759 * Attach an agent to the specified process (proces name or PID) 18760 */ attachAgent(String process, String path)18761 public void attachAgent(String process, String path) { 18762 try { 18763 synchronized (this) { 18764 ProcessRecord proc = findProcessLocked(process, UserHandle.USER_SYSTEM, 18765 "attachAgent"); 18766 if (proc == null || proc.thread == null) { 18767 throw new IllegalArgumentException("Unknown process: " + process); 18768 } 18769 18770 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 18771 if (!isDebuggable) { 18772 if ((proc.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 18773 throw new SecurityException("Process not debuggable: " + proc); 18774 } 18775 } 18776 18777 proc.thread.attachAgent(path); 18778 } 18779 } catch (RemoteException e) { 18780 throw new IllegalStateException("Process disappeared"); 18781 } 18782 } 18783 18784 /** 18785 * When power button is very long pressed, call this interface to do some pre-shutdown work 18786 * like persisting database etc. 18787 */ prepareForPossibleShutdown()18788 public void prepareForPossibleShutdown() { 18789 synchronized (this) { 18790 if (mUsageStatsService != null) { 18791 mUsageStatsService.prepareForPossibleShutdown(); 18792 } 18793 } 18794 } 18795 18796 @VisibleForTesting 18797 public static class Injector { 18798 private NetworkManagementInternal mNmi; 18799 getContext()18800 public Context getContext() { 18801 return null; 18802 } 18803 getAppOpsService(File file, Handler handler)18804 public AppOpsService getAppOpsService(File file, Handler handler) { 18805 return new AppOpsService(file, handler); 18806 } 18807 getUiHandler(ActivityManagerService service)18808 public Handler getUiHandler(ActivityManagerService service) { 18809 return service.new UiHandler(); 18810 } 18811 isNetworkRestrictedForUid(int uid)18812 public boolean isNetworkRestrictedForUid(int uid) { 18813 if (ensureHasNetworkManagementInternal()) { 18814 return mNmi.isNetworkRestrictedForUid(uid); 18815 } 18816 return false; 18817 } 18818 ensureHasNetworkManagementInternal()18819 private boolean ensureHasNetworkManagementInternal() { 18820 if (mNmi == null) { 18821 mNmi = LocalServices.getService(NetworkManagementInternal.class); 18822 } 18823 return mNmi != null; 18824 } 18825 } 18826 18827 @Override startDelegateShellPermissionIdentity(int delegateUid, @Nullable String[] permissions)18828 public void startDelegateShellPermissionIdentity(int delegateUid, 18829 @Nullable String[] permissions) { 18830 if (UserHandle.getCallingAppId() != Process.SHELL_UID 18831 && UserHandle.getCallingAppId() != Process.ROOT_UID) { 18832 throw new SecurityException("Only the shell can delegate its permissions"); 18833 } 18834 18835 // We allow delegation only to one instrumentation started from the shell 18836 synchronized (ActivityManagerService.this) { 18837 // If there is a delegate it should be the same instance for app ops and permissions. 18838 if (mAppOpsService.getAppOpsServiceDelegate() 18839 != getPackageManagerInternalLocked().getCheckPermissionDelegate()) { 18840 throw new IllegalStateException("Bad shell delegate state"); 18841 } 18842 18843 // If the delegate is already set up for the target UID, nothing to do. 18844 if (mAppOpsService.getAppOpsServiceDelegate() != null) { 18845 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) { 18846 throw new IllegalStateException("Bad shell delegate state"); 18847 } 18848 final ShellDelegate delegate = (ShellDelegate) mAppOpsService 18849 .getAppOpsServiceDelegate(); 18850 if (delegate.getDelegateUid() != delegateUid) { 18851 throw new SecurityException("Shell can delegate permissions only " 18852 + "to one instrumentation at a time"); 18853 } 18854 delegate.setPermissions(permissions); 18855 return; 18856 } 18857 18858 final int instrCount = mActiveInstrumentation.size(); 18859 for (int i = 0; i < instrCount; i++) { 18860 final ActiveInstrumentation instr = mActiveInstrumentation.get(i); 18861 if (instr.mTargetInfo.uid != delegateUid) { 18862 continue; 18863 } 18864 // If instrumentation started from the shell the connection is not null 18865 if (instr.mUiAutomationConnection == null) { 18866 throw new SecurityException("Shell can delegate its permissions" + 18867 " only to an instrumentation started from the shell"); 18868 } 18869 18870 // Hook them up... 18871 final ShellDelegate shellDelegate = new ShellDelegate( 18872 instr.mTargetInfo.packageName, delegateUid, permissions); 18873 mAppOpsService.setAppOpsServiceDelegate(shellDelegate); 18874 getPackageManagerInternalLocked().setCheckPermissionDelegate(shellDelegate); 18875 return; 18876 } 18877 } 18878 } 18879 18880 @Override stopDelegateShellPermissionIdentity()18881 public void stopDelegateShellPermissionIdentity() { 18882 if (UserHandle.getCallingAppId() != Process.SHELL_UID 18883 && UserHandle.getCallingAppId() != Process.ROOT_UID) { 18884 throw new SecurityException("Only the shell can delegate its permissions"); 18885 } 18886 synchronized (ActivityManagerService.this) { 18887 mAppOpsService.setAppOpsServiceDelegate(null); 18888 getPackageManagerInternalLocked().setCheckPermissionDelegate(null); 18889 } 18890 } 18891 18892 private class ShellDelegate implements CheckOpsDelegate, CheckPermissionDelegate { 18893 private final String mTargetPackageName; 18894 private final int mTargetUid; 18895 private @Nullable String[] mPermissions; 18896 ShellDelegate(String targetPacakgeName, int targetUid, @Nullable String[] permissions)18897 ShellDelegate(String targetPacakgeName, int targetUid, @Nullable String[] permissions) { 18898 mTargetPackageName = targetPacakgeName; 18899 mTargetUid = targetUid; 18900 mPermissions = permissions; 18901 } 18902 getDelegateUid()18903 int getDelegateUid() { 18904 return mTargetUid; 18905 } 18906 setPermissions(@ullable String[] permissions)18907 void setPermissions(@Nullable String[] permissions) { 18908 mPermissions = permissions; 18909 } 18910 18911 @Override checkOperation(int code, int uid, String packageName, boolean raw, QuadFunction<Integer, Integer, String, Boolean, Integer> superImpl)18912 public int checkOperation(int code, int uid, String packageName, boolean raw, 18913 QuadFunction<Integer, Integer, String, Boolean, Integer> superImpl) { 18914 if (uid == mTargetUid && isTargetOp(code)) { 18915 final long identity = Binder.clearCallingIdentity(); 18916 try { 18917 return superImpl.apply(code, Process.SHELL_UID, 18918 "com.android.shell", raw); 18919 } finally { 18920 Binder.restoreCallingIdentity(identity); 18921 } 18922 } 18923 return superImpl.apply(code, uid, packageName, raw); 18924 } 18925 18926 @Override checkAudioOperation(int code, int usage, int uid, String packageName, QuadFunction<Integer, Integer, Integer, String, Integer> superImpl)18927 public int checkAudioOperation(int code, int usage, int uid, String packageName, 18928 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) { 18929 if (uid == mTargetUid && isTargetOp(code)) { 18930 final long identity = Binder.clearCallingIdentity(); 18931 try { 18932 return superImpl.apply(code, usage, Process.SHELL_UID, 18933 "com.android.shell"); 18934 } finally { 18935 Binder.restoreCallingIdentity(identity); 18936 } 18937 } 18938 return superImpl.apply(code, usage, uid, packageName); 18939 } 18940 18941 @Override noteOperation(int code, int uid, String packageName, TriFunction<Integer, Integer, String, Integer> superImpl)18942 public int noteOperation(int code, int uid, String packageName, 18943 TriFunction<Integer, Integer, String, Integer> superImpl) { 18944 if (uid == mTargetUid && isTargetOp(code)) { 18945 final long identity = Binder.clearCallingIdentity(); 18946 try { 18947 return mAppOpsService.noteProxyOperation(code, Process.SHELL_UID, 18948 "com.android.shell", uid, packageName); 18949 } finally { 18950 Binder.restoreCallingIdentity(identity); 18951 } 18952 } 18953 return superImpl.apply(code, uid, packageName); 18954 } 18955 18956 @Override checkPermission(String permName, String pkgName, int userId, TriFunction<String, String, Integer, Integer> superImpl)18957 public int checkPermission(String permName, String pkgName, int userId, 18958 TriFunction<String, String, Integer, Integer> superImpl) { 18959 if (mTargetPackageName.equals(pkgName) && isTargetPermission(permName)) { 18960 final long identity = Binder.clearCallingIdentity(); 18961 try { 18962 return superImpl.apply(permName, "com.android.shell", userId); 18963 } finally { 18964 Binder.restoreCallingIdentity(identity); 18965 } 18966 } 18967 return superImpl.apply(permName, pkgName, userId); 18968 } 18969 18970 @Override checkUidPermission(String permName, int uid, BiFunction<String, Integer, Integer> superImpl)18971 public int checkUidPermission(String permName, int uid, 18972 BiFunction<String, Integer, Integer> superImpl) { 18973 if (uid == mTargetUid && isTargetPermission(permName)) { 18974 final long identity = Binder.clearCallingIdentity(); 18975 try { 18976 return superImpl.apply(permName, Process.SHELL_UID); 18977 } finally { 18978 Binder.restoreCallingIdentity(identity); 18979 } 18980 } 18981 return superImpl.apply(permName, uid); 18982 } 18983 isTargetOp(int code)18984 private boolean isTargetOp(int code) { 18985 // null permissions means all ops are targeted 18986 if (mPermissions == null) { 18987 return true; 18988 } 18989 // no permission for the op means the op is targeted 18990 final String permission = AppOpsManager.opToPermission(code); 18991 if (permission == null) { 18992 return true; 18993 } 18994 return isTargetPermission(permission); 18995 } 18996 isTargetPermission(@onNull String permission)18997 private boolean isTargetPermission(@NonNull String permission) { 18998 // null permissions means all permissions are targeted 18999 return (mPermissions == null || ArrayUtils.contains(mPermissions, permission)); 19000 } 19001 } 19002 19003 /** 19004 * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would 19005 * cause a watchdog kill. 19006 */ maybeTriggerWatchdog()19007 void maybeTriggerWatchdog() { 19008 final String key = "debug.trigger.watchdog"; 19009 if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) { 19010 Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!"); 19011 19012 // Clear the property; otherwise the system would hang again after a watchdog restart. 19013 SystemProperties.set(key, ""); 19014 synchronized (ActivityManagerService.this) { 19015 try { 19016 // Arbitrary long sleep for watchdog to catch. 19017 Thread.sleep(60 * 60 * 1000); 19018 } catch (InterruptedException e) { 19019 } 19020 } 19021 } 19022 } 19023 isOnOffloadQueue(int flags)19024 private boolean isOnOffloadQueue(int flags) { 19025 return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0)); 19026 } 19027 19028 @Override getLifeMonitor()19029 public ParcelFileDescriptor getLifeMonitor() { 19030 if (!isCallerShell()) { 19031 throw new SecurityException("Only shell can call it"); 19032 } 19033 synchronized (this) { 19034 try { 19035 if (mLifeMonitorFds == null) { 19036 mLifeMonitorFds = ParcelFileDescriptor.createPipe(); 19037 } 19038 // The returned FD will be closed, but we want to keep our reader open, 19039 // so return a dup instead. 19040 return mLifeMonitorFds[0].dup(); 19041 } catch (IOException e) { 19042 Slog.w(TAG, "Unable to create pipe", e); 19043 return null; 19044 } 19045 } 19046 } 19047 } 19048