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.MANAGE_ACTIVITY_TASKS; 25 import static android.Manifest.permission.MANAGE_USERS; 26 import static android.Manifest.permission.REQUEST_COMPANION_RUN_IN_BACKGROUND; 27 import static android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; 28 import static android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND; 29 import static android.app.ActivityManager.INSTR_FLAG_ALWAYS_CHECK_SIGNATURE; 30 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS; 31 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_ISOLATED_STORAGE; 32 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_TEST_API_CHECKS; 33 import static android.app.ActivityManager.INSTR_FLAG_NO_RESTART; 34 import static android.app.ActivityManager.INTENT_SENDER_ACTIVITY; 35 import static android.app.ActivityManager.PROCESS_CAPABILITY_ALL; 36 import static android.app.ActivityManager.PROCESS_STATE_BOUND_TOP; 37 import static android.app.ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 38 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT; 39 import static android.app.ActivityManager.PROCESS_STATE_TOP; 40 import static android.app.ActivityManager.RESTRICTION_LEVEL_FORCE_STOPPED; 41 import static android.app.ActivityManager.RESTRICTION_REASON_DEFAULT; 42 import static android.app.ActivityManager.RESTRICTION_REASON_USAGE; 43 import static android.app.ActivityManager.RESTRICTION_SOURCE_SYSTEM; 44 import static android.app.ActivityManager.RESTRICTION_SOURCE_USER; 45 import static android.app.ActivityManager.StopUserOnSwitch; 46 import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN; 47 import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_UNFROZEN; 48 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY; 49 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL; 50 import static android.app.ActivityManagerInternal.MEDIA_PROJECTION_TOKEN_EVENT_CREATED; 51 import static android.app.ActivityManagerInternal.MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED; 52 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_BACKUP; 53 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_FINISH_RECEIVER; 54 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_PROCESS_BEGIN; 55 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_PROCESS_END; 56 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_SHELL; 57 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_SYSTEM_INIT; 58 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_UI_VISIBILITY; 59 import static android.app.AppOpsManager.OP_NONE; 60 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_BACKUP; 61 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_INSTRUMENTATION; 62 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_PERSISTENT; 63 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_SYSTEM; 64 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 65 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES; 66 import static android.content.pm.PackageManager.MATCH_ALL; 67 import static android.content.pm.PackageManager.MATCH_ANY_USER; 68 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 72 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 73 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 74 import static android.content.pm.PackageManager.SIGNATURE_NO_MATCH; 75 import static android.net.ConnectivityManager.BLOCKED_REASON_NONE; 76 import static android.os.FactoryTest.FACTORY_TEST_OFF; 77 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL; 78 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH; 79 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL; 80 import static android.os.IServiceManager.DUMP_FLAG_PROTO; 81 import static android.os.InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS; 82 import static android.os.PowerExemptionManager.REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD; 83 import static android.os.PowerExemptionManager.REASON_BACKGROUND_ACTIVITY_PERMISSION; 84 import static android.os.PowerExemptionManager.REASON_BOOT_COMPLETED; 85 import static android.os.PowerExemptionManager.REASON_COMPANION_DEVICE_MANAGER; 86 import static android.os.PowerExemptionManager.REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION; 87 import static android.os.PowerExemptionManager.REASON_LOCKED_BOOT_COMPLETED; 88 import static android.os.PowerExemptionManager.REASON_PROC_STATE_BTOP; 89 import static android.os.PowerExemptionManager.REASON_PROC_STATE_PERSISTENT; 90 import static android.os.PowerExemptionManager.REASON_PROC_STATE_PERSISTENT_UI; 91 import static android.os.PowerExemptionManager.REASON_PROC_STATE_TOP; 92 import static android.os.PowerExemptionManager.REASON_START_ACTIVITY_FLAG; 93 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALERT_WINDOW_PERMISSION; 94 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALLOW_LISTED; 95 import static android.os.PowerExemptionManager.REASON_SYSTEM_UID; 96 import static android.os.PowerExemptionManager.REASON_UID_VISIBLE; 97 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED; 98 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_NONE; 99 import static android.os.PowerExemptionManager.getReasonCodeFromProcState; 100 import static android.os.Process.BLUETOOTH_UID; 101 import static android.os.Process.FIRST_APPLICATION_UID; 102 import static android.os.Process.INVALID_UID; 103 import static android.os.Process.NETWORK_STACK_UID; 104 import static android.os.Process.NFC_UID; 105 import static android.os.Process.PHONE_UID; 106 import static android.os.Process.PROC_OUT_LONG; 107 import static android.os.Process.PROC_SPACE_TERM; 108 import static android.os.Process.ROOT_UID; 109 import static android.os.Process.SCHED_FIFO; 110 import static android.os.Process.SCHED_RESET_ON_FORK; 111 import static android.os.Process.SE_UID; 112 import static android.os.Process.SHELL_UID; 113 import static android.os.Process.SIGNAL_USR1; 114 import static android.os.Process.SYSTEM_UID; 115 import static android.os.Process.THREAD_PRIORITY_FOREGROUND; 116 import static android.os.Process.THREAD_PRIORITY_TOP_APP_BOOST; 117 import static android.os.Process.ZYGOTE_POLICY_FLAG_BATCH_LAUNCH; 118 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY; 119 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE; 120 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS; 121 import static android.os.Process.ZYGOTE_PROCESS; 122 import static android.os.Process.getTotalMemory; 123 import static android.os.Process.isThreadInProcess; 124 import static android.os.Process.killProcess; 125 import static android.os.Process.killProcessGroup; 126 import static android.os.Process.killProcessQuiet; 127 import static android.os.Process.myPid; 128 import static android.os.Process.myUid; 129 import static android.os.Process.readProcFile; 130 import static android.os.Process.sendSignal; 131 import static android.os.Process.setThreadPriority; 132 import static android.os.Process.setThreadScheduler; 133 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES; 134 import static android.provider.Settings.Global.DEBUG_APP; 135 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER; 136 import static android.util.FeatureFlagUtils.SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS; 137 import static android.view.Display.INVALID_DISPLAY; 138 139 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_CONFIGURATION; 140 import static com.android.internal.util.FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__NEW_MUTABLE_IMPLICIT_PENDING_INTENT_RETRIEVED; 141 import static com.android.sdksandbox.flags.Flags.sdkSandboxInstrumentationInfo; 142 import static com.android.server.am.ActiveServices.FGS_SAW_RESTRICTIONS; 143 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL; 144 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALLOWLISTS; 145 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK; 146 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP; 147 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; 148 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; 149 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 150 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK; 151 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ; 152 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER; 153 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES; 154 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE; 155 import static com.android.server.am.ActivityManagerDebugConfig.LOG_WRITER_INFO; 156 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP; 157 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; 158 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP; 159 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU; 160 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; 161 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK; 162 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ; 163 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER; 164 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES; 165 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE; 166 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS; 167 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 168 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 169 import static com.android.server.am.MemoryStatUtil.hasMemcg; 170 import static com.android.server.am.ProcessList.ProcStartHandler; 171 import static com.android.server.flags.Flags.disableSystemCompaction; 172 import static com.android.server.net.NetworkPolicyManagerInternal.updateBlockedReasonsWithProcState; 173 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 174 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND; 175 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND; 176 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP; 177 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH; 178 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION; 179 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK; 180 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH; 181 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD; 182 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD; 183 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD; 184 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD; 185 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD; 186 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD; 187 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD; 188 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD; 189 import static com.android.server.wm.ActivityTaskManagerService.DUMP_TOP_RESUMED_ACTIVITY; 190 import static com.android.server.wm.ActivityTaskManagerService.DUMP_VISIBLE_ACTIVITIES; 191 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE; 192 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString; 193 import static com.android.systemui.shared.Flags.enableHomeDelay; 194 195 import android.Manifest; 196 import android.Manifest.permission; 197 import android.annotation.NonNull; 198 import android.annotation.Nullable; 199 import android.annotation.PermissionMethod; 200 import android.annotation.PermissionName; 201 import android.annotation.RequiresPermission; 202 import android.annotation.UserIdInt; 203 import android.app.Activity; 204 import android.app.ActivityClient; 205 import android.app.ActivityManager; 206 import android.app.ActivityManager.ForegroundServiceApiType; 207 import android.app.ActivityManager.PendingIntentInfo; 208 import android.app.ActivityManager.ProcessCapability; 209 import android.app.ActivityManager.RestrictionLevel; 210 import android.app.ActivityManager.RunningTaskInfo; 211 import android.app.ActivityManager.UidFrozenStateChangedCallback.UidFrozenState; 212 import android.app.ActivityManagerInternal; 213 import android.app.ActivityManagerInternal.BindServiceEventListener; 214 import android.app.ActivityManagerInternal.BroadcastEventListener; 215 import android.app.ActivityManagerInternal.ForegroundServiceStateListener; 216 import android.app.ActivityManagerInternal.MediaProjectionTokenEvent; 217 import android.app.ActivityManagerInternal.OomAdjReason; 218 import android.app.ActivityTaskManager.RootTaskInfo; 219 import android.app.ActivityThread; 220 import android.app.AnrController; 221 import android.app.AppGlobals; 222 import android.app.AppOpsManager; 223 import android.app.AppOpsManager.AttributionFlags; 224 import android.app.AppOpsManagerInternal.CheckOpsDelegate; 225 import android.app.ApplicationErrorReport; 226 import android.app.ApplicationExitInfo; 227 import android.app.ApplicationStartInfo; 228 import android.app.ApplicationThreadConstants; 229 import android.app.BackgroundStartPrivileges; 230 import android.app.BroadcastOptions; 231 import android.app.ContentProviderHolder; 232 import android.app.ForegroundServiceDelegationOptions; 233 import android.app.IActivityController; 234 import android.app.IActivityManager; 235 import android.app.IApplicationStartInfoCompleteListener; 236 import android.app.IApplicationThread; 237 import android.app.IForegroundServiceObserver; 238 import android.app.IInstrumentationWatcher; 239 import android.app.INotificationManager; 240 import android.app.IProcessObserver; 241 import android.app.IServiceConnection; 242 import android.app.IStopUserCallback; 243 import android.app.ITaskStackListener; 244 import android.app.IUiAutomationConnection; 245 import android.app.IUidFrozenStateChangedCallback; 246 import android.app.IUidObserver; 247 import android.app.IUnsafeIntentStrictModeCallback; 248 import android.app.IUserSwitchObserver; 249 import android.app.Instrumentation; 250 import android.app.Notification; 251 import android.app.NotificationManager; 252 import android.app.PendingIntent; 253 import android.app.PendingIntentStats; 254 import android.app.ProcessMemoryState; 255 import android.app.ProfilerInfo; 256 import android.app.ServiceStartNotAllowedException; 257 import android.app.WaitResult; 258 import android.app.assist.ActivityId; 259 import android.app.backup.BackupAnnotations.BackupDestination; 260 import android.app.backup.IBackupManager; 261 import android.app.compat.CompatChanges; 262 import android.app.job.JobParameters; 263 import android.app.usage.UsageEvents; 264 import android.app.usage.UsageEvents.Event; 265 import android.app.usage.UsageStatsManager; 266 import android.app.usage.UsageStatsManagerInternal; 267 import android.appwidget.AppWidgetManager; 268 import android.appwidget.AppWidgetManagerInternal; 269 import android.compat.annotation.ChangeId; 270 import android.compat.annotation.EnabledSince; 271 import android.content.AttributionSource; 272 import android.content.AutofillOptions; 273 import android.content.BroadcastReceiver; 274 import android.content.ComponentCallbacks2; 275 import android.content.ComponentName; 276 import android.content.ContentCaptureOptions; 277 import android.content.ContentProvider; 278 import android.content.ContentResolver; 279 import android.content.Context; 280 import android.content.Context.BindServiceFlags; 281 import android.content.IIntentReceiver; 282 import android.content.IIntentSender; 283 import android.content.Intent; 284 import android.content.IntentFilter; 285 import android.content.LocusId; 286 import android.content.ServiceConnection; 287 import android.content.pm.ActivityInfo; 288 import android.content.pm.ActivityPresentationInfo; 289 import android.content.pm.ApplicationInfo; 290 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy; 291 import android.content.pm.IPackageDataObserver; 292 import android.content.pm.IPackageManager; 293 import android.content.pm.IncrementalStatesInfo; 294 import android.content.pm.InstrumentationInfo; 295 import android.content.pm.PackageInfo; 296 import android.content.pm.PackageManager; 297 import android.content.pm.PackageManager.NameNotFoundException; 298 import android.content.pm.PackageManagerInternal; 299 import android.content.pm.ParceledListSlice; 300 import android.content.pm.PermissionInfo; 301 import android.content.pm.ProcessInfo; 302 import android.content.pm.ProviderInfo; 303 import android.content.pm.ProviderInfoList; 304 import android.content.pm.ResolveInfo; 305 import android.content.pm.ServiceInfo; 306 import android.content.pm.SharedLibraryInfo; 307 import android.content.pm.TestUtilityService; 308 import android.content.pm.UserInfo; 309 import android.content.pm.UserProperties; 310 import android.content.pm.VersionedPackage; 311 import android.content.res.CompatibilityInfo; 312 import android.content.res.Configuration; 313 import android.content.res.Resources; 314 import android.database.ContentObserver; 315 import android.graphics.Rect; 316 import android.hardware.display.DisplayManager; 317 import android.hardware.display.DisplayManagerInternal; 318 import android.media.audiofx.AudioEffect; 319 import android.net.ConnectivityManager; 320 import android.net.Proxy; 321 import android.net.Uri; 322 import android.os.AppZygote; 323 import android.os.BatteryStats; 324 import android.os.Binder; 325 import android.os.BinderProxy; 326 import android.os.BugreportParams; 327 import android.os.Build; 328 import android.os.Bundle; 329 import android.os.Debug; 330 import android.os.DropBoxManager; 331 import android.os.FactoryTest; 332 import android.os.FileUtils; 333 import android.os.Handler; 334 import android.os.IBinder; 335 import android.os.IDeviceIdentifiersPolicyService; 336 import android.os.IPermissionController; 337 import android.os.IProcessInfoService; 338 import android.os.IProgressListener; 339 import android.os.InputConstants; 340 import android.os.Looper; 341 import android.os.Message; 342 import android.os.Parcel; 343 import android.os.ParcelFileDescriptor; 344 import android.os.PowerExemptionManager; 345 import android.os.PowerExemptionManager.ReasonCode; 346 import android.os.PowerExemptionManager.TempAllowListType; 347 import android.os.PowerManager; 348 import android.os.PowerManager.ServiceType; 349 import android.os.PowerManagerInternal; 350 import android.os.Process; 351 import android.os.RemoteCallback; 352 import android.os.RemoteCallbackList; 353 import android.os.RemoteException; 354 import android.os.ResultReceiver; 355 import android.os.ServiceManager; 356 import android.os.SharedMemory; 357 import android.os.ShellCallback; 358 import android.os.StrictMode; 359 import android.os.SystemClock; 360 import android.os.SystemProperties; 361 import android.os.Trace; 362 import android.os.TransactionTooLargeException; 363 import android.os.UserHandle; 364 import android.os.UserManager; 365 import android.os.WorkSource; 366 import android.os.incremental.IIncrementalService; 367 import android.os.incremental.IncrementalManager; 368 import android.os.incremental.IncrementalMetrics; 369 import android.os.storage.IStorageManager; 370 import android.os.storage.StorageManager; 371 import android.provider.DeviceConfig; 372 import android.provider.Settings; 373 import android.server.ServerProtoEnums; 374 import android.sysprop.InitProperties; 375 import android.system.Os; 376 import android.system.OsConstants; 377 import android.telephony.TelephonyManager; 378 import android.text.TextUtils; 379 import android.text.style.SuggestionSpan; 380 import android.util.ArrayMap; 381 import android.util.ArraySet; 382 import android.util.EventLog; 383 import android.util.FeatureFlagUtils; 384 import android.util.IndentingPrintWriter; 385 import android.util.IntArray; 386 import android.util.Log; 387 import android.util.MathUtils; 388 import android.util.Pair; 389 import android.util.PrintWriterPrinter; 390 import android.util.Slog; 391 import android.util.SparseArray; 392 import android.util.SparseIntArray; 393 import android.util.StatsEvent; 394 import android.util.TimeUtils; 395 import android.util.proto.ProtoOutputStream; 396 import android.util.proto.ProtoUtils; 397 import android.view.Display; 398 import android.view.Gravity; 399 import android.view.LayoutInflater; 400 import android.view.View; 401 import android.view.WindowManager; 402 import android.view.autofill.AutofillManagerInternal; 403 404 import com.android.internal.annotations.CompositeRWLock; 405 import com.android.internal.annotations.GuardedBy; 406 import com.android.internal.annotations.VisibleForTesting; 407 import com.android.internal.app.IAppOpsActiveCallback; 408 import com.android.internal.app.IAppOpsCallback; 409 import com.android.internal.app.IAppOpsService; 410 import com.android.internal.app.ProcessMap; 411 import com.android.internal.app.SystemUserHomeActivity; 412 import com.android.internal.app.procstats.ProcessState; 413 import com.android.internal.app.procstats.ProcessStats; 414 import com.android.internal.content.InstallLocationUtils; 415 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 416 import com.android.internal.notification.SystemNotificationChannels; 417 import com.android.internal.os.BackgroundThread; 418 import com.android.internal.os.BinderCallHeavyHitterWatcher.BinderCallHeavyHitterListener; 419 import com.android.internal.os.BinderCallHeavyHitterWatcher.HeavyHitterContainer; 420 import com.android.internal.os.BinderInternal; 421 import com.android.internal.os.BinderInternal.BinderProxyCountEventListener; 422 import com.android.internal.os.BinderTransactionNameResolver; 423 import com.android.internal.os.ByteTransferPipe; 424 import com.android.internal.os.IResultReceiver; 425 import com.android.internal.os.ProcessCpuTracker; 426 import com.android.internal.os.SomeArgs; 427 import com.android.internal.os.TimeoutRecord; 428 import com.android.internal.os.TransferPipe; 429 import com.android.internal.os.Zygote; 430 import com.android.internal.pm.pkg.parsing.ParsingPackageUtils; 431 import com.android.internal.policy.AttributeCache; 432 import com.android.internal.protolog.common.ProtoLog; 433 import com.android.internal.util.DumpUtils; 434 import com.android.internal.util.FastPrintWriter; 435 import com.android.internal.util.FrameworkStatsLog; 436 import com.android.internal.util.MemInfoReader; 437 import com.android.internal.util.Preconditions; 438 import com.android.server.AlarmManagerInternal; 439 import com.android.server.BootReceiver; 440 import com.android.server.DeviceIdleInternal; 441 import com.android.server.DisplayThread; 442 import com.android.server.IntentResolver; 443 import com.android.server.IoThread; 444 import com.android.server.LocalManagerRegistry; 445 import com.android.server.LocalServices; 446 import com.android.server.LockGuard; 447 import com.android.server.PackageWatchdog; 448 import com.android.server.ServiceThread; 449 import com.android.server.SystemConfig; 450 import com.android.server.SystemService; 451 import com.android.server.SystemServiceManager; 452 import com.android.server.ThreadPriorityBooster; 453 import com.android.server.UserspaceRebootLogger; 454 import com.android.server.Watchdog; 455 import com.android.server.am.ComponentAliasResolver.Resolution; 456 import com.android.server.am.LowMemDetector.MemFactor; 457 import com.android.server.appop.AppOpsService; 458 import com.android.server.compat.PlatformCompat; 459 import com.android.server.contentcapture.ContentCaptureManagerInternal; 460 import com.android.server.criticalevents.CriticalEventLog; 461 import com.android.server.firewall.IntentFirewall; 462 import com.android.server.graphics.fonts.FontManagerInternal; 463 import com.android.server.job.JobSchedulerInternal; 464 import com.android.server.net.NetworkManagementInternal; 465 import com.android.server.os.NativeTombstoneManager; 466 import com.android.server.pm.Computer; 467 import com.android.server.pm.Installer; 468 import com.android.server.pm.SaferIntentUtils; 469 import com.android.server.pm.UserManagerInternal; 470 import com.android.server.pm.permission.PermissionManagerServiceInternal; 471 import com.android.server.pm.pkg.AndroidPackage; 472 import com.android.server.pm.pkg.SELinuxUtil; 473 import com.android.server.pm.snapshot.PackageDataSnapshot; 474 import com.android.server.power.stats.BatteryStatsImpl; 475 import com.android.server.sdksandbox.SdkSandboxManagerLocal; 476 import com.android.server.stats.pull.StatsPullAtomService; 477 import com.android.server.stats.pull.StatsPullAtomServiceInternal; 478 import com.android.server.uri.GrantUri; 479 import com.android.server.uri.NeededUriGrants; 480 import com.android.server.uri.UriGrantsManagerInternal; 481 import com.android.server.utils.AnrTimer; 482 import com.android.server.utils.PriorityDump; 483 import com.android.server.utils.Slogf; 484 import com.android.server.utils.TimingsTraceAndSlog; 485 import com.android.server.vr.VrManagerInternal; 486 import com.android.server.wm.ActivityMetricsLaunchObserver; 487 import com.android.server.wm.ActivityServiceConnectionsHolder; 488 import com.android.server.wm.ActivityTaskManagerInternal; 489 import com.android.server.wm.ActivityTaskManagerService; 490 import com.android.server.wm.WindowManagerInternal; 491 import com.android.server.wm.WindowManagerService; 492 import com.android.server.wm.WindowProcessController; 493 494 import dalvik.annotation.optimization.NeverCompile; 495 import dalvik.system.VMRuntime; 496 497 import libcore.util.EmptyArray; 498 499 import java.io.File; 500 import java.io.FileDescriptor; 501 import java.io.FileNotFoundException; 502 import java.io.FileOutputStream; 503 import java.io.IOException; 504 import java.io.InputStreamReader; 505 import java.io.PrintWriter; 506 import java.time.Instant; 507 import java.time.ZoneId; 508 import java.time.ZonedDateTime; 509 import java.time.format.DateTimeFormatter; 510 import java.util.ArrayList; 511 import java.util.Arrays; 512 import java.util.Collections; 513 import java.util.Comparator; 514 import java.util.HashMap; 515 import java.util.HashSet; 516 import java.util.Iterator; 517 import java.util.LinkedList; 518 import java.util.List; 519 import java.util.Locale; 520 import java.util.Map; 521 import java.util.Objects; 522 import java.util.Set; 523 import java.util.UUID; 524 import java.util.concurrent.CopyOnWriteArrayList; 525 import java.util.concurrent.CountDownLatch; 526 import java.util.concurrent.Executor; 527 import java.util.concurrent.TimeUnit; 528 import java.util.concurrent.atomic.AtomicBoolean; 529 import java.util.concurrent.atomic.AtomicInteger; 530 import java.util.function.BiFunction; 531 import java.util.function.Consumer; 532 533 public class ActivityManagerService extends IActivityManager.Stub 534 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock { 535 536 private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED = 537 "persist.sys.device_provisioned"; 538 539 static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM; 540 static final String TAG_BACKUP = TAG + POSTFIX_BACKUP; 541 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 542 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 543 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION; 544 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; 545 static final String TAG_LRU = TAG + POSTFIX_LRU; 546 static final String TAG_MU = TAG + POSTFIX_MU; 547 static final String TAG_NETWORK = TAG + POSTFIX_NETWORK; 548 static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ; 549 private static final String TAG_POWER = TAG + POSTFIX_POWER; 550 static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES; 551 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 552 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 553 static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS; 554 555 // Mock "pretend we're idle now" broadcast action to the job scheduler; declared 556 // here so that while the job scheduler can depend on AMS, the other way around 557 // need not be the case. 558 public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE"; 559 560 private static final String INTENT_BUGREPORT_REQUESTED = 561 "com.android.internal.intent.action.BUGREPORT_REQUESTED"; 562 private static final String SHELL_APP_PACKAGE = "com.android.shell"; 563 564 // The flags that are set for all calls we make to the package manager. 565 public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 566 567 static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed"; 568 569 // Maximum number of receivers an app can register. 570 private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000; 571 572 // How long we wait for a launched process to attach to the activity manager 573 // before we decide it's never going to come up for real. 574 static final int PROC_START_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 575 576 // How long we wait for a launched process to complete its app startup before we ANR. 577 static final int BIND_APPLICATION_TIMEOUT = 15 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 578 579 // How long we wait to kill an application zygote, after the last process using 580 // it has gone away. 581 static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000; 582 583 // How long we wait for a launched process to attach to the activity manager 584 // before we decide it's never going to come up for real, when the process was 585 // started with a wrapper for instrumentation (such as Valgrind) because it 586 // could take much longer than usual. 587 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 588 589 // How long we allow a receiver to run before giving up on it. 590 static final int BROADCAST_FG_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 591 static final int BROADCAST_BG_TIMEOUT = 60 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 592 593 public static final int MY_PID = myPid(); 594 595 static final String[] EMPTY_STRING_ARRAY = new String[0]; 596 597 // How many bytes to write into the dropbox log before truncating 598 static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024; 599 // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count 600 // as one line, but close enough for now. 601 static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100; 602 603 // How many seconds should the system wait before terminating the spawned logcat process. 604 static final int LOGCAT_TIMEOUT_SEC = 10; 605 606 // Necessary ApplicationInfo flags to mark an app as persistent 607 static final int PERSISTENT_MASK = 608 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT; 609 610 // Intent sent when remote bugreport collection has been completed 611 private static final String INTENT_REMOTE_BUGREPORT_FINISHED = 612 "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED"; 613 614 public static final String DATA_FILE_PATH_HEADER = "Data File: "; 615 public static final String DATA_FILE_PATH_FOOTER = "End Data File\n"; 616 617 // If set, we will push process association information in to procstats. 618 static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true; 619 620 // The minimum memory growth threshold (in KB) for low RAM devices. 621 private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB 622 623 /** 624 * The number of binder proxies we need to have before we start dumping debug info 625 * and kill the offenders. 626 */ 627 private static final int BINDER_PROXY_HIGH_WATERMARK = 6000; 628 629 /** 630 * Low watermark that needs to be met before we consider dumping info again, 631 * after already hitting the high watermark. 632 */ 633 private static final int BINDER_PROXY_LOW_WATERMARK = 5500; 634 635 /** 636 * The number of binder proxies we need to have before we start warning. 637 */ 638 private static final int BINDER_PROXY_WARNING_WATERMARK = 5750; 639 640 // Max character limit for a notification title. If the notification title is larger than this 641 // the notification will not be legible to the user. 642 private static final int MAX_BUGREPORT_TITLE_SIZE = 100; 643 private static final int MAX_BUGREPORT_DESCRIPTION_SIZE = 150; 644 645 private static final DateTimeFormatter DROPBOX_TIME_FORMATTER = 646 DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSZ"); 647 648 OomAdjuster mOomAdjuster; 649 650 static final String EXTRA_TITLE = "android.intent.extra.TITLE"; 651 static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION"; 652 static final String EXTRA_BUGREPORT_TYPE = "android.intent.extra.BUGREPORT_TYPE"; 653 static final String EXTRA_BUGREPORT_NONCE = "android.intent.extra.BUGREPORT_NONCE"; 654 static final String EXTRA_EXTRA_ATTACHMENT_URI = 655 "android.intent.extra.EXTRA_ATTACHMENT_URI"; 656 /** 657 * It is now required for apps to explicitly set either 658 * {@link android.content.Context#RECEIVER_EXPORTED} or 659 * {@link android.content.Context#RECEIVER_NOT_EXPORTED} when registering a receiver for an 660 * unprotected broadcast in code. 661 */ 662 @ChangeId 663 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE) 664 private static final long DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED = 161145287L; 665 666 /** 667 * The maximum number of bytes that {@link #setProcessStateSummary} accepts. 668 * 669 * @see {@link android.app.ActivityManager#setProcessStateSummary(byte[])} 670 */ 671 static final int MAX_STATE_DATA_SIZE = 128; 672 673 /** All system services */ 674 SystemServiceManager mSystemServiceManager; 675 676 private Installer mInstaller; 677 678 final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter(); 679 680 @CompositeRWLock({"this", "mProcLock"}) 681 final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>(); 682 683 public final IntentFirewall mIntentFirewall; 684 685 /** 686 * The global lock for AMS, it's de-facto the ActivityManagerService object as of now. 687 */ 688 final ActivityManagerGlobalLock mGlobalLock = ActivityManagerService.this; 689 690 /** 691 * Whether or not to enable the {@link #mProcLock}. If {@code false}, the {@link #mProcLock} 692 * will be equivalent to the {@link #mGlobalLock}. 693 */ 694 private static final boolean ENABLE_PROC_LOCK = true; 695 696 /** 697 * The lock for process management. 698 * 699 * <p> 700 * This lock is widely used in conjunction with the {@link #mGlobalLock} at present, 701 * where it'll require any of the locks to read from a data class, and both of the locks 702 * to write into that data class. 703 * 704 * For the naming convention of function suffixes: 705 * <ul> 706 * <li>-LOSP: Locked with any Of global am Service or Process lock</li> 707 * <li>-LSP: Locked with both of global am Service and Process lock</li> 708 * <li>-Locked: Locked with global am service lock alone</li> 709 * <li>-LPr: Locked with Process lock alone</li> 710 * </ul> 711 * For the simplicity, the getters/setters of the fields in data classes usually don't end with 712 * the above suffixes even if they're guarded by the locks here. 713 * </p> 714 * 715 * <p> 716 * In terms of locking order, it should be right below to the {@link #mGlobalLock}, 717 * and above everything else which used to be underneath the {@link #mGlobalLock}. 718 * As of today, the core components(services/providers/broadcasts) are still guarded by 719 * the {@link #mGlobalLock} alone, so be cautious, avoid from acquiring the {@link #mGlobalLock} 720 * while holding this lock. 721 * </p> 722 * 723 */ 724 final ActivityManagerGlobalLock mProcLock = ENABLE_PROC_LOCK 725 ? new ActivityManagerProcLock() : mGlobalLock; 726 727 // Whether we should use SCHED_FIFO for UI and RenderThreads. 728 final boolean mUseFifoUiScheduling; 729 730 /** Whether some specified important processes are allowed to use FIFO priority. */ 731 boolean mAllowSpecifiedFifoScheduling = true; 732 733 @GuardedBy("this") 734 private final SparseArray<IUnsafeIntentStrictModeCallback> 735 mStrictModeCallbacks = new SparseArray<>(); 736 737 // Convenient for easy iteration over the queues. Foreground is first 738 // so that dispatch of foreground broadcasts gets precedence. 739 private BroadcastQueue mBroadcastQueue; 740 741 @GuardedBy("this") 742 BroadcastStats mLastBroadcastStats; 743 744 @GuardedBy("this") 745 BroadcastStats mCurBroadcastStats; 746 747 TraceErrorLogger mTraceErrorLogger; 748 749 private volatile int mDeviceOwnerUid = INVALID_UID; 750 751 /** 752 * Map userId to its companion app uids. 753 */ 754 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>(); 755 756 /** 757 * The profile owner UIDs. 758 */ 759 private ArraySet<Integer> mProfileOwnerUids = null; 760 761 final UserController mUserController; 762 @VisibleForTesting 763 public final PendingIntentController mPendingIntentController; 764 765 final AppErrors mAppErrors; 766 final PackageWatchdog mPackageWatchdog; 767 768 @GuardedBy("mDeliveryGroupPolicyIgnoredActions") 769 private final ArraySet<String> mDeliveryGroupPolicyIgnoredActions = new ArraySet(); 770 771 private AccessCheckDelegateHelper mAccessCheckDelegateHelper; 772 773 /** 774 * Uids of apps with current active camera sessions. Access synchronized on 775 * the IntArray instance itself, and no other locks must be acquired while that 776 * one is held. 777 */ 778 @GuardedBy("mActiveCameraUids") 779 final IntArray mActiveCameraUids = new IntArray(4); 780 781 /** 782 * Helper class which strips out priority and proto arguments then calls the dump function with 783 * the appropriate arguments. If priority arguments are omitted, function calls the legacy 784 * dump command. 785 * If priority arguments are omitted all sections are dumped, otherwise sections are dumped 786 * according to their priority. 787 */ 788 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() { 789 @Override 790 public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args, 791 boolean asProto) { 792 if (asProto) return; 793 doDump(fd, pw, new String[]{"activities"}, asProto); 794 doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto); 795 } 796 797 @Override 798 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 799 doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto); 800 } 801 802 @Override 803 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 804 doDump(fd, pw, args, asProto); 805 } 806 }; 807 808 private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster( 809 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY); 810 boostPriorityForLockedSection()811 static void boostPriorityForLockedSection() { 812 sThreadPriorityBooster.boost(); 813 } 814 resetPriorityAfterLockedSection()815 static void resetPriorityAfterLockedSection() { 816 sThreadPriorityBooster.reset(); 817 } 818 819 private static ThreadPriorityBooster sProcThreadPriorityBooster = new ThreadPriorityBooster( 820 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_PROC); 821 boostPriorityForProcLockedSection()822 static void boostPriorityForProcLockedSection() { 823 if (ENABLE_PROC_LOCK) { 824 sProcThreadPriorityBooster.boost(); 825 } else { 826 sThreadPriorityBooster.boost(); 827 } 828 } 829 resetPriorityAfterProcLockedSection()830 static void resetPriorityAfterProcLockedSection() { 831 if (ENABLE_PROC_LOCK) { 832 sProcThreadPriorityBooster.reset(); 833 } else { 834 sThreadPriorityBooster.reset(); 835 } 836 } 837 838 /** 839 * Process management. 840 */ 841 final ProcessList mProcessList; 842 843 /** 844 * The list of phantom processes. 845 * @see PhantomProcessRecord 846 */ 847 final PhantomProcessList mPhantomProcessList; 848 849 /** 850 * Tracking long-term execution of processes to look for abuse and other 851 * bad app behavior. 852 */ 853 final ProcessStatsService mProcessStats; 854 855 /** 856 * Non-persistent appId allowlist for background restrictions 857 */ 858 @CompositeRWLock({"this", "mProcLock"}) 859 private int[] mBackgroundAppIdAllowlist = new int[] { 860 BLUETOOTH_UID 861 }; 862 863 /** 864 * Broadcast actions that will always be deliverable to unlaunched/background apps 865 */ 866 @GuardedBy("this") 867 private ArraySet<String> mBackgroundLaunchBroadcasts; 868 869 /** 870 * When an app has restrictions on the other apps that can have associations with it, 871 * it appears here with a set of the allowed apps and also track debuggability of the app. 872 */ 873 @GuardedBy("this") 874 private ArrayMap<String, PackageAssociationInfo> mAllowedAssociations; 875 876 @GuardedBy("this") 877 final ComponentAliasResolver mComponentAliasResolver; 878 879 private static final long HOME_LAUNCH_TIMEOUT_MS = 15000; 880 private final AtomicBoolean mHasHomeDelay = new AtomicBoolean(false); 881 882 /** 883 * Tracks all users with computed color resources by ThemeOverlaycvontroller 884 */ 885 @GuardedBy("this") 886 private final Set<Integer> mThemeOverlayReadyUsers = new HashSet<>(); 887 888 /** 889 * Tracks association information for a particular package along with debuggability. 890 * <p> Associations for a package A are allowed to package B if B is part of the 891 * allowed associations for A or if A is debuggable. 892 */ 893 private final class PackageAssociationInfo { 894 private final String mSourcePackage; 895 private final ArraySet<String> mAllowedPackageAssociations; 896 private boolean mIsDebuggable; 897 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)898 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, 899 boolean isDebuggable) { 900 mSourcePackage = sourcePackage; 901 mAllowedPackageAssociations = allowedPackages; 902 mIsDebuggable = isDebuggable; 903 } 904 905 /** 906 * Returns true if {@code mSourcePackage} is allowed association with 907 * {@code targetPackage}. 908 */ isPackageAssociationAllowed(String targetPackage)909 boolean isPackageAssociationAllowed(String targetPackage) { 910 return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage); 911 } 912 isDebuggable()913 boolean isDebuggable() { 914 return mIsDebuggable; 915 } 916 setDebuggable(boolean isDebuggable)917 void setDebuggable(boolean isDebuggable) { 918 mIsDebuggable = isDebuggable; 919 } 920 getAllowedPackageAssociations()921 ArraySet<String> getAllowedPackageAssociations() { 922 return mAllowedPackageAssociations; 923 } 924 } 925 926 /** 927 * These are the currently running processes for which we have a ProcessInfo. 928 * Note: needs to be static since the permission checking call chain is static. This 929 * all probably should be refactored into a separate permission checking object. 930 */ 931 @GuardedBy("sActiveProcessInfoSelfLocked") 932 static final SparseArray<ProcessInfo> sActiveProcessInfoSelfLocked = new SparseArray<>(); 933 934 /** 935 * All of the processes we currently have running organized by pid. 936 * The keys are the pid running the application. 937 * 938 * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock! 939 */ 940 final PidMap mPidsSelfLocked = new PidMap(); 941 static final class PidMap { 942 private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>(); 943 get(int pid)944 ProcessRecord get(int pid) { 945 return mPidMap.get(pid); 946 } 947 size()948 int size() { 949 return mPidMap.size(); 950 } 951 valueAt(int index)952 ProcessRecord valueAt(int index) { 953 return mPidMap.valueAt(index); 954 } 955 keyAt(int index)956 int keyAt(int index) { 957 return mPidMap.keyAt(index); 958 } 959 indexOfKey(int key)960 int indexOfKey(int key) { 961 return mPidMap.indexOfKey(key); 962 } 963 doAddInternal(int pid, ProcessRecord app)964 void doAddInternal(int pid, ProcessRecord app) { 965 mPidMap.put(pid, app); 966 } 967 doRemoveInternal(int pid, ProcessRecord app)968 boolean doRemoveInternal(int pid, ProcessRecord app) { 969 final ProcessRecord existingApp = mPidMap.get(pid); 970 if (existingApp != null && existingApp.getStartSeq() == app.getStartSeq()) { 971 mPidMap.remove(pid); 972 return true; 973 } 974 return false; 975 } 976 } 977 978 private final PendingStartActivityUids mPendingStartActivityUids; 979 980 /** 981 * Puts the process record in the map. 982 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 983 * method. 984 */ 985 @GuardedBy("this") addPidLocked(ProcessRecord app)986 void addPidLocked(ProcessRecord app) { 987 final int pid = app.getPid(); 988 synchronized (mPidsSelfLocked) { 989 mPidsSelfLocked.doAddInternal(pid, app); 990 } 991 synchronized (sActiveProcessInfoSelfLocked) { 992 if (app.processInfo != null) { 993 sActiveProcessInfoSelfLocked.put(pid, app.processInfo); 994 } else { 995 sActiveProcessInfoSelfLocked.remove(pid); 996 } 997 } 998 mAtmInternal.onProcessMapped(pid, app.getWindowProcessController()); 999 } 1000 1001 /** 1002 * Removes the process record from the map. 1003 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 1004 * method. 1005 */ 1006 @GuardedBy("this") removePidLocked(int pid, ProcessRecord app)1007 boolean removePidLocked(int pid, ProcessRecord app) { 1008 final boolean removed; 1009 synchronized (mPidsSelfLocked) { 1010 removed = mPidsSelfLocked.doRemoveInternal(pid, app); 1011 } 1012 if (removed) { 1013 synchronized (sActiveProcessInfoSelfLocked) { 1014 sActiveProcessInfoSelfLocked.remove(pid); 1015 } 1016 mAtmInternal.onProcessUnMapped(pid); 1017 } 1018 return removed; 1019 } 1020 1021 /** 1022 * All of the processes that have been forced to be important. The key 1023 * is the pid of the caller who requested it (we hold a death 1024 * link on it). 1025 */ 1026 abstract class ImportanceToken implements IBinder.DeathRecipient { 1027 final int pid; 1028 final IBinder token; 1029 final String reason; 1030 ImportanceToken(int _pid, IBinder _token, String _reason)1031 ImportanceToken(int _pid, IBinder _token, String _reason) { 1032 pid = _pid; 1033 token = _token; 1034 reason = _reason; 1035 } 1036 1037 @Override toString()1038 public String toString() { 1039 return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this)) 1040 + " " + reason + " " + pid + " " + token + " }"; 1041 } 1042 dumpDebug(ProtoOutputStream proto, long fieldId)1043 void dumpDebug(ProtoOutputStream proto, long fieldId) { 1044 final long pToken = proto.start(fieldId); 1045 proto.write(ImportanceTokenProto.PID, pid); 1046 if (token != null) { 1047 proto.write(ImportanceTokenProto.TOKEN, token.toString()); 1048 } 1049 proto.write(ImportanceTokenProto.REASON, reason); 1050 proto.end(pToken); 1051 } 1052 } 1053 @GuardedBy("this") 1054 final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>(); 1055 1056 /** The processes that are allowed to use SCHED_FIFO prorioty. */ 1057 @GuardedBy("mProcLock") 1058 final ArrayList<ProcessRecord> mSpecifiedFifoProcesses = new ArrayList<>(); 1059 1060 /** 1061 * List of records for processes that someone had tried to start before the 1062 * system was ready. We don't start them at that point, but ensure they 1063 * are started by the time booting is complete. 1064 */ 1065 @GuardedBy("this") 1066 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 1067 1068 /** 1069 * List of persistent applications that are in the process 1070 * of being started. 1071 */ 1072 @GuardedBy("this") 1073 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 1074 1075 private final ActivityMetricsLaunchObserver mActivityLaunchObserver = 1076 new ActivityMetricsLaunchObserver() { 1077 1078 @Override 1079 public void onIntentStarted(@NonNull Intent intent, long timestampNanos) { 1080 synchronized (this) { 1081 mProcessList.getAppStartInfoTracker().onIntentStarted(intent, timestampNanos); 1082 } 1083 } 1084 1085 @Override 1086 public void onIntentFailed(long id) { 1087 mProcessList.getAppStartInfoTracker().onIntentFailed(id); 1088 } 1089 1090 @Override 1091 public void onActivityLaunched(long id, ComponentName name, int temperature, int userId) { 1092 mAppProfiler.onActivityLaunched(); 1093 synchronized (ActivityManagerService.this) { 1094 ProcessRecord record = null; 1095 try { 1096 record = getProcessRecordLocked(name.getPackageName(), mContext 1097 .getPackageManager().getPackageUidAsUser(name.getPackageName(), 0, 1098 userId)); 1099 } catch (NameNotFoundException nnfe) { 1100 // Ignore, record will be lost. 1101 } 1102 mProcessList.getAppStartInfoTracker().onActivityLaunched(id, name, temperature, 1103 record); 1104 } 1105 } 1106 1107 @Override 1108 public void onActivityLaunchCancelled(long id) { 1109 mProcessList.getAppStartInfoTracker().onActivityLaunchCancelled(id); 1110 } 1111 1112 @Override 1113 public void onActivityLaunchFinished(long id, ComponentName name, long timestampNanos, 1114 int launchMode) { 1115 mProcessList.getAppStartInfoTracker().onActivityLaunchFinished(id, name, 1116 timestampNanos, launchMode); 1117 } 1118 1119 @Override 1120 public void onReportFullyDrawn(long id, long timestampNanos) { 1121 mProcessList.getAppStartInfoTracker().onReportFullyDrawn(id, timestampNanos); 1122 } 1123 }; 1124 1125 private volatile boolean mBinderTransactionTrackingEnabled = false; 1126 1127 /** 1128 * Fingerprints (hashCode()) of stack traces that we've 1129 * already logged DropBox entries for. Guarded by itself. If 1130 * something (rogue user app) forces this over 1131 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 1132 */ 1133 @GuardedBy("mAlreadyLoggedViolatedStacks") 1134 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 1135 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 1136 1137 /** 1138 * Keeps track of all IIntentReceivers that have been registered for broadcasts. 1139 * Hash keys are the receiver IBinder, hash value is a ReceiverList. 1140 */ 1141 @GuardedBy("this") 1142 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>(); 1143 1144 /** 1145 * Resolver for broadcast intents to registered receivers. 1146 * Holds BroadcastFilter (subclass of IntentFilter). 1147 */ 1148 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 1149 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 1150 @Override 1151 protected boolean allowFilterResult( 1152 BroadcastFilter filter, List<BroadcastFilter> dest) { 1153 IBinder target = filter.receiverList.receiver.asBinder(); 1154 for (int i = dest.size() - 1; i >= 0; i--) { 1155 if (dest.get(i).receiverList.receiver.asBinder() == target) { 1156 return false; 1157 } 1158 } 1159 return true; 1160 } 1161 1162 @Override 1163 protected BroadcastFilter newResult(@NonNull Computer computer, BroadcastFilter filter, 1164 int match, int userId, long customFlags) { 1165 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 1166 || userId == filter.owningUserId) { 1167 return super.newResult(computer, filter, match, userId, customFlags); 1168 } 1169 return null; 1170 } 1171 1172 @Override 1173 protected IntentFilter getIntentFilter(@NonNull BroadcastFilter input) { 1174 return input; 1175 } 1176 1177 @Override 1178 protected BroadcastFilter[] newArray(int size) { 1179 return new BroadcastFilter[size]; 1180 } 1181 1182 @Override 1183 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 1184 return packageName.equals(filter.packageName); 1185 } 1186 }; 1187 1188 /** 1189 * State of all active sticky broadcasts per user. Keys are the action of the 1190 * sticky Intent, values are an ArrayList of all broadcasted intents with 1191 * that action (which should usually be one). The SparseArray is keyed 1192 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 1193 * for stickies that are sent to all users. 1194 */ 1195 @GuardedBy("mStickyBroadcasts") 1196 final SparseArray<ArrayMap<String, ArrayList<StickyBroadcast>>> mStickyBroadcasts = 1197 new SparseArray<>(); 1198 1199 @VisibleForTesting 1200 static final class StickyBroadcast { 1201 public Intent intent; 1202 public boolean deferUntilActive; 1203 public int originalCallingUid; 1204 /** The snapshot process state of the app who sent this broadcast */ 1205 public int originalCallingAppProcessState; 1206 public String resolvedDataType; 1207 create(Intent intent, boolean deferUntilActive, int originalCallingUid, int originalCallingAppProcessState, String resolvedDataType)1208 public static StickyBroadcast create(Intent intent, boolean deferUntilActive, 1209 int originalCallingUid, int originalCallingAppProcessState, 1210 String resolvedDataType) { 1211 final StickyBroadcast b = new StickyBroadcast(); 1212 b.intent = intent; 1213 b.deferUntilActive = deferUntilActive; 1214 b.originalCallingUid = originalCallingUid; 1215 b.originalCallingAppProcessState = originalCallingAppProcessState; 1216 b.resolvedDataType = resolvedDataType; 1217 return b; 1218 } 1219 1220 @Override toString()1221 public String toString() { 1222 return "{intent=" + intent + ", defer=" + deferUntilActive + ", originalCallingUid=" 1223 + originalCallingUid + ", originalCallingAppProcessState=" 1224 + originalCallingAppProcessState + ", type=" + resolvedDataType + "}"; 1225 } 1226 } 1227 1228 final ActiveServices mServices; 1229 1230 final static class Association { 1231 final int mSourceUid; 1232 final String mSourceProcess; 1233 final int mTargetUid; 1234 final ComponentName mTargetComponent; 1235 final String mTargetProcess; 1236 1237 int mCount; 1238 long mTime; 1239 1240 int mNesting; 1241 long mStartTime; 1242 1243 // states of the source process when the bind occurred. 1244 int mLastState = ActivityManager.MAX_PROCESS_STATE + 1; 1245 long mLastStateUptime; 1246 long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE 1247 - ActivityManager.MIN_PROCESS_STATE+1]; 1248 Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1249 Association(int sourceUid, String sourceProcess, int targetUid, 1250 ComponentName targetComponent, String targetProcess) { 1251 mSourceUid = sourceUid; 1252 mSourceProcess = sourceProcess; 1253 mTargetUid = targetUid; 1254 mTargetComponent = targetComponent; 1255 mTargetProcess = targetProcess; 1256 } 1257 } 1258 1259 /** 1260 * When service association tracking is enabled, this is all of the associations we 1261 * have seen. Mapping is target uid -> target component -> source uid -> source process name 1262 * -> association data. 1263 */ 1264 @GuardedBy("this") 1265 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>> 1266 mAssociations = new SparseArray<>(); 1267 boolean mTrackingAssociations; 1268 1269 /** 1270 * Backup/restore process management 1271 */ 1272 @GuardedBy("this") 1273 final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>(); 1274 1275 final ContentProviderHelper mCpHelper; 1276 1277 CoreSettingsObserver mCoreSettingsObserver; 1278 1279 /** 1280 * All information we have collected about the runtime performance of 1281 * any user id that can impact battery performance. 1282 */ 1283 final BatteryStatsService mBatteryStatsService; 1284 1285 StatsPullAtomServiceInternal mStatsPullAtomServiceInternal; 1286 1287 /** 1288 * Information about component usage 1289 */ 1290 volatile UsageStatsManagerInternal mUsageStatsService; 1291 1292 /** 1293 * Access to DeviceIdleController service. 1294 */ 1295 DeviceIdleInternal mLocalDeviceIdleController; 1296 1297 /** 1298 * Power-save allowlisted app-ids (not including except-idle-allowlisted ones). 1299 */ 1300 @CompositeRWLock({"this", "mProcLock"}) 1301 int[] mDeviceIdleAllowlist = new int[0]; 1302 1303 /** 1304 * Power-save allowlisted app-ids (including except-idle-allowlisted ones). 1305 */ 1306 @CompositeRWLock({"this", "mProcLock"}) 1307 int[] mDeviceIdleExceptIdleAllowlist = new int[0]; 1308 1309 /** 1310 * Set of app ids that are temporarily allowed to escape bg check due to high-pri message 1311 */ 1312 @CompositeRWLock({"this", "mProcLock"}) 1313 int[] mDeviceIdleTempAllowlist = new int[0]; 1314 1315 static final class PendingTempAllowlist { 1316 final int targetUid; 1317 final long duration; 1318 final String tag; 1319 final int type; 1320 final @ReasonCode int reasonCode; 1321 final int callingUid; 1322 PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, int type, int callingUid)1323 PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, 1324 int type, int callingUid) { 1325 this.targetUid = targetUid; 1326 this.duration = duration; 1327 this.tag = tag; 1328 this.type = type; 1329 this.reasonCode = reasonCode; 1330 this.callingUid = callingUid; 1331 } 1332 dumpDebug(ProtoOutputStream proto, long fieldId)1333 void dumpDebug(ProtoOutputStream proto, long fieldId) { 1334 final long token = proto.start(fieldId); 1335 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID, 1336 targetUid); 1337 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS, 1338 duration); 1339 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag); 1340 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TYPE, type); 1341 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.REASON_CODE, 1342 reasonCode); 1343 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.CALLING_UID, 1344 callingUid); 1345 proto.end(token); 1346 } 1347 } 1348 1349 @CompositeRWLock({"this", "mProcLock"}) 1350 final PendingTempAllowlists mPendingTempAllowlist = new PendingTempAllowlists(this); 1351 1352 public static final class FgsTempAllowListItem { 1353 final long mDuration; 1354 final @PowerExemptionManager.ReasonCode int mReasonCode; 1355 final String mReason; 1356 final int mCallingUid; 1357 FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, String reason, int callingUid)1358 FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, 1359 String reason, int callingUid) { 1360 mDuration = duration; 1361 mReasonCode = reasonCode; 1362 mReason = reason; 1363 mCallingUid = callingUid; 1364 } 1365 dump(PrintWriter pw)1366 void dump(PrintWriter pw) { 1367 pw.print(" duration=" + mDuration + 1368 " callingUid=" + UserHandle.formatUid(mCallingUid) + 1369 " reasonCode=" + PowerExemptionManager.reasonCodeToString(mReasonCode) + 1370 " reason=" + mReason); 1371 } 1372 } 1373 1374 /** 1375 * The temp-allowlist that is allowed to start FGS from background. 1376 */ 1377 @CompositeRWLock({"this", "mProcLock"}) 1378 final FgsTempAllowList<FgsTempAllowListItem> mFgsStartTempAllowList = 1379 new FgsTempAllowList(); 1380 1381 static final FgsTempAllowListItem FAKE_TEMP_ALLOW_LIST_ITEM = new FgsTempAllowListItem( 1382 Long.MAX_VALUE, REASON_SYSTEM_ALLOW_LISTED, "", INVALID_UID); 1383 1384 /* 1385 * List of uids that are allowed to have while-in-use permission when FGS is started from 1386 * background. 1387 */ 1388 private final FgsTempAllowList<String> mFgsWhileInUseTempAllowList = 1389 new FgsTempAllowList(); 1390 1391 /** 1392 * Information about and control over application operations 1393 */ 1394 final AppOpsService mAppOpsService; 1395 private AppOpsManager mAppOpsManager; 1396 1397 /** 1398 * List of initialization arguments to pass to all processes when binding applications to them. 1399 * For example, references to the commonly used services. 1400 */ 1401 ArrayMap<String, IBinder> mAppBindArgs; 1402 ArrayMap<String, IBinder> mIsolatedAppBindArgs; 1403 1404 volatile boolean mProcessesReady = false; 1405 volatile boolean mSystemReady = false; 1406 volatile boolean mOnBattery = false; 1407 final int mFactoryTest; 1408 volatile boolean mBooting = false; 1409 1410 @GuardedBy("this") boolean mCallFinishBooting = false; 1411 @GuardedBy("this") boolean mBootAnimationComplete = false; 1412 1413 final Context mContext; 1414 1415 /** 1416 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can 1417 * change at runtime. Use mContext for non-UI purposes. 1418 */ 1419 final Context mUiContext; 1420 1421 /** 1422 * Last time (in uptime) at which we checked for power usage. 1423 */ 1424 @GuardedBy("mProcLock") 1425 long mLastPowerCheckUptime; 1426 1427 /** 1428 * For some direct access we need to power manager. 1429 */ 1430 PowerManagerInternal mLocalPowerManager; 1431 1432 /** 1433 * State of external calls telling us if the device is awake or asleep. 1434 */ 1435 AtomicInteger mWakefulness = new AtomicInteger(PowerManagerInternal.WAKEFULNESS_AWAKE); 1436 1437 /** 1438 * The uptime of the last time we performed idle maintenance. 1439 */ 1440 @GuardedBy("mProcLock") 1441 long mLastIdleTime = SystemClock.uptimeMillis(); 1442 1443 /** 1444 * For reporting to battery stats the current top application. 1445 * 1446 * <p>It has its own lock to avoid from the need of double locking if using the global 1447 * ActivityManagerService lock and proc lock to guard it.</p> 1448 */ 1449 @GuardedBy("mCurResumedAppLock") 1450 private String mCurResumedPackage = null; 1451 1452 @GuardedBy("mCurResumedAppLock") 1453 private int mCurResumedUid = -1; 1454 1455 /** 1456 * Dedicated lock for {@link #mCurResumedPackage} and {@link #mCurResumedUid}. 1457 */ 1458 private final Object mCurResumedAppLock = new Object(); 1459 1460 /** 1461 * For reporting to battery stats the apps currently running foreground 1462 * service. The ProcessMap is package/uid tuples; each of these contain 1463 * an array of the currently foreground processes. 1464 */ 1465 @GuardedBy("this") 1466 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1467 = new ProcessMap<ArrayList<ProcessRecord>>(); 1468 1469 /** 1470 * The list of foreground service state change listeners. 1471 */ 1472 @GuardedBy("this") 1473 final ArrayList<ForegroundServiceStateListener> mForegroundServiceStateListeners = 1474 new ArrayList<>(); 1475 1476 /** 1477 * The list of broadcast event listeners. 1478 */ 1479 final CopyOnWriteArrayList<BroadcastEventListener> mBroadcastEventListeners = 1480 new CopyOnWriteArrayList<>(); 1481 1482 /** 1483 * The list of bind service event listeners. 1484 */ 1485 final CopyOnWriteArrayList<BindServiceEventListener> mBindServiceEventListeners = 1486 new CopyOnWriteArrayList<>(); 1487 1488 /** 1489 * Set if the systemServer made a call to enterSafeMode. 1490 */ 1491 @GuardedBy("this") 1492 boolean mSafeMode; 1493 1494 @GuardedBy("this") 1495 private String mDebugApp = null; 1496 1497 @GuardedBy("this") 1498 private boolean mWaitForDebugger = false; 1499 1500 @GuardedBy("this") 1501 private boolean mSuspendUponWait = false; 1502 1503 @GuardedBy("this") 1504 private boolean mDebugTransient = false; 1505 1506 @GuardedBy("this") 1507 private String mOrigDebugApp = null; 1508 1509 @GuardedBy("this") 1510 private boolean mOrigWaitForDebugger = false; 1511 1512 @GuardedBy("this") 1513 boolean mAlwaysFinishActivities = false; 1514 1515 @GuardedBy("mProcLock") 1516 private String mTrackAllocationApp = null; 1517 1518 @GuardedBy("this") 1519 String mNativeDebuggingApp = null; 1520 1521 final Injector mInjector; 1522 1523 static final class ProcessChangeItem { 1524 static final int CHANGE_ACTIVITIES = 1<<0; 1525 static final int CHANGE_FOREGROUND_SERVICES = 1<<1; 1526 int changes; 1527 int uid; 1528 int pid; 1529 int processState; 1530 boolean foregroundActivities; 1531 int foregroundServiceTypes; 1532 } 1533 1534 @GuardedBy("mOomAdjObserverLock") 1535 OomAdjObserver mCurOomAdjObserver; 1536 1537 @GuardedBy("mOomAdjObserverLock") 1538 int mCurOomAdjUid; 1539 1540 /** 1541 * Dedicated lock for {@link #mCurOomAdjObserver} and {@link #mCurOomAdjUid}. 1542 */ 1543 final Object mOomAdjObserverLock = new Object(); 1544 1545 interface OomAdjObserver { onOomAdjMessage(String msg)1546 void onOomAdjMessage(String msg); 1547 } 1548 1549 final AnrHelper mAnrHelper = new AnrHelper(this); 1550 1551 /** Set to true after the system has finished booting. */ 1552 volatile boolean mBooted = false; 1553 1554 /** 1555 * Current boot phase. 1556 */ 1557 int mBootPhase; 1558 1559 /** 1560 * The time stamp that all apps have received BOOT_COMPLETED. 1561 */ 1562 volatile long mBootCompletedTimestamp; 1563 1564 @GuardedBy("this") 1565 boolean mDeterministicUidIdle = false; 1566 1567 @VisibleForTesting 1568 public WindowManagerService mWindowManager; 1569 WindowManagerInternal mWmInternal; 1570 @VisibleForTesting 1571 public ActivityTaskManagerService mActivityTaskManager; 1572 @VisibleForTesting 1573 public ActivityTaskManagerInternal mAtmInternal; 1574 UriGrantsManagerInternal mUgmInternal; 1575 @VisibleForTesting 1576 public final ActivityManagerInternal mInternal; 1577 final ActivityThread mSystemThread; 1578 1579 final UidObserverController mUidObserverController; 1580 private volatile IUidObserver mNetworkPolicyUidObserver; 1581 1582 @GuardedBy("mUidNetworkBlockedReasons") 1583 private final SparseIntArray mUidNetworkBlockedReasons = new SparseIntArray(); 1584 1585 final AppRestrictionController mAppRestrictionController; 1586 1587 /** 1588 * The collection of the MediaProjection tokens per UID, for the apps that are allowed to 1589 * start FGS with the type "mediaProjection"; this permission is granted via the request over 1590 * the call to {@link android.media.project.MediaProjectionManager#createScreenCaptureIntent()}. 1591 * 1592 * <p>Note, the "token" here is actually an instance of 1593 * {@link android.media.projection.IMediaProjection}.</p> 1594 */ 1595 @GuardedBy("mMediaProjectionTokenMap") 1596 private final SparseArray<ArraySet<IBinder>> mMediaProjectionTokenMap = new SparseArray(); 1597 1598 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1599 final ProcessRecord mApp; 1600 final int mPid; 1601 final IApplicationThread mAppThread; 1602 AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1603 AppDeathRecipient(ProcessRecord app, int pid, 1604 IApplicationThread thread) { 1605 if (DEBUG_ALL) Slog.v( 1606 TAG, "New death recipient " + this 1607 + " for thread " + thread.asBinder()); 1608 mApp = app; 1609 mPid = pid; 1610 mAppThread = thread; 1611 } 1612 1613 @Override binderDied()1614 public void binderDied() { 1615 if (DEBUG_ALL) Slog.v( 1616 TAG, "Death received in " + this 1617 + " for thread " + mAppThread.asBinder()); 1618 synchronized(ActivityManagerService.this) { 1619 appDiedLocked(mApp, mPid, mAppThread, true, null); 1620 } 1621 } 1622 } 1623 1624 static final int SHOW_ERROR_UI_MSG = 1; 1625 static final int SHOW_NOT_RESPONDING_UI_MSG = 2; 1626 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1627 static final int WAIT_FOR_DEBUGGER_UI_MSG = 6; 1628 static final int SERVICE_TIMEOUT_MSG = 12; 1629 static final int UPDATE_TIME_ZONE = 13; 1630 static final int PROC_START_TIMEOUT_MSG = 20; 1631 static final int KILL_APPLICATION_MSG = 22; 1632 static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26; 1633 static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27; 1634 static final int CLEAR_DNS_CACHE_MSG = 28; 1635 static final int UPDATE_HTTP_PROXY_MSG = 29; 1636 static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31; 1637 static final int DISPATCH_PROCESS_DIED_UI_MSG = 32; 1638 static final int REPORT_MEM_USAGE_MSG = 33; 1639 static final int UPDATE_TIME_PREFERENCE_MSG = 41; 1640 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49; 1641 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50; 1642 static final int ABORT_DUMPHEAP_MSG = 51; 1643 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56; 1644 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57; 1645 static final int IDLE_UIDS_MSG = 58; 1646 static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63; 1647 static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66; 1648 static final int SERVICE_FOREGROUND_TIMEOUT_ANR_MSG = 67; 1649 static final int PUSH_TEMP_ALLOWLIST_UI_MSG = 68; 1650 static final int SERVICE_FOREGROUND_CRASH_MSG = 69; 1651 static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70; 1652 static final int KILL_APP_ZYGOTE_MSG = 71; 1653 static final int BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG = 72; 1654 static final int WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG = 73; 1655 static final int DISPATCH_SENDING_BROADCAST_EVENT = 74; 1656 static final int DISPATCH_BINDING_SERVICE_EVENT = 75; 1657 static final int SERVICE_SHORT_FGS_TIMEOUT_MSG = 76; 1658 static final int SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG = 77; 1659 static final int SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG = 78; 1660 static final int UPDATE_CACHED_APP_HIGH_WATERMARK = 79; 1661 static final int ADD_UID_TO_OBSERVER_MSG = 80; 1662 static final int REMOVE_UID_FROM_OBSERVER_MSG = 81; 1663 static final int BIND_APPLICATION_TIMEOUT_SOFT_MSG = 82; 1664 static final int BIND_APPLICATION_TIMEOUT_HARD_MSG = 83; 1665 static final int SERVICE_FGS_TIMEOUT_MSG = 84; 1666 static final int SERVICE_FGS_CRASH_TIMEOUT_MSG = 85; 1667 static final int FOLLOW_UP_OOMADJUSTER_UPDATE_MSG = 86; 1668 1669 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1670 1671 /** 1672 * Flag whether the current user is a "monkey", i.e. whether 1673 * the UI is driven by a UI automation tool. 1674 */ 1675 private volatile boolean mUserIsMonkey; 1676 1677 @VisibleForTesting 1678 public final ServiceThread mHandlerThread; 1679 final MainHandler mHandler; 1680 final Handler mUiHandler; 1681 final ServiceThread mProcStartHandlerThread; 1682 final ProcStartHandler mProcStartHandler; 1683 1684 ActivityManagerConstants mConstants; 1685 1686 // Encapsulates the global setting "hidden_api_blacklist_exemptions" 1687 final HiddenApiSettings mHiddenApiBlacklist; 1688 1689 private final PlatformCompat mPlatformCompat; 1690 1691 PackageManagerInternal mPackageManagerInt; 1692 PermissionManagerServiceInternal mPermissionManagerInt; 1693 private TestUtilityService mTestUtilityService; 1694 1695 // Packages which have received a (LOCKED_)BOOT_COMPLETED broadcast since 1696 // the private space profile has been started 1697 @GuardedBy("this") 1698 private final ArraySet<String> mPrivateSpaceBootCompletedPackages = new ArraySet<String>(); 1699 1700 /** 1701 * Whether to force background check on all apps (for battery saver) or not. 1702 */ 1703 @CompositeRWLock({"this", "mProcLock"}) 1704 private boolean mForceBackgroundCheck; 1705 1706 private static String sTheRealBuildSerial = Build.UNKNOWN; 1707 1708 @GuardedBy("mProcLock") 1709 private ParcelFileDescriptor[] mLifeMonitorFds; 1710 1711 static final HostingRecord sNullHostingRecord = 1712 new HostingRecord(HostingRecord.HOSTING_TYPE_EMPTY); 1713 /** 1714 * Used to notify activity lifecycle events. 1715 */ 1716 @Nullable volatile ContentCaptureManagerInternal mContentCaptureService; 1717 1718 /* 1719 * The default duration for the binder heavy hitter auto sampler 1720 */ 1721 private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS = 300000L; 1722 1723 /** 1724 * The default throttling duration for the binder heavy hitter auto sampler 1725 */ 1726 private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS = 3600000L; 1727 1728 /** 1729 * The last time when the binder heavy hitter auto sampler started. 1730 */ 1731 @GuardedBy("mProcLock") 1732 private long mLastBinderHeavyHitterAutoSamplerStart = 0L; 1733 1734 AppProfiler mAppProfiler; 1735 1736 private static final int INDEX_NATIVE_PSS = 0; 1737 private static final int INDEX_NATIVE_SWAP_PSS = 1; 1738 private static final int INDEX_NATIVE_RSS = 2; 1739 private static final int INDEX_NATIVE_PRIVATE_DIRTY = 3; 1740 private static final int INDEX_DALVIK_PSS = 4; 1741 private static final int INDEX_DALVIK_SWAP_PSS = 5; 1742 private static final int INDEX_DALVIK_RSS = 6; 1743 private static final int INDEX_DALVIK_PRIVATE_DIRTY = 7; 1744 private static final int INDEX_OTHER_PSS = 8; 1745 private static final int INDEX_OTHER_SWAP_PSS = 9; 1746 private static final int INDEX_OTHER_RSS = 10; 1747 private static final int INDEX_OTHER_PRIVATE_DIRTY = 11; 1748 private static final int INDEX_TOTAL_PSS = 12; 1749 private static final int INDEX_TOTAL_SWAP_PSS = 13; 1750 private static final int INDEX_TOTAL_RSS = 14; 1751 private static final int INDEX_TOTAL_PRIVATE_DIRTY = 15; 1752 private static final int INDEX_TOTAL_NATIVE_PSS = 16; 1753 private static final int INDEX_TOTAL_MEMTRACK_GRAPHICS = 17; 1754 private static final int INDEX_TOTAL_MEMTRACK_GL = 18; 1755 private static final int INDEX_LAST = 19; 1756 1757 /** 1758 * Used to notify activity lifecycle events. 1759 */ 1760 @Nullable 1761 volatile ActivityManagerInternal.VoiceInteractionManagerProvider 1762 mVoiceInteractionManagerProvider; 1763 1764 final class UiHandler extends Handler { UiHandler()1765 public UiHandler() { 1766 super(com.android.server.UiThread.get().getLooper(), null, true); 1767 } 1768 1769 @Override handleMessage(Message msg)1770 public void handleMessage(Message msg) { 1771 switch (msg.what) { 1772 case SHOW_ERROR_UI_MSG: { 1773 mAppErrors.handleShowAppErrorUi(msg); 1774 ensureBootCompleted(); 1775 } break; 1776 case SHOW_NOT_RESPONDING_UI_MSG: { 1777 mAppErrors.handleShowAnrUi(msg); 1778 ensureBootCompleted(); 1779 } break; 1780 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: { 1781 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1782 synchronized (mProcLock) { 1783 ProcessRecord proc = (ProcessRecord) data.get("app"); 1784 if (proc == null) { 1785 Slog.e(TAG, "App not found when showing strict mode dialog."); 1786 break; 1787 } 1788 if (proc.mErrorState.getDialogController().hasViolationDialogs()) { 1789 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1790 return; 1791 } 1792 AppErrorResult res = (AppErrorResult) data.get("result"); 1793 if (mAtmInternal.showStrictModeViolationDialog()) { 1794 proc.mErrorState.getDialogController().showViolationDialogs(res); 1795 } else { 1796 // The device is asleep, so just pretend that the user 1797 // saw a crash dialog and hit "force quit". 1798 res.set(0); 1799 } 1800 } 1801 ensureBootCompleted(); 1802 } break; 1803 case WAIT_FOR_DEBUGGER_UI_MSG: { 1804 synchronized (mProcLock) { 1805 ProcessRecord app = (ProcessRecord) msg.obj; 1806 if (msg.arg1 != 0) { 1807 if (!app.hasWaitedForDebugger()) { 1808 app.mErrorState.getDialogController().showDebugWaitingDialogs(); 1809 app.setWaitedForDebugger(true); 1810 } 1811 } else { 1812 app.mErrorState.getDialogController().clearWaitingDialog(); 1813 } 1814 } 1815 } break; 1816 case DISPATCH_PROCESSES_CHANGED_UI_MSG: { 1817 mProcessList.dispatchProcessesChanged(); 1818 break; 1819 } 1820 case DISPATCH_PROCESS_DIED_UI_MSG: { 1821 if (false) { // DO NOT SUBMIT WITH TRUE 1822 maybeTriggerWatchdog(); 1823 } 1824 final int pid = msg.arg1; 1825 final int uid = msg.arg2; 1826 mProcessList.dispatchProcessDied(pid, uid); 1827 break; 1828 } 1829 case DISPATCH_OOM_ADJ_OBSERVER_MSG: { 1830 dispatchOomAdjObserver((String) msg.obj); 1831 } break; 1832 case PUSH_TEMP_ALLOWLIST_UI_MSG: { 1833 pushTempAllowlist(); 1834 } break; 1835 case ADD_UID_TO_OBSERVER_MSG: { 1836 mUidObserverController.addUidToObserverImpl((IBinder) msg.obj, msg.arg1); 1837 } break; 1838 case REMOVE_UID_FROM_OBSERVER_MSG: { 1839 mUidObserverController.removeUidFromObserverImpl((IBinder) msg.obj, msg.arg1); 1840 } break; 1841 } 1842 } 1843 } 1844 1845 final class MainHandler extends Handler { MainHandler(Looper looper)1846 public MainHandler(Looper looper) { 1847 super(looper, null, true); 1848 } 1849 1850 @Override handleMessage(Message msg)1851 public void handleMessage(Message msg) { 1852 switch (msg.what) { 1853 case GC_BACKGROUND_PROCESSES_MSG: { 1854 synchronized (ActivityManagerService.this) { 1855 mAppProfiler.performAppGcsIfAppropriateLocked(); 1856 } 1857 } break; 1858 case SERVICE_TIMEOUT_MSG: { 1859 mServices.serviceTimeout((ProcessRecord) msg.obj); 1860 } break; 1861 case SERVICE_FOREGROUND_TIMEOUT_MSG: { 1862 mServices.serviceForegroundTimeout((ServiceRecord) msg.obj); 1863 } break; 1864 case SERVICE_FOREGROUND_TIMEOUT_ANR_MSG: { 1865 SomeArgs args = (SomeArgs) msg.obj; 1866 mServices.serviceForegroundTimeoutANR((ProcessRecord) args.arg1, 1867 (TimeoutRecord) args.arg2); 1868 args.recycle(); 1869 } break; 1870 case SERVICE_FOREGROUND_CRASH_MSG: { 1871 SomeArgs args = (SomeArgs) msg.obj; 1872 mServices.serviceForegroundCrash( 1873 (ProcessRecord) args.arg1, 1874 (String) args.arg2, 1875 (ComponentName) args.arg3); 1876 args.recycle(); 1877 } break; 1878 case UPDATE_TIME_ZONE: { 1879 synchronized (mProcLock) { 1880 mProcessList.forEachLruProcessesLOSP(false, app -> { 1881 final IApplicationThread thread = app.getThread(); 1882 if (thread != null) { 1883 try { 1884 thread.updateTimeZone(); 1885 } catch (RemoteException ex) { 1886 Slog.w(TAG, "Failed to update time zone for: " 1887 + app.info.processName); 1888 } 1889 } 1890 }); 1891 } 1892 } break; 1893 case CLEAR_DNS_CACHE_MSG: { 1894 synchronized (mProcLock) { 1895 mProcessList.clearAllDnsCacheLOSP(); 1896 } 1897 } break; 1898 case UPDATE_HTTP_PROXY_MSG: { 1899 mProcessList.setAllHttpProxy(); 1900 } break; 1901 case PROC_START_TIMEOUT_MSG: { 1902 ProcessRecord app = (ProcessRecord) msg.obj; 1903 synchronized (ActivityManagerService.this) { 1904 handleProcessStartOrKillTimeoutLocked(app, /* isKillTimeout */ false); 1905 } 1906 } break; 1907 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: { 1908 ProcessRecord app = (ProcessRecord) msg.obj; 1909 synchronized (ActivityManagerService.this) { 1910 mCpHelper.processContentProviderPublishTimedOutLocked(app); 1911 } 1912 } break; 1913 case KILL_APPLICATION_MSG: { 1914 synchronized (ActivityManagerService.this) { 1915 final int appId = msg.arg1; 1916 final int userId = msg.arg2; 1917 SomeArgs args = (SomeArgs) msg.obj; 1918 String pkg = (String) args.arg1; 1919 String reason = (String) args.arg2; 1920 int exitInfoReason = (int) args.arg3; 1921 args.recycle(); 1922 forceStopPackageLocked(pkg, appId, false, false, true, false, 1923 false, false, userId, reason, exitInfoReason); 1924 } 1925 } break; 1926 1927 case KILL_APP_ZYGOTE_MSG: { 1928 synchronized (ActivityManagerService.this) { 1929 final AppZygote appZygote = (AppZygote) msg.obj; 1930 mProcessList.killAppZygoteIfNeededLocked(appZygote, false /* force */); 1931 } 1932 } break; 1933 case CHECK_EXCESSIVE_POWER_USE_MSG: { 1934 checkExcessivePowerUsage(); 1935 removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG); 1936 Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 1937 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 1938 } break; 1939 case REPORT_MEM_USAGE_MSG: { 1940 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>) msg.obj; 1941 Thread thread = new Thread() { 1942 @Override public void run() { 1943 mAppProfiler.reportMemUsage(memInfos); 1944 } 1945 }; 1946 thread.start(); 1947 break; 1948 } 1949 case UPDATE_TIME_PREFERENCE_MSG: { 1950 // The user's time format preference might have changed. 1951 // For convenience we re-use the Intent extra values. 1952 synchronized (mProcLock) { 1953 mProcessList.updateAllTimePrefsLOSP(msg.arg1); 1954 } 1955 break; 1956 } 1957 case NOTIFY_CLEARTEXT_NETWORK_MSG: { 1958 final int uid = msg.arg1; 1959 final byte[] firstPacket = (byte[]) msg.obj; 1960 1961 synchronized (mProcLock) { 1962 synchronized (mPidsSelfLocked) { 1963 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 1964 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 1965 final IApplicationThread thread = p.getThread(); 1966 if (p.uid == uid && thread != null) { 1967 try { 1968 thread.notifyCleartextNetwork(firstPacket); 1969 } catch (RemoteException ignored) { 1970 } 1971 } 1972 } 1973 } 1974 } 1975 } break; 1976 case POST_DUMP_HEAP_NOTIFICATION_MSG: { 1977 mAppProfiler.handlePostDumpHeapNotification(); 1978 } break; 1979 case ABORT_DUMPHEAP_MSG: { 1980 mAppProfiler.handleAbortDumpHeap((String) msg.obj); 1981 } break; 1982 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: { 1983 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj; 1984 try { 1985 connection.shutdown(); 1986 } catch (RemoteException e) { 1987 Slog.w(TAG, "Error shutting down UiAutomationConnection"); 1988 } 1989 // Only a UiAutomation can set this flag and now that 1990 // it is finished we make sure it is reset to its default. 1991 mUserIsMonkey = false; 1992 } break; 1993 case IDLE_UIDS_MSG: { 1994 idleUids(); 1995 } break; 1996 case HANDLE_TRUST_STORAGE_UPDATE_MSG: { 1997 synchronized (mProcLock) { 1998 mProcessList.handleAllTrustStorageUpdateLOSP(); 1999 } 2000 } break; 2001 case BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG: { 2002 handleBinderHeavyHitterAutoSamplerTimeOut(); 2003 } break; 2004 case WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG: { 2005 synchronized (ActivityManagerService.this) { 2006 ((ContentProviderRecord) msg.obj).onProviderPublishStatusLocked(false); 2007 } 2008 } break; 2009 case DISPATCH_SENDING_BROADCAST_EVENT: { 2010 mBroadcastEventListeners.forEach(l -> 2011 l.onSendingBroadcast((String) msg.obj, msg.arg1)); 2012 } break; 2013 case DISPATCH_BINDING_SERVICE_EVENT: { 2014 mBindServiceEventListeners.forEach(l -> 2015 l.onBindingService((String) msg.obj, msg.arg1)); 2016 } break; 2017 case SERVICE_SHORT_FGS_TIMEOUT_MSG: { 2018 mServices.onShortFgsTimeout((ServiceRecord) msg.obj); 2019 } break; 2020 case SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG: { 2021 mServices.onShortFgsProcstateTimeout((ServiceRecord) msg.obj); 2022 } break; 2023 case SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG: { 2024 mServices.onShortFgsAnrTimeout((ServiceRecord) msg.obj); 2025 } break; 2026 case UPDATE_CACHED_APP_HIGH_WATERMARK: { 2027 mAppProfiler.mCachedAppsWatermarkData.updateCachedAppsSnapshot((long) msg.obj); 2028 } break; 2029 case BIND_APPLICATION_TIMEOUT_SOFT_MSG: { 2030 handleBindApplicationTimeoutSoft((ProcessRecord) msg.obj, msg.arg1); 2031 } break; 2032 case BIND_APPLICATION_TIMEOUT_HARD_MSG: { 2033 handleBindApplicationTimeoutHard((ProcessRecord) msg.obj); 2034 } break; 2035 case SERVICE_FGS_TIMEOUT_MSG: { 2036 mServices.onFgsTimeout((ServiceRecord) msg.obj); 2037 } break; 2038 case SERVICE_FGS_CRASH_TIMEOUT_MSG: { 2039 mServices.onFgsCrashTimeout((ServiceRecord) msg.obj); 2040 } break; 2041 case FOLLOW_UP_OOMADJUSTER_UPDATE_MSG: { 2042 handleFollowUpOomAdjusterUpdate(); 2043 } break; 2044 } 2045 } 2046 } 2047 2048 setSystemProcess()2049 public void setSystemProcess() { 2050 try { 2051 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, 2052 DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); 2053 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 2054 ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false, 2055 DUMP_FLAG_PRIORITY_HIGH); 2056 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 2057 ServiceManager.addService("dbinfo", new DbBinder(this)); 2058 mAppProfiler.setCpuInfoService(); 2059 ServiceManager.addService("permission", new PermissionController(this)); 2060 ServiceManager.addService("processinfo", new ProcessInfoService(this)); 2061 ServiceManager.addService("cacheinfo", new CacheBinder(this)); 2062 2063 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 2064 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); 2065 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 2066 2067 synchronized (this) { 2068 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName, 2069 false, 2070 0, 2071 false, 2072 0, 2073 null, 2074 new HostingRecord(HostingRecord.HOSTING_TYPE_SYSTEM)); 2075 app.setPersistent(true); 2076 app.setPid(MY_PID); 2077 app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ); 2078 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 2079 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_SYSTEM); 2080 addPidLocked(app); 2081 updateLruProcessLocked(app, false, null); 2082 updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT); 2083 } 2084 } catch (PackageManager.NameNotFoundException e) { 2085 throw new RuntimeException( 2086 "Unable to find android system package", e); 2087 } 2088 2089 // Start watching app ops after we and the package manager are up and running. 2090 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null, 2091 new IAppOpsCallback.Stub() { 2092 @Override public void opChanged(int op, int uid, String packageName, 2093 String persistentDeviceId) { 2094 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) { 2095 if (getAppOpsManager().checkOpNoThrow(op, uid, packageName) 2096 != AppOpsManager.MODE_ALLOWED) { 2097 runInBackgroundDisabled(uid); 2098 } 2099 } 2100 } 2101 }); 2102 2103 final int[] cameraOp = {AppOpsManager.OP_CAMERA}; 2104 mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() { 2105 @Override 2106 public void opActiveChanged(int op, int uid, String packageName, String attributionTag, 2107 int virtualDeviceId, boolean active, @AttributionFlags int attributionFlags, 2108 int attributionChainId) { 2109 cameraActiveChanged(uid, active); 2110 } 2111 }); 2112 } 2113 setWindowManager(WindowManagerService wm)2114 public void setWindowManager(WindowManagerService wm) { 2115 synchronized (this) { 2116 mWindowManager = wm; 2117 mWmInternal = LocalServices.getService(WindowManagerInternal.class); 2118 mActivityTaskManager.setWindowManager(wm); 2119 } 2120 } 2121 2122 /** 2123 * @param usageStatsManager shouldn't be null 2124 */ setUsageStatsManager(@onNull UsageStatsManagerInternal usageStatsManager)2125 public void setUsageStatsManager(@NonNull UsageStatsManagerInternal usageStatsManager) { 2126 mUsageStatsService = usageStatsManager; 2127 mActivityTaskManager.setUsageStatsManager(usageStatsManager); 2128 } 2129 2130 /** 2131 * Sets the internal content capture manager service. 2132 * 2133 * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock. 2134 */ setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)2135 public void setContentCaptureManager( 2136 @Nullable ContentCaptureManagerInternal contentCaptureManager) { 2137 mContentCaptureService = contentCaptureManager; 2138 } 2139 startObservingNativeCrashes()2140 public void startObservingNativeCrashes() { 2141 final NativeCrashListener ncl = new NativeCrashListener(this); 2142 ncl.start(); 2143 } 2144 2145 /** 2146 * Sets a policy for handling app ops. 2147 * 2148 * @param appOpsPolicy The policy. 2149 */ setAppOpsPolicy(@ullable CheckOpsDelegate appOpsPolicy)2150 public void setAppOpsPolicy(@Nullable CheckOpsDelegate appOpsPolicy) { 2151 mAppOpsService.setAppOpsPolicy(appOpsPolicy); 2152 } 2153 getAppOpsService()2154 public IAppOpsService getAppOpsService() { 2155 return mAppOpsService; 2156 } 2157 2158 /** 2159 * Sets the internal voice interaction manager service. 2160 */ setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)2161 private void setVoiceInteractionManagerProvider( 2162 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) { 2163 mVoiceInteractionManagerProvider = provider; 2164 } 2165 2166 /** 2167 * Represents volatile states associated with a Dropbox entry. 2168 * <p> 2169 * These states, such as the process frozen state, can change quickly over time and thus 2170 * should be captured as soon as possible to ensure accurate state. If a state is undefined, 2171 * it means that the state was not read early and a fallback value can be used. 2172 * </p> 2173 */ 2174 static class VolatileDropboxEntryStates { 2175 private final Boolean mIsProcessFrozen; 2176 private final ZonedDateTime mTimestamp; 2177 VolatileDropboxEntryStates(Boolean frozenState, ZonedDateTime timestamp)2178 private VolatileDropboxEntryStates(Boolean frozenState, ZonedDateTime timestamp) { 2179 this.mIsProcessFrozen = frozenState; 2180 this.mTimestamp = timestamp; 2181 } 2182 withProcessFrozenStateAndTimestamp( boolean frozenState, ZonedDateTime timestamp)2183 public static VolatileDropboxEntryStates withProcessFrozenStateAndTimestamp( 2184 boolean frozenState, ZonedDateTime timestamp) { 2185 return new VolatileDropboxEntryStates(frozenState, timestamp); 2186 } 2187 isProcessFrozen()2188 public Boolean isProcessFrozen() { 2189 return mIsProcessFrozen; 2190 } 2191 getTimestamp()2192 public ZonedDateTime getTimestamp() { 2193 return mTimestamp; 2194 } 2195 } 2196 2197 static class MemBinder extends Binder { 2198 ActivityManagerService mActivityManagerService; 2199 private final PriorityDump.PriorityDumper mPriorityDumper = 2200 new PriorityDump.PriorityDumper() { 2201 @Override 2202 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, 2203 boolean asProto) { 2204 dump(fd, pw, new String[] {"-a"}, asProto); 2205 } 2206 2207 @Override 2208 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 2209 mActivityManagerService.dumpApplicationMemoryUsage( 2210 fd, pw, " ", args, false, null, asProto); 2211 } 2212 }; 2213 MemBinder(ActivityManagerService activityManagerService)2214 MemBinder(ActivityManagerService activityManagerService) { 2215 mActivityManagerService = activityManagerService; 2216 } 2217 2218 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2219 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2220 try { 2221 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2222 2223 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2224 "meminfo", pw)) return; 2225 PriorityDump.dump(mPriorityDumper, fd, pw, args); 2226 } finally { 2227 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2228 } 2229 } 2230 } 2231 2232 static class GraphicsBinder extends Binder { 2233 ActivityManagerService mActivityManagerService; GraphicsBinder(ActivityManagerService activityManagerService)2234 GraphicsBinder(ActivityManagerService activityManagerService) { 2235 mActivityManagerService = activityManagerService; 2236 } 2237 2238 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2239 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2240 try { 2241 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2242 2243 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2244 "gfxinfo", pw)) return; 2245 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 2246 } finally { 2247 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2248 } 2249 } 2250 } 2251 2252 static class DbBinder extends Binder { 2253 ActivityManagerService mActivityManagerService; DbBinder(ActivityManagerService activityManagerService)2254 DbBinder(ActivityManagerService activityManagerService) { 2255 mActivityManagerService = activityManagerService; 2256 } 2257 2258 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2259 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2260 try { 2261 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2262 2263 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2264 "dbinfo", pw)) return; 2265 mActivityManagerService.dumpDbInfo(fd, pw, args); 2266 } finally { 2267 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2268 } 2269 } 2270 } 2271 2272 static class CacheBinder extends Binder { 2273 ActivityManagerService mActivityManagerService; 2274 CacheBinder(ActivityManagerService activityManagerService)2275 CacheBinder(ActivityManagerService activityManagerService) { 2276 mActivityManagerService = activityManagerService; 2277 } 2278 2279 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2280 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2281 try { 2282 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2283 2284 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2285 "cacheinfo", pw)) { 2286 return; 2287 } 2288 2289 mActivityManagerService.dumpBinderCacheContents(fd, pw, args); 2290 } finally { 2291 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2292 } 2293 } 2294 } 2295 2296 public static final class Lifecycle extends SystemService { 2297 private final ActivityManagerService mService; 2298 private static ActivityTaskManagerService sAtm; 2299 Lifecycle(Context context)2300 public Lifecycle(Context context) { 2301 super(context); 2302 mService = new ActivityManagerService(context, sAtm); 2303 } 2304 startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2305 public static ActivityManagerService startService( 2306 SystemServiceManager ssm, ActivityTaskManagerService atm) { 2307 sAtm = atm; 2308 return ssm.startService(ActivityManagerService.Lifecycle.class).getService(); 2309 } 2310 2311 @Override onStart()2312 public void onStart() { 2313 mService.start(); 2314 } 2315 2316 @Override onBootPhase(int phase)2317 public void onBootPhase(int phase) { 2318 mService.mBootPhase = phase; 2319 if (phase == PHASE_SYSTEM_SERVICES_READY) { 2320 mService.mBatteryStatsService.systemServicesReady(); 2321 mService.mServices.systemServicesReady(); 2322 } else if (phase == PHASE_ACTIVITY_MANAGER_READY) { 2323 mService.startBroadcastObservers(); 2324 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { 2325 mService.mPackageWatchdog.onPackagesReady(); 2326 mService.scheduleHomeTimeout(); 2327 } 2328 } 2329 2330 @Override onUserStopped(@onNull TargetUser user)2331 public void onUserStopped(@NonNull TargetUser user) { 2332 mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier()); 2333 2334 if (android.os.Flags.allowPrivateProfile() 2335 && android.multiuser.Flags.enablePrivateSpaceFeatures()) { 2336 final UserManagerInternal umInternal = 2337 LocalServices.getService(UserManagerInternal.class); 2338 UserInfo userInfo = umInternal.getUserInfo(user.getUserIdentifier()); 2339 2340 if (userInfo != null && userInfo.isPrivateProfile()) { 2341 synchronized (mService) { 2342 mService.mPrivateSpaceBootCompletedPackages.clear(); 2343 } 2344 } 2345 } 2346 } 2347 getService()2348 public ActivityManagerService getService() { 2349 return mService; 2350 } 2351 } 2352 maybeLogUserspaceRebootEvent()2353 private void maybeLogUserspaceRebootEvent() { 2354 if (!UserspaceRebootLogger.shouldLogUserspaceRebootEvent()) { 2355 return; 2356 } 2357 final int userId = mUserController.getCurrentUserId(); 2358 if (userId != UserHandle.USER_SYSTEM) { 2359 // Only log for user0. 2360 return; 2361 } 2362 // TODO(b/148767783): should we check all profiles under user0? 2363 UserspaceRebootLogger.logEventAsync(StorageManager.isCeStorageUnlocked(userId), 2364 BackgroundThread.getExecutor()); 2365 } 2366 2367 /** 2368 * Encapsulates global settings related to hidden API enforcement behaviour, including tracking 2369 * the latest value via a content observer. 2370 */ 2371 static class HiddenApiSettings extends ContentObserver 2372 implements DeviceConfig.OnPropertiesChangedListener { 2373 2374 private final Context mContext; 2375 private boolean mBlacklistDisabled; 2376 private String mExemptionsStr; 2377 private List<String> mExemptions = Collections.emptyList(); 2378 private int mLogSampleRate = -1; 2379 private int mStatslogSampleRate = -1; 2380 @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT; 2381 2382 /** 2383 * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in 2384 * the range 0 to 0x10000 inclusive. 2385 * 2386 * @hide 2387 */ 2388 public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE = 2389 "hidden_api_access_log_sampling_rate"; 2390 2391 /** 2392 * Sampling rate for hidden API access event logging with statslog, as an integer in the 2393 * range 0 to 0x10000 inclusive. 2394 * 2395 * @hide 2396 */ 2397 public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE = 2398 "hidden_api_access_statslog_sampling_rate"; 2399 onPropertiesChanged(DeviceConfig.Properties properties)2400 public void onPropertiesChanged(DeviceConfig.Properties properties) { 2401 int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0x0); 2402 if (logSampleRate < 0 || logSampleRate > 0x10000) { 2403 logSampleRate = -1; 2404 } 2405 if (logSampleRate != -1 && logSampleRate != mLogSampleRate) { 2406 mLogSampleRate = logSampleRate; 2407 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate); 2408 } 2409 2410 int statslogSampleRate = 2411 properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0); 2412 if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) { 2413 statslogSampleRate = -1; 2414 } 2415 if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) { 2416 mStatslogSampleRate = statslogSampleRate; 2417 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate); 2418 } 2419 } 2420 HiddenApiSettings(Handler handler, Context context)2421 public HiddenApiSettings(Handler handler, Context context) { 2422 super(handler); 2423 mContext = context; 2424 } 2425 registerObserver()2426 public void registerObserver() { 2427 mContext.getContentResolver().registerContentObserver( 2428 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS), 2429 false, 2430 this); 2431 mContext.getContentResolver().registerContentObserver( 2432 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY), 2433 false, 2434 this); 2435 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT, 2436 mContext.getMainExecutor(), this); 2437 update(); 2438 } 2439 update()2440 private void update() { 2441 String exemptions = Settings.Global.getString(mContext.getContentResolver(), 2442 Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS); 2443 if (!TextUtils.equals(exemptions, mExemptionsStr)) { 2444 mExemptionsStr = exemptions; 2445 if ("*".equals(exemptions)) { 2446 mBlacklistDisabled = true; 2447 mExemptions = Collections.emptyList(); 2448 } else { 2449 mBlacklistDisabled = false; 2450 mExemptions = TextUtils.isEmpty(exemptions) 2451 ? Collections.emptyList() 2452 : Arrays.asList(exemptions.split(",")); 2453 } 2454 if (!ZYGOTE_PROCESS.setApiDenylistExemptions(mExemptions)) { 2455 Slog.e(TAG, "Failed to set API blacklist exemptions!"); 2456 // leave mExemptionsStr as is, so we don't try to send the same list again. 2457 mExemptions = Collections.emptyList(); 2458 } 2459 } 2460 mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY); 2461 } 2462 getValidEnforcementPolicy(String settingsKey)2463 private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) { 2464 int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey, 2465 ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT); 2466 if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) { 2467 return policy; 2468 } else { 2469 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 2470 } 2471 } 2472 isDisabled()2473 boolean isDisabled() { 2474 return mBlacklistDisabled; 2475 } 2476 getPolicy()2477 @HiddenApiEnforcementPolicy int getPolicy() { 2478 return mPolicy; 2479 } 2480 onChange(boolean selfChange)2481 public void onChange(boolean selfChange) { 2482 update(); 2483 } 2484 } 2485 getAppOpsManager()2486 AppOpsManager getAppOpsManager() { 2487 if (mAppOpsManager == null) { 2488 mAppOpsManager = mContext.getSystemService(AppOpsManager.class); 2489 } 2490 return mAppOpsManager; 2491 } 2492 2493 /** Provides the basic functionality for unit tests. */ 2494 @VisibleForTesting ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread)2495 ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread) { 2496 this(injector, handlerThread, null); 2497 } 2498 2499 /** Provides the basic functionality for unit tests. */ 2500 @VisibleForTesting ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread, @Nullable UserController userController)2501 ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread, 2502 @Nullable UserController userController) { 2503 mInjector = injector; 2504 mContext = mInjector.getContext(); 2505 mUiContext = null; 2506 mAppErrors = injector.getAppErrors(); 2507 mPackageWatchdog = null; 2508 mAppOpsService = mInjector.getAppOpsService(null /* recentAccessesFile */, 2509 null /* storageFile */, null /* handler */); 2510 mBatteryStatsService = mInjector.getBatteryStatsService(); 2511 mHandler = new MainHandler(handlerThread.getLooper()); 2512 mHandlerThread = handlerThread; 2513 mConstants = new ActivityManagerConstants(mContext, this, mHandler); 2514 final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */); 2515 mPlatformCompat = null; 2516 mProcessList = injector.getProcessList(this); 2517 mProcessList.init(this, activeUids, mPlatformCompat); 2518 mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), null); 2519 mPhantomProcessList = new PhantomProcessList(this); 2520 mOomAdjuster = mConstants.ENABLE_NEW_OOMADJ 2521 ? new OomAdjusterModernImpl(this, mProcessList, activeUids, handlerThread) 2522 : new OomAdjuster(this, mProcessList, activeUids, handlerThread); 2523 2524 mIntentFirewall = injector.getIntentFirewall(); 2525 mProcessStats = new ProcessStatsService(this, mContext.getCacheDir()); 2526 mCpHelper = new ContentProviderHelper(this, false); 2527 mServices = mInjector.getActiveServices(this); 2528 mSystemThread = null; 2529 mUiHandler = injector.getUiHandler(null /* service */); 2530 mUidObserverController = new UidObserverController(mUiHandler); 2531 mUserController = userController == null ? new UserController(this) : userController; 2532 mInjector.mUserController = mUserController; 2533 mPendingIntentController = 2534 new PendingIntentController(handlerThread.getLooper(), mUserController, mConstants); 2535 mAppRestrictionController = new AppRestrictionController(mContext, this); 2536 mProcStartHandlerThread = null; 2537 mProcStartHandler = null; 2538 mHiddenApiBlacklist = null; 2539 mFactoryTest = FACTORY_TEST_OFF; 2540 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2541 mInternal = new LocalService(); 2542 mPendingStartActivityUids = new PendingStartActivityUids(); 2543 mUseFifoUiScheduling = false; 2544 mBroadcastQueue = injector.getBroadcastQueue(this); 2545 mComponentAliasResolver = new ComponentAliasResolver(this); 2546 } 2547 2548 // Note: This method is invoked on the main thread but may need to attach various 2549 // handlers to other threads. So take care to be explicit about the looper. ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2550 public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) { 2551 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); 2552 mInjector = new Injector(systemContext); 2553 mContext = systemContext; 2554 2555 mFactoryTest = FactoryTest.getMode(); 2556 mSystemThread = ActivityThread.currentActivityThread(); 2557 mUiContext = mSystemThread.getSystemUiContext(); 2558 2559 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2560 2561 mHandlerThread = new ServiceThread(TAG, 2562 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2563 mHandlerThread.start(); 2564 mHandler = new MainHandler(mHandlerThread.getLooper()); 2565 mUiHandler = mInjector.getUiHandler(this); 2566 2567 mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", 2568 THREAD_PRIORITY_FOREGROUND, false /* allowIo */); 2569 mProcStartHandlerThread.start(); 2570 mProcStartHandler = new ProcStartHandler(this, mProcStartHandlerThread.getLooper()); 2571 2572 mConstants = new ActivityManagerConstants(mContext, this, mHandler); 2573 final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */); 2574 mPlatformCompat = (PlatformCompat) ServiceManager.getService( 2575 Context.PLATFORM_COMPAT_SERVICE); 2576 mProcessList = mInjector.getProcessList(this); 2577 mProcessList.init(this, activeUids, mPlatformCompat); 2578 mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), 2579 new LowMemDetector(this)); 2580 mPhantomProcessList = new PhantomProcessList(this); 2581 mOomAdjuster = mConstants.ENABLE_NEW_OOMADJ 2582 ? new OomAdjusterModernImpl(this, mProcessList, activeUids) 2583 : new OomAdjuster(this, mProcessList, activeUids); 2584 2585 mBroadcastQueue = mInjector.getBroadcastQueue(this); 2586 2587 mServices = new ActiveServices(this); 2588 mCpHelper = new ContentProviderHelper(this, true); 2589 mPackageWatchdog = PackageWatchdog.getInstance(mUiContext); 2590 mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog); 2591 mUidObserverController = new UidObserverController(mUiHandler); 2592 2593 final File systemDir = SystemServiceManager.ensureSystemDir(); 2594 2595 // TODO: Move creation of battery stats service outside of activity manager service. 2596 mBatteryStatsService = BatteryStatsService.create(systemContext, systemDir, 2597 BackgroundThread.getHandler(), this); 2598 mOnBattery = DEBUG_POWER ? true 2599 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2600 2601 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2602 2603 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops_accesses.xml"), 2604 new File(systemDir, "appops.xml"), mHandler); 2605 2606 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2607 2608 mUserController = new UserController(this); 2609 mInjector.mUserController = mUserController; 2610 2611 mPendingIntentController = new PendingIntentController( 2612 mHandlerThread.getLooper(), mUserController, mConstants); 2613 2614 mAppRestrictionController = new AppRestrictionController(mContext, this); 2615 2616 mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0; 2617 2618 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations")); 2619 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2620 2621 mActivityTaskManager = atm; 2622 mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, 2623 DisplayThread.get().getLooper()); 2624 mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class); 2625 2626 mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext); 2627 2628 Watchdog.getInstance().addMonitor(this); 2629 Watchdog.getInstance().addThread(mHandler); 2630 2631 // bind background threads to little cores 2632 // this is expected to fail inside of framework tests because apps can't touch cpusets directly 2633 // make sure we've already adjusted system_server's internal view of itself first 2634 updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT); 2635 try { 2636 Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(), 2637 Process.THREAD_GROUP_SYSTEM); 2638 Process.setThreadGroupAndCpuset( 2639 mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(), 2640 Process.THREAD_GROUP_SYSTEM); 2641 } catch (Exception e) { 2642 Slog.w(TAG, "Setting background thread cpuset failed"); 2643 } 2644 2645 mInternal = new LocalService(); 2646 mPendingStartActivityUids = new PendingStartActivityUids(); 2647 mTraceErrorLogger = new TraceErrorLogger(); 2648 mComponentAliasResolver = new ComponentAliasResolver(this); 2649 } 2650 setBroadcastQueueForTest(BroadcastQueue broadcastQueue)2651 void setBroadcastQueueForTest(BroadcastQueue broadcastQueue) { 2652 mBroadcastQueue = broadcastQueue; 2653 } 2654 getBroadcastQueue()2655 BroadcastQueue getBroadcastQueue() { 2656 return mBroadcastQueue; 2657 } 2658 setSystemServiceManager(SystemServiceManager mgr)2659 public void setSystemServiceManager(SystemServiceManager mgr) { 2660 mSystemServiceManager = mgr; 2661 } 2662 setInstaller(Installer installer)2663 public void setInstaller(Installer installer) { 2664 mInstaller = installer; 2665 } 2666 start()2667 private void start() { 2668 mBatteryStatsService.publish(); 2669 mAppOpsService.publish(); 2670 mProcessStats.publish(); 2671 Slog.d("AppOps", "AppOpsService published"); 2672 LocalServices.addService(ActivityManagerInternal.class, mInternal); 2673 LocalManagerRegistry.addManager(ActivityManagerLocal.class, 2674 (ActivityManagerLocal) mInternal); 2675 mActivityTaskManager.onActivityManagerInternalAdded(); 2676 mPendingIntentController.onActivityManagerInternalAdded(); 2677 mAppProfiler.onActivityManagerInternalAdded(); 2678 CriticalEventLog.init(); 2679 } 2680 initPowerManagement()2681 public void initPowerManagement() { 2682 mActivityTaskManager.onInitPowerManagement(); 2683 mBatteryStatsService.initPowerManagement(); 2684 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); 2685 } 2686 getBackgroundLaunchBroadcasts()2687 private ArraySet<String> getBackgroundLaunchBroadcasts() { 2688 if (mBackgroundLaunchBroadcasts == null) { 2689 mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts(); 2690 } 2691 return mBackgroundLaunchBroadcasts; 2692 } 2693 getWearRemoteIntentAction()2694 private String getWearRemoteIntentAction() { 2695 return mContext.getResources().getString( 2696 com.android.internal.R.string.config_wearRemoteIntentAction); 2697 } 2698 2699 /** 2700 * Ensures that the given package name has an explicit set of allowed associations. 2701 * If it does not, give it an empty set. 2702 */ requireAllowedAssociationsLocked(String packageName)2703 void requireAllowedAssociationsLocked(String packageName) { 2704 ensureAllowedAssociations(); 2705 if (mAllowedAssociations.get(packageName) == null) { 2706 mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName, 2707 new ArraySet<>(), /* isDebuggable = */ false)); 2708 } 2709 } 2710 2711 /** 2712 * Returns true if the package {@code pkg1} running under user handle {@code uid1} is 2713 * allowed association with the package {@code pkg2} running under user handle {@code uid2}. 2714 * <p> If either of the packages are running as part of the core system, then the 2715 * association is implicitly allowed. 2716 */ validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2717 boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) { 2718 ensureAllowedAssociations(); 2719 // Interactions with the system uid are always allowed, since that is the core system 2720 // that everyone needs to be able to interact with. Also allow reflexive associations 2721 // within the same uid. 2722 if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID 2723 || UserHandle.getAppId(uid2) == SYSTEM_UID) { 2724 return true; 2725 } 2726 2727 // Check for association on both source and target packages. 2728 PackageAssociationInfo pai = mAllowedAssociations.get(pkg1); 2729 if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) { 2730 return false; 2731 } 2732 pai = mAllowedAssociations.get(pkg2); 2733 if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) { 2734 return false; 2735 } 2736 // If no explicit associations are provided in the manifest, then assume the app is 2737 // allowed associations with any package. 2738 return true; 2739 } 2740 2741 /** Sets up allowed associations for system prebuilt packages from system config (if needed). */ ensureAllowedAssociations()2742 private void ensureAllowedAssociations() { 2743 if (mAllowedAssociations == null) { 2744 ArrayMap<String, ArraySet<String>> allowedAssociations = 2745 SystemConfig.getInstance().getAllowedAssociations(); 2746 mAllowedAssociations = new ArrayMap<>(allowedAssociations.size()); 2747 PackageManagerInternal pm = getPackageManagerInternal(); 2748 for (int i = 0; i < allowedAssociations.size(); i++) { 2749 final String pkg = allowedAssociations.keyAt(i); 2750 final ArraySet<String> asc = allowedAssociations.valueAt(i); 2751 2752 // Query latest debuggable flag from package-manager. 2753 boolean isDebuggable = false; 2754 try { 2755 ApplicationInfo ai = AppGlobals.getPackageManager() 2756 .getApplicationInfo(pkg, MATCH_ALL, 0); 2757 if (ai != null) { 2758 isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 2759 } 2760 } catch (RemoteException e) { 2761 /* ignore */ 2762 } 2763 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable)); 2764 } 2765 } 2766 } 2767 2768 /** Updates allowed associations for app info (specifically, based on debuggability). */ updateAssociationForApp(ApplicationInfo appInfo)2769 private void updateAssociationForApp(ApplicationInfo appInfo) { 2770 ensureAllowedAssociations(); 2771 PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName); 2772 if (pai != null) { 2773 pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); 2774 } 2775 } 2776 2777 @Override onTransact(int code, Parcel data, Parcel reply, int flags)2778 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2779 throws RemoteException { 2780 if (code == SYSPROPS_TRANSACTION) { 2781 // We need to tell all apps about the system property change. 2782 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2783 synchronized (mProcLock) { 2784 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 2785 mProcessList.getProcessNamesLOSP().getMap(); 2786 final int numOfNames = pmap.size(); 2787 for (int ip = 0; ip < numOfNames; ip++) { 2788 SparseArray<ProcessRecord> apps = pmap.valueAt(ip); 2789 final int numOfApps = apps.size(); 2790 for (int ia = 0; ia < numOfApps; ia++) { 2791 ProcessRecord app = apps.valueAt(ia); 2792 final IApplicationThread thread = app.getThread(); 2793 if (thread != null) { 2794 procs.add(thread.asBinder()); 2795 } 2796 } 2797 } 2798 } 2799 2800 int N = procs.size(); 2801 for (int i=0; i<N; i++) { 2802 Parcel data2 = Parcel.obtain(); 2803 try { 2804 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 2805 Binder.FLAG_ONEWAY); 2806 } catch (RemoteException e) { 2807 } 2808 data2.recycle(); 2809 } 2810 } 2811 try { 2812 return super.onTransact(code, data, reply, flags); 2813 } catch (RuntimeException e) { 2814 // The activity manager only throws certain exceptions intentionally, so let's 2815 // log all others. 2816 if (!(e instanceof SecurityException 2817 || e instanceof IllegalArgumentException 2818 || e instanceof IllegalStateException)) { 2819 Slog.wtf(TAG, "Activity Manager Crash." 2820 + " UID:" + Binder.getCallingUid() 2821 + " PID:" + Binder.getCallingPid() 2822 + " TRANS:" + code, e); 2823 } 2824 throw e; 2825 } 2826 } 2827 updateCpuStats()2828 void updateCpuStats() { 2829 mAppProfiler.updateCpuStats(); 2830 } 2831 updateCpuStatsNow()2832 void updateCpuStatsNow() { 2833 mAppProfiler.updateCpuStatsNow(); 2834 } 2835 2836 @Override batteryNeedsCpuUpdate()2837 public void batteryNeedsCpuUpdate() { 2838 updateCpuStatsNow(); 2839 } 2840 2841 @Override batteryPowerChanged(boolean onBattery)2842 public void batteryPowerChanged(boolean onBattery) { 2843 // When plugging in, update the CPU stats first before changing 2844 // the plug state. 2845 updateCpuStatsNow(); 2846 synchronized (mProcLock) { 2847 mOnBattery = DEBUG_POWER ? true : onBattery; 2848 } 2849 } 2850 2851 @Override batteryStatsReset()2852 public void batteryStatsReset() { 2853 // Empty for now. 2854 } 2855 2856 @Override batterySendBroadcast(Intent intent)2857 public void batterySendBroadcast(Intent intent) { 2858 synchronized (this) { 2859 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, null, 2860 null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(), 2861 Binder.getCallingPid(), UserHandle.USER_ALL); 2862 } 2863 } 2864 2865 /** 2866 * Initialize the application bind args. These are passed to each 2867 * process when the bindApplication() IPC is sent to the process. They're 2868 * lazily setup to make sure the services are running when they're asked for. 2869 */ getCommonServicesLocked(boolean isolated)2870 private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) { 2871 // Isolated processes won't get this optimization, so that we don't 2872 // violate the rules about which services they have access to. 2873 if (isolated) { 2874 if (mIsolatedAppBindArgs == null) { 2875 mIsolatedAppBindArgs = new ArrayMap<>(1); 2876 addServiceToMap(mIsolatedAppBindArgs, "package"); 2877 addServiceToMap(mIsolatedAppBindArgs, "permissionmgr"); 2878 } 2879 return mIsolatedAppBindArgs; 2880 } 2881 2882 if (mAppBindArgs == null) { 2883 mAppBindArgs = new ArrayMap<>(); 2884 2885 // Add common services. 2886 // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too. 2887 // Enable the check in ApplicationThread.bindApplication() to make sure. 2888 addServiceToMap(mAppBindArgs, "package"); 2889 addServiceToMap(mAppBindArgs, "permissionmgr"); 2890 addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE); 2891 addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE); 2892 addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE); 2893 addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE); 2894 addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE); 2895 addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE); 2896 addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE); 2897 addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE); 2898 addServiceToMap(mAppBindArgs, "graphicsstats"); 2899 addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE); 2900 addServiceToMap(mAppBindArgs, "content"); 2901 addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE); 2902 addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE); 2903 addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE); 2904 addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE); 2905 addServiceToMap(mAppBindArgs, Context.POWER_SERVICE); 2906 addServiceToMap(mAppBindArgs, Context.USER_SERVICE); 2907 addServiceToMap(mAppBindArgs, "mount"); 2908 addServiceToMap(mAppBindArgs, Context.PLATFORM_COMPAT_SERVICE); 2909 } 2910 return mAppBindArgs; 2911 } 2912 addServiceToMap(ArrayMap<String, IBinder> map, String name)2913 private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) { 2914 final IBinder service = ServiceManager.getService(name); 2915 if (service != null) { 2916 map.put(name, service); 2917 if (false) { 2918 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache."); 2919 } 2920 } 2921 } 2922 2923 @Override setFocusedRootTask(int taskId)2924 public void setFocusedRootTask(int taskId) { 2925 mActivityTaskManager.setFocusedRootTask(taskId); 2926 } 2927 2928 /** Sets the task stack listener that gets callbacks when a task stack changes. */ 2929 @Override registerTaskStackListener(ITaskStackListener listener)2930 public void registerTaskStackListener(ITaskStackListener listener) { 2931 mActivityTaskManager.registerTaskStackListener(listener); 2932 } 2933 2934 /** 2935 * Unregister a task stack listener so that it stops receiving callbacks. 2936 */ 2937 @Override unregisterTaskStackListener(ITaskStackListener listener)2938 public void unregisterTaskStackListener(ITaskStackListener listener) { 2939 mActivityTaskManager.unregisterTaskStackListener(listener); 2940 } 2941 2942 @GuardedBy("this") updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2943 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2944 ProcessRecord client) { 2945 mProcessList.updateLruProcessLocked(app, activityChange, client); 2946 } 2947 2948 @GuardedBy("this") removeLruProcessLocked(ProcessRecord app)2949 final void removeLruProcessLocked(ProcessRecord app) { 2950 mProcessList.removeLruProcessLocked(app); 2951 } 2952 2953 @GuardedBy("this") getProcessRecordLocked(String processName, int uid)2954 final ProcessRecord getProcessRecordLocked(String processName, int uid) { 2955 return mProcessList.getProcessRecordLocked(processName, uid); 2956 } 2957 2958 @GuardedBy(anyOf = {"this", "mProcLock"}) getProcessNamesLOSP()2959 final ProcessMap<ProcessRecord> getProcessNamesLOSP() { 2960 return mProcessList.getProcessNamesLOSP(); 2961 } 2962 notifyPackageUse(String packageName, int reason)2963 void notifyPackageUse(String packageName, int reason) { 2964 getPackageManagerInternal().notifyPackageUse(packageName, reason); 2965 } 2966 startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2967 boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 2968 String processName, String abiOverride, int uid, Runnable crashHandler) { 2969 synchronized(this) { 2970 ApplicationInfo info = new ApplicationInfo(); 2971 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 2972 // For isolated processes, the former contains the parent's uid and the latter the 2973 // actual uid of the isolated process. 2974 // In the special case introduced by this method (which is, starting an isolated 2975 // process directly from the SystemServer without an actual parent app process) the 2976 // closest thing to a parent's uid is SYSTEM_UID. 2977 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 2978 // the |isolated| logic in the ProcessRecord constructor. 2979 info.uid = SYSTEM_UID; 2980 info.processName = processName; 2981 info.className = entryPoint; 2982 info.packageName = "android"; 2983 info.seInfoUser = SELinuxUtil.COMPLETE_STR; 2984 info.targetSdkVersion = Build.VERSION.SDK_INT; 2985 ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */, 2986 false /* knownToBeDead */, 0 /* intentFlags */, 2987 sNullHostingRecord /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY, 2988 true /* allowWhileBooting */, true /* isolated */, 2989 uid, false /* isSdkSandbox */, 0 /* sdkSandboxUid */, 2990 null /* sdkSandboxClientAppPackage */, 2991 abiOverride, entryPoint, entryPointArgs, crashHandler); 2992 return proc != null; 2993 } 2994 } 2995 2996 @GuardedBy("this") startSdkSandboxProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid, String sdkSandboxClientAppPackage)2997 final ProcessRecord startSdkSandboxProcessLocked(String processName, 2998 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2999 HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid, 3000 String sdkSandboxClientAppPackage) { 3001 return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, 3002 hostingRecord, zygotePolicyFlags, false /* allowWhileBooting */, 3003 false /* isolated */, 0 /* isolatedUid */, 3004 true /* isSdkSandbox */, sdkSandboxUid, sdkSandboxClientAppPackage, 3005 null /* ABI override */, null /* entryPoint */, 3006 null /* entryPointArgs */, null /* crashHandler */); 3007 } 3008 3009 @GuardedBy("this") startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated)3010 final ProcessRecord startProcessLocked(String processName, 3011 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 3012 HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, 3013 boolean isolated) { 3014 return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, 3015 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */, 3016 false /* isSdkSandbox */, 0 /* sdkSandboxClientAppUid */, 3017 null /* sdkSandboxClientAppPackage */, 3018 null /* ABI override */, null /* entryPoint */, 3019 null /* entryPointArgs */, null /* crashHandler */); 3020 } 3021 isAllowedWhileBooting(ApplicationInfo ai)3022 boolean isAllowedWhileBooting(ApplicationInfo ai) { 3023 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 3024 } 3025 3026 /** 3027 * Update battery stats on the activity' usage. 3028 * @param activity 3029 * @param uid 3030 * @param userId 3031 * @param resumed 3032 */ updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)3033 void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) { 3034 if (DEBUG_SWITCH) { 3035 Slog.d(TAG_SWITCH, 3036 "updateBatteryStats: comp=" + activity + "res=" + resumed); 3037 } 3038 mBatteryStatsService.updateBatteryStatsOnActivityUsage(activity.getPackageName(), 3039 activity.getShortClassName(), uid, userId, resumed); 3040 } 3041 3042 /** 3043 * Update UsageStas on the activity's usage. 3044 * @param activity 3045 * @param userId 3046 * @param event 3047 * @param appToken ActivityRecord's appToken. 3048 * @param taskRoot Task's root 3049 */ updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)3050 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 3051 IBinder appToken, ComponentName taskRoot, ActivityId activityId) { 3052 if (DEBUG_SWITCH) { 3053 Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp=" 3054 + activity + " hash=" + appToken.hashCode() + " event=" + event); 3055 } 3056 if (mUsageStatsService != null) { 3057 mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(), taskRoot); 3058 if (event == Event.ACTIVITY_RESUMED) { 3059 // Report component usage as an activity is an app component 3060 mUsageStatsService.reportEvent( 3061 activity.getPackageName(), userId, Event.APP_COMPONENT_USED); 3062 } 3063 } 3064 ContentCaptureManagerInternal contentCaptureService = mContentCaptureService; 3065 if (contentCaptureService != null && (event == Event.ACTIVITY_PAUSED 3066 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED 3067 || event == Event.ACTIVITY_DESTROYED)) { 3068 contentCaptureService.notifyActivityEvent(userId, activity, event, activityId); 3069 } 3070 // Currently we have move most of logic to the client side. When the activity lifecycle 3071 // event changed, the client side will notify the VoiceInteractionManagerService. But 3072 // when the application process died, the VoiceInteractionManagerService will miss the 3073 // activity lifecycle event changed, so we still need ACTIVITY_DESTROYED event here to 3074 // know if the activity has been destroyed. 3075 if (mVoiceInteractionManagerProvider != null && event == Event.ACTIVITY_DESTROYED) { 3076 mVoiceInteractionManagerProvider.notifyActivityDestroyed(appToken); 3077 } 3078 } 3079 3080 /** 3081 * Update UsageStats on this package's usage. 3082 * @param packageName 3083 * @param userId 3084 * @param event 3085 */ updateActivityUsageStats(String packageName, int userId, int event)3086 public void updateActivityUsageStats(String packageName, int userId, int event) { 3087 if (DEBUG_SWITCH) { 3088 Slog.d(TAG_SWITCH, "updateActivityUsageStats: package=" 3089 + packageName + " event=" + event); 3090 } 3091 if (mUsageStatsService != null) { 3092 mUsageStatsService.reportEvent(packageName, userId, event); 3093 } 3094 } 3095 3096 /** 3097 * Update Usages on this foreground service's usage. 3098 * @param service 3099 * @param userId 3100 * @param started 3101 */ updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)3102 void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) { 3103 if (DEBUG_SWITCH) { 3104 Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp=" 3105 + service + " started=" + started); 3106 } 3107 if (mUsageStatsService != null) { 3108 mUsageStatsService.reportEvent(service, userId, 3109 started ? UsageEvents.Event.FOREGROUND_SERVICE_START 3110 : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null); 3111 } 3112 } 3113 compatibilityInfoForPackage(ApplicationInfo ai)3114 CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) { 3115 return mAtmInternal.compatibilityInfoForPackage(ai); 3116 } 3117 3118 /** 3119 * Enforces that the uid that calls a method is not an 3120 * {@link UserHandle#isIsolated(int) isolated} uid. 3121 * 3122 * @param caller the name of the method being called. 3123 * @throws SecurityException if the calling uid is an isolated uid. 3124 */ enforceNotIsolatedCaller(String caller)3125 /* package */ void enforceNotIsolatedCaller(String caller) { 3126 if (UserHandle.isIsolated(Binder.getCallingUid())) { 3127 throw new SecurityException("Isolated process not allowed to call " + caller); 3128 } 3129 } 3130 3131 /** 3132 * Enforces that the uid that calls a method is not an 3133 * {@link UserHandle#isIsolated(int) isolated} uid or an 3134 * {@link Process#isSdkSandboxUid(int) SDK sandbox} uid. 3135 * 3136 * @param caller the name of the method being called. 3137 * @throws SecurityException if the calling uid is an isolated uid or SDK sandbox uid. 3138 */ enforceNotIsolatedOrSdkSandboxCaller(String caller)3139 void enforceNotIsolatedOrSdkSandboxCaller(String caller) { 3140 enforceNotIsolatedCaller(caller); 3141 3142 if (Process.isSdkSandboxUid(Binder.getCallingUid())) { 3143 throw new SecurityException("SDK sandbox process not allowed to call " + caller); 3144 } 3145 } 3146 3147 /** 3148 * If the caller is an {@link Process#isSdkSandboxUid(int) SDK sandbox uid}, enforces that the 3149 * SDK sandbox has permission to start or bind to a given service. 3150 * 3151 * @param intent the intent used to start or bind to the service. 3152 * @throws IllegalStateException if {@link SdkSandboxManagerLocal} cannot be resolved. 3153 * @throws SecurityException if the SDK sandbox is not allowed to bind to this service. 3154 */ enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent)3155 private void enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent) { 3156 if (Process.isSdkSandboxUid(Binder.getCallingUid())) { 3157 SdkSandboxManagerLocal sdkSandboxManagerLocal = 3158 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 3159 if (sdkSandboxManagerLocal != null) { 3160 sdkSandboxManagerLocal.enforceAllowedToStartOrBindService(intent); 3161 } else { 3162 throw new IllegalStateException("SdkSandboxManagerLocal not found when checking" 3163 + " whether SDK sandbox uid may start or bind to a service."); 3164 } 3165 } 3166 } 3167 3168 /** 3169 * Enforces that the uid of the caller matches the uid of the package. 3170 * 3171 * @param packageName the name of the package to match uid against. 3172 * @param callingUid the uid of the caller. 3173 * @throws SecurityException if the calling uid doesn't match uid of the package. 3174 */ enforceCallingPackage(String packageName, int callingUid)3175 private void enforceCallingPackage(String packageName, int callingUid) { 3176 final int userId = UserHandle.getUserId(callingUid); 3177 final int packageUid = getPackageManagerInternal().getPackageUid(packageName, 3178 /*flags=*/ 0, userId); 3179 if (packageUid != callingUid) { 3180 throw new SecurityException(packageName + " does not belong to uid " + callingUid); 3181 } 3182 } 3183 3184 @Override setPackageScreenCompatMode(String packageName, int mode)3185 public void setPackageScreenCompatMode(String packageName, int mode) { 3186 mActivityTaskManager.setPackageScreenCompatMode(packageName, mode); 3187 } 3188 hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid)3189 private boolean hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid) { 3190 final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS, 3191 callingUid, callingPackage, null, false, "", false).getOpMode(); 3192 if (mode == AppOpsManager.MODE_DEFAULT) { 3193 return checkPermission(Manifest.permission.PACKAGE_USAGE_STATS, callingPid, callingUid) 3194 == PackageManager.PERMISSION_GRANTED; 3195 } 3196 return mode == AppOpsManager.MODE_ALLOWED; 3197 } 3198 hasUsageStatsPermission(String callingPackage)3199 private boolean hasUsageStatsPermission(String callingPackage) { 3200 return hasUsageStatsPermission(callingPackage, 3201 Binder.getCallingUid(), Binder.getCallingPid()); 3202 } 3203 enforceUsageStatsPermission(String callingPackage, int callingUid, int callingPid, String operation)3204 private void enforceUsageStatsPermission(String callingPackage, 3205 int callingUid, int callingPid, String operation) { 3206 if (!hasUsageStatsPermission(callingPackage, callingUid, callingPid)) { 3207 final String errorMsg = "Permission denial for <" + operation + "> from pid=" 3208 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3209 + " which requires PACKAGE_USAGE_STATS permission"; 3210 throw new SecurityException(errorMsg); 3211 } 3212 } 3213 3214 @Override getPackageProcessState(String packageName, String callingPackage)3215 public int getPackageProcessState(String packageName, String callingPackage) { 3216 if (!hasUsageStatsPermission(callingPackage)) { 3217 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 3218 "getPackageProcessState"); 3219 } 3220 3221 final int[] procState = {PROCESS_STATE_NONEXISTENT}; 3222 synchronized (mProcLock) { 3223 mProcessList.forEachLruProcessesLOSP(false, proc -> { 3224 if (procState[0] > proc.mState.getSetProcState()) { 3225 if (proc.getPkgList().containsKey(packageName) || (proc.getPkgDeps() != null 3226 && proc.getPkgDeps().contains(packageName))) { 3227 procState[0] = proc.mState.getSetProcState(); 3228 } 3229 } 3230 }); 3231 } 3232 return procState[0]; 3233 } 3234 3235 @Override setProcessMemoryTrimLevel(String process, int userId, int level)3236 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) 3237 throws RemoteException { 3238 if (!isCallerShell()) { 3239 throw new SecurityException("Only shell can call it"); 3240 } 3241 synchronized (this) { 3242 final ProcessRecord app = findProcessLOSP(process, userId, "setProcessMemoryTrimLevel"); 3243 if (app == null) { 3244 throw new IllegalArgumentException("Unknown process: " + process); 3245 } 3246 final IApplicationThread thread = app.getThread(); 3247 if (thread == null) { 3248 throw new IllegalArgumentException("Process has no app thread"); 3249 } 3250 if (app.mProfile.getTrimMemoryLevel() >= level) { 3251 throw new IllegalArgumentException( 3252 "Unable to set a higher trim level than current level"); 3253 } 3254 if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || 3255 app.mState.getCurProcState() > PROCESS_STATE_IMPORTANT_FOREGROUND)) { 3256 throw new IllegalArgumentException("Unable to set a background trim level " 3257 + "on a foreground process"); 3258 } 3259 thread.scheduleTrimMemory(level); 3260 synchronized (mProcLock) { 3261 app.mProfile.setTrimMemoryLevel(level); 3262 } 3263 return true; 3264 } 3265 } 3266 dispatchOomAdjObserver(String msg)3267 void dispatchOomAdjObserver(String msg) { 3268 OomAdjObserver observer; 3269 synchronized (mOomAdjObserverLock) { 3270 observer = mCurOomAdjObserver; 3271 } 3272 3273 if (observer != null) { 3274 observer.onOomAdjMessage(msg); 3275 } 3276 } 3277 setOomAdjObserver(int uid, OomAdjObserver observer)3278 void setOomAdjObserver(int uid, OomAdjObserver observer) { 3279 synchronized (mOomAdjObserverLock) { 3280 mCurOomAdjUid = uid; 3281 mCurOomAdjObserver = observer; 3282 } 3283 } 3284 clearOomAdjObserver()3285 void clearOomAdjObserver() { 3286 synchronized (mOomAdjObserverLock) { 3287 mCurOomAdjUid = -1; 3288 mCurOomAdjObserver = null; 3289 } 3290 } 3291 reportUidInfoMessageLocked(String tag, String msg, int uid)3292 void reportUidInfoMessageLocked(String tag, String msg, int uid) { 3293 Slog.i(TAG, msg); 3294 synchronized (mOomAdjObserverLock) { 3295 if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) { 3296 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget(); 3297 } 3298 } 3299 } 3300 3301 /** 3302 * @deprecated use {@link #startActivityWithFeature} instead 3303 */ 3304 @Deprecated 3305 @Override startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3306 public int startActivity(IApplicationThread caller, String callingPackage, 3307 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3308 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { 3309 return mActivityTaskManager.startActivity(caller, callingPackage, null, intent, 3310 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 3311 } 3312 3313 @Override startActivityWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3314 public int startActivityWithFeature(IApplicationThread caller, String callingPackage, 3315 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, 3316 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, 3317 Bundle bOptions) { 3318 return mActivityTaskManager.startActivity(caller, callingPackage, callingFeatureId, intent, 3319 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 3320 } 3321 3322 /** 3323 * @deprecated use {@link #startActivityAsUserWithFeature} instead 3324 */ 3325 @Deprecated 3326 @Override startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3327 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 3328 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3329 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 3330 return startActivityAsUserWithFeature(caller, callingPackage, null, intent, resolvedType, 3331 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId); 3332 } 3333 3334 @Override startActivityAsUserWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3335 public final int startActivityAsUserWithFeature(IApplicationThread caller, 3336 String callingPackage, String callingFeatureId, Intent intent, String resolvedType, 3337 IBinder resultTo, String resultWho, int requestCode, int startFlags, 3338 ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 3339 return mActivityTaskManager.startActivityAsUser(caller, callingPackage, 3340 callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, 3341 startFlags, profilerInfo, bOptions, userId); 3342 } 3343 startActivityAndWait(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3344 WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 3345 @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, 3346 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, 3347 Bundle bOptions, int userId) { 3348 return mActivityTaskManager.startActivityAndWait(caller, callingPackage, 3349 callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, 3350 startFlags, profilerInfo, bOptions, userId); 3351 } 3352 3353 @Override startActivityFromRecents(int taskId, Bundle bOptions)3354 public final int startActivityFromRecents(int taskId, Bundle bOptions) { 3355 return mActivityTaskManager.startActivityFromRecents(taskId, bOptions); 3356 } 3357 3358 /** 3359 * This is the internal entry point for handling Activity.finish(). 3360 * 3361 * @param token The Binder token referencing the Activity we want to finish. 3362 * @param resultCode Result code, if any, from this Activity. 3363 * @param resultData Result data (Intent), if any, from this Activity. 3364 * @param finishTask Whether to finish the task associated with this Activity. 3365 * 3366 * @return Returns true if the activity successfully finished, or false if it is still running. 3367 */ 3368 @Override finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3369 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 3370 int finishTask) { 3371 return ActivityClient.getInstance().finishActivity(token, resultCode, resultData, 3372 finishTask); 3373 } 3374 3375 @Override setRequestedOrientation(IBinder token, int requestedOrientation)3376 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 3377 ActivityClient.getInstance().setRequestedOrientation(token, requestedOrientation); 3378 } 3379 3380 @Override finishHeavyWeightApp()3381 public final void finishHeavyWeightApp() { 3382 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3383 != PackageManager.PERMISSION_GRANTED) { 3384 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 3385 + Binder.getCallingPid() 3386 + ", uid=" + Binder.getCallingUid() 3387 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3388 Slog.w(TAG, msg); 3389 throw new SecurityException(msg); 3390 } 3391 mAtmInternal.finishHeavyWeightApp(); 3392 } 3393 3394 @Override crashApplicationWithType(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId)3395 public void crashApplicationWithType(int uid, int initialPid, String packageName, int userId, 3396 String message, boolean force, int exceptionTypeId) { 3397 crashApplicationWithTypeWithExtras(uid, initialPid, packageName, userId, message, 3398 force, exceptionTypeId, null); 3399 } 3400 3401 @Override crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId, @Nullable Bundle extras)3402 public void crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, 3403 int userId, String message, boolean force, int exceptionTypeId, 3404 @Nullable Bundle extras) { 3405 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3406 != PackageManager.PERMISSION_GRANTED) { 3407 String msg = "Permission Denial: crashApplication() from pid=" 3408 + Binder.getCallingPid() 3409 + ", uid=" + Binder.getCallingUid() 3410 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3411 Slog.w(TAG, msg); 3412 throw new SecurityException(msg); 3413 } 3414 3415 synchronized(this) { 3416 mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId, 3417 message, force, exceptionTypeId, extras); 3418 } 3419 } 3420 3421 /** 3422 * Main function for removing an existing process from the activity manager 3423 * as a result of that process going away. Clears out all connections 3424 * to the process. 3425 */ 3426 @GuardedBy("this") handleAppDiedLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, boolean fromBinderDied)3427 final void handleAppDiedLocked(ProcessRecord app, int pid, 3428 boolean restarting, boolean allowRestart, boolean fromBinderDied) { 3429 boolean kept = cleanUpApplicationRecordLocked(app, pid, restarting, allowRestart, -1, 3430 false /*replacingPid*/, fromBinderDied); 3431 if (!kept && !restarting) { 3432 removeLruProcessLocked(app); 3433 if (pid > 0) { 3434 ProcessList.remove(pid); 3435 } 3436 } 3437 3438 mAppProfiler.onAppDiedLocked(app); 3439 3440 mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> { 3441 Slog.w(TAG, "Crash of app " + app.processName 3442 + " running instrumentation " + app.getActiveInstrumentation().mClass); 3443 Bundle info = new Bundle(); 3444 info.putString("shortMsg", "Process crashed."); 3445 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 3446 }); 3447 } 3448 3449 @GuardedBy(anyOf = {"this", "mProcLock"}) getRecordForAppLOSP(IApplicationThread thread)3450 ProcessRecord getRecordForAppLOSP(IApplicationThread thread) { 3451 if (thread == null) { 3452 return null; 3453 } 3454 return getRecordForAppLOSP(thread.asBinder()); 3455 } 3456 3457 @GuardedBy(anyOf = {"this", "mProcLock"}) getRecordForAppLOSP(IBinder threadBinder)3458 ProcessRecord getRecordForAppLOSP(IBinder threadBinder) { 3459 if (threadBinder == null) { 3460 return null; 3461 } 3462 3463 ProcessRecord record = mProcessList.getLRURecordForAppLOSP(threadBinder); 3464 if (record != null) return record; 3465 3466 // Validation: if it isn't in the LRU list, it shouldn't exist, but let's double-check that. 3467 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 3468 mProcessList.getProcessNamesLOSP().getMap(); 3469 for (int i = pmap.size()-1; i >= 0; i--) { 3470 final SparseArray<ProcessRecord> procs = pmap.valueAt(i); 3471 for (int j = procs.size()-1; j >= 0; j--) { 3472 final ProcessRecord proc = procs.valueAt(j); 3473 final IApplicationThread procThread = proc.getThread(); 3474 if (procThread != null && procThread.asBinder() == threadBinder) { 3475 if (!proc.isPendingFinishAttach()) { 3476 Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: " 3477 + proc); 3478 } 3479 return proc; 3480 } 3481 } 3482 } 3483 3484 return null; 3485 } 3486 3487 @GuardedBy("this") appDiedLocked(ProcessRecord app, String reason)3488 final void appDiedLocked(ProcessRecord app, String reason) { 3489 appDiedLocked(app, app.getPid(), app.getThread(), false, reason); 3490 } 3491 3492 @GuardedBy("this") appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied, String reason)3493 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, 3494 boolean fromBinderDied, String reason) { 3495 // First check if this ProcessRecord is actually active for the pid. 3496 final ProcessRecord curProc; 3497 synchronized (mPidsSelfLocked) { 3498 curProc = mPidsSelfLocked.get(pid); 3499 } 3500 if (curProc != app) { 3501 if (!fromBinderDied || !mProcessList.handleDyingAppDeathLocked(app, pid)) { 3502 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc); 3503 } 3504 return; 3505 } 3506 3507 mBatteryStatsService.noteProcessDied(app.info.uid, pid); 3508 3509 if (!app.isKilled()) { 3510 if (!fromBinderDied) { 3511 killProcessQuiet(pid); 3512 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_OTHER, 3513 ApplicationExitInfo.SUBREASON_UNKNOWN, reason); 3514 } 3515 app.killProcessGroupIfNecessaryLocked(true); 3516 synchronized (mProcLock) { 3517 app.setKilled(true); 3518 } 3519 } 3520 3521 // Clean up already done if the process has been re-started. 3522 IApplicationThread appThread; 3523 final int setAdj = app.mState.getSetAdj(); 3524 final int setProcState = app.mState.getSetProcState(); 3525 if (app.getPid() == pid && (appThread = app.getThread()) != null 3526 && appThread.asBinder() == thread.asBinder()) { 3527 boolean doLowMem = app.getActiveInstrumentation() == null; 3528 boolean doOomAdj = doLowMem; 3529 if (!app.isKilledByAm()) { 3530 reportUidInfoMessageLocked(TAG, 3531 "Process " + app.processName + " (pid " + pid + ") has died: " 3532 + ProcessList.makeOomAdjString(setAdj, true) + " " 3533 + ProcessList.makeProcStateString(setProcState), app.info.uid); 3534 mAppProfiler.setAllowLowerMemLevelLocked(true); 3535 } else { 3536 // Note that we always want to do oom adj to update our state with the 3537 // new number of procs. 3538 mAppProfiler.setAllowLowerMemLevelLocked(false); 3539 doLowMem = false; 3540 } 3541 if (doOomAdj) { 3542 if (Flags.migrateFullOomadjUpdates()) { 3543 app.forEachConnectionHost((host) -> enqueueOomAdjTargetLocked(host)); 3544 } 3545 } 3546 3547 EventLogTags.writeAmProcDied(app.userId, pid, app.processName, setAdj, setProcState); 3548 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 3549 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder()); 3550 handleAppDiedLocked(app, pid, false, true, fromBinderDied); 3551 3552 if (doOomAdj) { 3553 if (Flags.migrateFullOomadjUpdates()) { 3554 updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_PROCESS_END); 3555 } else { 3556 updateOomAdjLocked(OOM_ADJ_REASON_PROCESS_END); 3557 } 3558 } 3559 if (doLowMem) { 3560 mAppProfiler.doLowMemReportIfNeededLocked(app); 3561 } 3562 } else if (app.getPid() != pid) { 3563 // A new process has already been started. 3564 reportUidInfoMessageLocked(TAG, 3565 "Process " + app.processName + " (pid " + pid 3566 + ") has died and restarted (pid " + app.getPid() + ").", app.info.uid); 3567 3568 EventLogTags.writeAmProcDied(app.userId, app.getPid(), app.processName, 3569 setAdj, setProcState); 3570 } else if (DEBUG_PROCESSES) { 3571 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread " 3572 + thread.asBinder()); 3573 } 3574 3575 // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal 3576 // for pulling memory stats of other running processes when this process died. 3577 if (!hasMemcg()) { 3578 FrameworkStatsLog.write(FrameworkStatsLog.APP_DIED, SystemClock.elapsedRealtime()); 3579 } 3580 } 3581 3582 @Override clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)3583 public boolean clearApplicationUserData(final String packageName, boolean keepState, 3584 final IPackageDataObserver observer, int userId) { 3585 return clearApplicationUserData(packageName, keepState, /*isRestore=*/ false, observer, 3586 userId); 3587 } 3588 clearApplicationUserData(final String packageName, boolean keepState, boolean isRestore, final IPackageDataObserver observer, int userId)3589 private boolean clearApplicationUserData(final String packageName, boolean keepState, 3590 boolean isRestore, final IPackageDataObserver observer, int userId) { 3591 enforceNotIsolatedCaller("clearApplicationUserData"); 3592 int uid = Binder.getCallingUid(); 3593 int pid = Binder.getCallingPid(); 3594 EventLog.writeEvent(EventLogTags.AM_CLEAR_APP_DATA_CALLER, pid, uid, packageName); 3595 final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false, 3596 ALLOW_FULL_ONLY, "clearApplicationUserData", null); 3597 3598 final ApplicationInfo appInfo; 3599 final boolean isInstantApp; 3600 3601 final long callingId = Binder.clearCallingIdentity(); 3602 try { 3603 IPackageManager pm = AppGlobals.getPackageManager(); 3604 boolean permitted = true; 3605 // Instant packages are not protected 3606 if (getPackageManagerInternal().isPackageDataProtected( 3607 resolvedUserId, packageName)) { 3608 if (ActivityManager.checkUidPermission(android.Manifest.permission.MANAGE_USERS, 3609 uid) == PERMISSION_GRANTED) { 3610 // The caller has the MANAGE_USERS permission, tell them what's going on. 3611 throw new SecurityException( 3612 "Cannot clear data for a protected package: " + packageName); 3613 } else { 3614 permitted = false; // fall through and throw the SecurityException below. 3615 } 3616 } 3617 3618 ApplicationInfo applicationInfo = null; 3619 if (permitted) { 3620 try { 3621 applicationInfo = pm.getApplicationInfo(packageName, 3622 MATCH_UNINSTALLED_PACKAGES, resolvedUserId); 3623 } catch (RemoteException e) { 3624 /* ignore */ 3625 } 3626 permitted = (applicationInfo != null && applicationInfo.uid == uid) // own uid data 3627 || (checkComponentPermission(permission.CLEAR_APP_USER_DATA, 3628 pid, uid, -1, true) == PackageManager.PERMISSION_GRANTED); 3629 } 3630 3631 if (!permitted) { 3632 throw new SecurityException("PID " + pid + " does not have permission " 3633 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 3634 + " of package " + packageName); 3635 } 3636 appInfo = applicationInfo; 3637 3638 final boolean hasInstantMetadata = getPackageManagerInternal() 3639 .hasInstantApplicationMetadata(packageName, resolvedUserId); 3640 final boolean isUninstalledAppWithoutInstantMetadata = 3641 (appInfo == null && !hasInstantMetadata); 3642 isInstantApp = (appInfo != null && appInfo.isInstantApp()) 3643 || hasInstantMetadata; 3644 final boolean canAccessInstantApps = checkComponentPermission( 3645 permission.ACCESS_INSTANT_APPS, pid, uid, -1, true) 3646 == PackageManager.PERMISSION_GRANTED; 3647 3648 if (isUninstalledAppWithoutInstantMetadata || (isInstantApp 3649 && !canAccessInstantApps)) { 3650 Slog.w(TAG, "Invalid packageName: " + packageName); 3651 if (observer != null) { 3652 try { 3653 observer.onRemoveCompleted(packageName, false); 3654 } catch (RemoteException e) { 3655 Slog.i(TAG, "Observer no longer exists."); 3656 } 3657 } 3658 return false; 3659 } 3660 3661 synchronized (this) { 3662 if (appInfo != null) { 3663 forceStopPackageLocked(packageName, appInfo.uid, "clear data"); 3664 mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId); 3665 } 3666 } 3667 3668 final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() { 3669 @Override 3670 public void onRemoveCompleted(String packageName, boolean succeeded) 3671 throws RemoteException { 3672 if (appInfo != null) { 3673 synchronized (ActivityManagerService.this) { 3674 finishForceStopPackageLocked(packageName, appInfo.uid); 3675 } 3676 } 3677 3678 if (succeeded) { 3679 3680 mPackageManagerInt.sendPackageDataClearedBroadcast(packageName, 3681 ((appInfo != null) ? appInfo.uid : INVALID_UID), resolvedUserId, 3682 isRestore, isInstantApp); 3683 } 3684 3685 if (observer != null) { 3686 observer.onRemoveCompleted(packageName, succeeded); 3687 } 3688 } 3689 }; 3690 3691 try { 3692 // Clear application user data 3693 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId); 3694 3695 if (appInfo != null) { 3696 // Restore already established notification state and permission grants, 3697 // so it told us to keep those intact -- it's about to emplace app data 3698 // that is appropriate for those bits of system state. 3699 if (!keepState) { 3700 // Remove all permissions granted from/to this package 3701 mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId, 3702 true, false); 3703 3704 // Reset notification state 3705 INotificationManager inm = NotificationManager.getService(); 3706 inm.clearData(packageName, appInfo.uid, uid == appInfo.uid); 3707 } 3708 3709 // Clear its scheduled jobs 3710 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 3711 // Clearing data is a user-initiated action. 3712 js.cancelJobsForUid(appInfo.uid, /* includeProxiedJobs */ true, 3713 JobParameters.STOP_REASON_USER, 3714 JobParameters.INTERNAL_STOP_REASON_DATA_CLEARED, "clear data"); 3715 3716 // Clear its pending alarms 3717 AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class); 3718 ami.removeAlarmsForUid(appInfo.uid); 3719 } 3720 } catch (RemoteException e) { 3721 } 3722 } finally { 3723 Binder.restoreCallingIdentity(callingId); 3724 } 3725 return true; 3726 } 3727 3728 @Override killBackgroundProcesses(final String packageName, int userId)3729 public void killBackgroundProcesses(final String packageName, int userId) { 3730 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3731 != PackageManager.PERMISSION_GRANTED && 3732 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 3733 != PackageManager.PERMISSION_GRANTED) { 3734 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 3735 + Binder.getCallingPid() 3736 + ", uid=" + Binder.getCallingUid() 3737 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3738 Slog.w(TAG, msg); 3739 throw new SecurityException(msg); 3740 } 3741 final boolean hasKillAllPermission = checkCallingPermission( 3742 android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES) == PERMISSION_GRANTED; 3743 final int callingUid = Binder.getCallingUid(); 3744 final int callingAppId = UserHandle.getAppId(callingUid); 3745 3746 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, 3747 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 3748 final int[] userIds = mUserController.expandUserId(userId); 3749 3750 final long callingId = Binder.clearCallingIdentity(); 3751 try { 3752 IPackageManager pm = AppGlobals.getPackageManager(); 3753 for (int targetUserId : userIds) { 3754 int appId = -1; 3755 try { 3756 appId = UserHandle.getAppId( 3757 pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 3758 targetUserId)); 3759 } catch (RemoteException e) { 3760 } 3761 if (appId == -1 || (!hasKillAllPermission && appId != callingAppId)) { 3762 Slog.w(TAG, "Invalid packageName: " + packageName); 3763 return; 3764 } 3765 synchronized (this) { 3766 synchronized (mProcLock) { 3767 mProcessList.killPackageProcessesLSP(packageName, appId, targetUserId, 3768 ProcessList.SERVICE_ADJ, ApplicationExitInfo.REASON_USER_REQUESTED, 3769 ApplicationExitInfo.SUBREASON_KILL_BACKGROUND, "kill background"); 3770 } 3771 } 3772 } 3773 } finally { 3774 Binder.restoreCallingIdentity(callingId); 3775 } 3776 } 3777 3778 @Override killAllBackgroundProcesses()3779 public void killAllBackgroundProcesses() { 3780 if (checkCallingPermission(android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES) 3781 != PackageManager.PERMISSION_GRANTED) { 3782 final String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 3783 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3784 + " requires " + android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES; 3785 Slog.w(TAG, msg); 3786 throw new SecurityException(msg); 3787 } 3788 3789 final long callingId = Binder.clearCallingIdentity(); 3790 try { 3791 synchronized (this) { 3792 // Allow memory level to go down (the flag needs to be set before updating oom adj) 3793 // because this method is also used to simulate low memory. 3794 mAppProfiler.setAllowLowerMemLevelLocked(true); 3795 synchronized (mProcLock) { 3796 mProcessList.killPackageProcessesLSP(null /* packageName */, -1 /* appId */, 3797 UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ, 3798 ApplicationExitInfo.REASON_USER_REQUESTED, 3799 ApplicationExitInfo.SUBREASON_KILL_BACKGROUND, 3800 "kill all background"); 3801 } 3802 3803 mAppProfiler.doLowMemReportIfNeededLocked(null); 3804 } 3805 } finally { 3806 Binder.restoreCallingIdentity(callingId); 3807 } 3808 } 3809 3810 /** 3811 * Kills all background processes, except those matching any of the 3812 * specified properties. 3813 * 3814 * @param minTargetSdk the target SDK version at or above which to preserve 3815 * processes, or {@code -1} to ignore the target SDK 3816 * @param maxProcState the process state at or below which to preserve 3817 * processes, or {@code -1} to ignore the process state 3818 */ killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)3819 void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 3820 if (checkCallingPermission(android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES) 3821 != PackageManager.PERMISSION_GRANTED) { 3822 final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid=" 3823 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3824 + " requires " + android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES; 3825 Slog.w(TAG, msg); 3826 throw new SecurityException(msg); 3827 } 3828 3829 final long callingId = Binder.clearCallingIdentity(); 3830 try { 3831 synchronized (this) { 3832 synchronized (mProcLock) { 3833 mProcessList.killAllBackgroundProcessesExceptLSP(minTargetSdk, maxProcState); 3834 } 3835 } 3836 } finally { 3837 Binder.restoreCallingIdentity(callingId); 3838 } 3839 } 3840 3841 @Override stopAppForUser(final String packageName, int userId)3842 public void stopAppForUser(final String packageName, int userId) { 3843 if (checkCallingPermission(MANAGE_ACTIVITY_TASKS) 3844 != PackageManager.PERMISSION_GRANTED) { 3845 String msg = "Permission Denial: stopAppForUser() from pid=" 3846 + Binder.getCallingPid() 3847 + ", uid=" + Binder.getCallingUid() 3848 + " requires " + MANAGE_ACTIVITY_TASKS; 3849 Slog.w(TAG, msg); 3850 throw new SecurityException(msg); 3851 } 3852 3853 final int callingPid = Binder.getCallingPid(); 3854 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 3855 userId, true, ALLOW_FULL_ONLY, "stopAppForUser", null); 3856 final long callingId = Binder.clearCallingIdentity(); 3857 try { 3858 stopAppForUserInternal(packageName, userId); 3859 } finally { 3860 Binder.restoreCallingIdentity(callingId); 3861 } 3862 } 3863 3864 @Override registerForegroundServiceObserver(IForegroundServiceObserver callback)3865 public boolean registerForegroundServiceObserver(IForegroundServiceObserver callback) { 3866 final int callingUid = Binder.getCallingUid(); 3867 final int permActivityTasks = checkCallingPermission(MANAGE_ACTIVITY_TASKS); 3868 final int permAcrossUsersFull = checkCallingPermission(INTERACT_ACROSS_USERS_FULL); 3869 if (permActivityTasks != PackageManager.PERMISSION_GRANTED 3870 || permAcrossUsersFull != PERMISSION_GRANTED) { 3871 String msg = "Permission Denial: registerForegroundServiceObserver() from pid=" 3872 + Binder.getCallingPid() 3873 + ", uid=" + callingUid 3874 + " requires " + MANAGE_ACTIVITY_TASKS 3875 + " and " + INTERACT_ACROSS_USERS_FULL; 3876 Slog.w(TAG, msg); 3877 throw new SecurityException(msg); 3878 } 3879 3880 synchronized (this) { 3881 return mServices.registerForegroundServiceObserverLocked(callingUid, callback); 3882 } 3883 } 3884 3885 @Override forceStopPackage(final String packageName, int userId)3886 public void forceStopPackage(final String packageName, int userId) { 3887 forceStopPackage(packageName, userId, /*flags=*/ 0, null); 3888 } 3889 3890 @Override forceStopPackageEvenWhenStopping(final String packageName, int userId)3891 public void forceStopPackageEvenWhenStopping(final String packageName, int userId) { 3892 forceStopPackage(packageName, userId, ActivityManager.FLAG_OR_STOPPED, null); 3893 } 3894 forceStopPackage(final String packageName, int userId, int userRunningFlags, String reason)3895 private void forceStopPackage(final String packageName, int userId, int userRunningFlags, 3896 String reason) { 3897 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3898 != PackageManager.PERMISSION_GRANTED) { 3899 String msg = "Permission Denial: forceStopPackage() from pid=" 3900 + Binder.getCallingPid() 3901 + ", uid=" + Binder.getCallingUid() 3902 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3903 Slog.w(TAG, msg); 3904 throw new SecurityException(msg); 3905 } 3906 final int callingPid = Binder.getCallingPid(); 3907 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 3908 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 3909 final long callingId = Binder.clearCallingIdentity(); 3910 try { 3911 IPackageManager pm = AppGlobals.getPackageManager(); 3912 synchronized (this) { 3913 int[] users = userId == UserHandle.USER_ALL 3914 ? mUserController.getUsers() : new int[] { userId }; 3915 for (int user : users) { 3916 if (getPackageManagerInternal().isPackageStateProtected( 3917 packageName, user)) { 3918 Slog.w(TAG, "Ignoring request to force stop protected package " 3919 + packageName + " u" + user); 3920 return; 3921 } 3922 3923 int pkgUid = -1; 3924 try { 3925 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 3926 user); 3927 } catch (RemoteException e) { 3928 } 3929 if (pkgUid == -1) { 3930 Slog.w(TAG, "Invalid packageName: " + packageName); 3931 continue; 3932 } 3933 try { 3934 pm.setPackageStoppedState(packageName, true, user); 3935 } catch (RemoteException e) { 3936 } catch (IllegalArgumentException e) { 3937 Slog.w(TAG, "Failed trying to unstop package " 3938 + packageName + ": " + e); 3939 } 3940 if (mUserController.isUserRunning(user, userRunningFlags)) { 3941 3942 String description; 3943 if (reason == null) { 3944 description = "from pid " + callingPid; 3945 3946 // Add the name of the process if it's available 3947 final ProcessRecord callerApp; 3948 synchronized (mPidsSelfLocked) { 3949 callerApp = mPidsSelfLocked.get(callingPid); 3950 } 3951 if (callerApp != null) { 3952 description += " (" + callerApp.processName + ")"; 3953 } 3954 } else { 3955 description = reason; 3956 } 3957 3958 forceStopPackageLocked(packageName, UserHandle.getAppId(pkgUid), 3959 false /* callerWillRestart */, false /* purgeCache */, 3960 true /* doIt */, false /* evenPersistent */, 3961 false /* uninstalling */, true /* packageStateStopped */, 3962 user, description); 3963 finishForceStopPackageLocked(packageName, pkgUid); 3964 } 3965 } 3966 } 3967 } finally { 3968 Binder.restoreCallingIdentity(callingId); 3969 } 3970 } 3971 3972 @Override addPackageDependency(String packageName)3973 public void addPackageDependency(String packageName) { 3974 int callingPid = Binder.getCallingPid(); 3975 if (callingPid == myPid()) { 3976 // Yeah, um, no. 3977 return; 3978 } 3979 final int callingUid = Binder.getCallingUid(); 3980 final int callingUserId = UserHandle.getUserId(callingUid); 3981 if (getPackageManagerInternal().filterAppAccess(packageName, callingUid, callingUserId)) { 3982 Slog.w(TAG, "Failed trying to add dependency on non-existing package: " + packageName); 3983 return; 3984 } 3985 ProcessRecord proc; 3986 synchronized (mPidsSelfLocked) { 3987 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 3988 } 3989 if (proc != null) { 3990 ArraySet<String> pkgDeps = proc.getPkgDeps(); 3991 synchronized (this) { 3992 synchronized (mProcLock) { 3993 if (pkgDeps == null) { 3994 proc.setPkgDeps(pkgDeps = new ArraySet<String>(1)); 3995 } 3996 pkgDeps.add(packageName); 3997 } 3998 } 3999 } 4000 } 4001 4002 /* 4003 * The pkg name and app id have to be specified. 4004 */ 4005 @Override killApplication(String pkg, int appId, int userId, String reason, int exitInfoReason)4006 public void killApplication(String pkg, int appId, int userId, String reason, 4007 int exitInfoReason) { 4008 if (pkg == null) { 4009 return; 4010 } 4011 // Make sure the uid is valid. 4012 if (appId < 0) { 4013 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 4014 return; 4015 } 4016 int callerUid = Binder.getCallingUid(); 4017 // Only the system server can kill an application 4018 if (UserHandle.getAppId(callerUid) == SYSTEM_UID) { 4019 // Post an aysnc message to kill the application 4020 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 4021 msg.arg1 = appId; 4022 msg.arg2 = userId; 4023 SomeArgs args = SomeArgs.obtain(); 4024 args.arg1 = pkg; 4025 args.arg2 = reason; 4026 args.arg3 = exitInfoReason; 4027 msg.obj = args; 4028 mHandler.sendMessage(msg); 4029 } else { 4030 throw new SecurityException(callerUid + " cannot kill pkg: " + 4031 pkg); 4032 } 4033 } 4034 4035 @Override closeSystemDialogs(String reason)4036 public void closeSystemDialogs(String reason) { 4037 mAtmInternal.closeSystemDialogs(reason); 4038 } 4039 4040 @Override getProcessMemoryInfo(int[] pids)4041 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 4042 enforceNotIsolatedCaller("getProcessMemoryInfo"); 4043 4044 final long now = SystemClock.uptimeMillis(); 4045 final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME; 4046 4047 final int callingPid = Binder.getCallingPid(); 4048 final int callingUid = Binder.getCallingUid(); 4049 final int callingUserId = UserHandle.getUserId(callingUid); 4050 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 4051 callingUid) == PackageManager.PERMISSION_GRANTED; 4052 // Check REAL_GET_TASKS to see if they are allowed to access other uids 4053 final boolean allUids = mAtmInternal.isGetTasksAllowed( 4054 "getProcessMemoryInfo", callingPid, callingUid); 4055 4056 // Check if the caller is actually instrumented and from shell, if it's true, we may lift 4057 // the throttle of PSS info sampling. 4058 boolean isCallerInstrumentedFromShell = false; 4059 synchronized (mProcLock) { 4060 synchronized (mPidsSelfLocked) { 4061 ProcessRecord caller = mPidsSelfLocked.get(callingPid); 4062 if (caller != null) { 4063 final ActiveInstrumentation instr = caller.getActiveInstrumentation(); 4064 isCallerInstrumentedFromShell = instr != null 4065 && (instr.mSourceUid == SHELL_UID || instr.mSourceUid == ROOT_UID); 4066 } 4067 } 4068 } 4069 4070 final Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 4071 for (int i=pids.length-1; i>=0; i--) { 4072 final Debug.MemoryInfo mi = infos[i] = new Debug.MemoryInfo(); 4073 final ProcessRecord proc; 4074 final int oomAdj; 4075 final ProcessProfileRecord profile; 4076 synchronized (mAppProfiler.mProfilerLock) { 4077 synchronized (mPidsSelfLocked) { 4078 proc = mPidsSelfLocked.get(pids[i]); 4079 if (proc != null) { 4080 profile = proc.mProfile; 4081 oomAdj = profile.getSetAdj(); 4082 } else { 4083 profile = null; 4084 oomAdj = 0; 4085 } 4086 } 4087 } 4088 final int targetUid = (proc != null) ? proc.uid : -1; 4089 final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1; 4090 4091 if (callingUid != targetUid) { 4092 if (!allUids) { 4093 continue; // Not allowed to see other UIDs. 4094 } 4095 4096 if (!allUsers && (targetUserId != callingUserId)) { 4097 continue; // Not allowed to see other users. 4098 } 4099 } 4100 if (proc != null) { 4101 synchronized (mAppProfiler.mProfilerLock) { 4102 if (profile.getLastMemInfoTime() >= lastNow && profile.getLastMemInfo() != null 4103 && !isCallerInstrumentedFromShell) { 4104 // It hasn't been long enough that we want to take another sample; return 4105 // the last one. 4106 mi.set(profile.getLastMemInfo()); 4107 continue; 4108 } 4109 } 4110 } 4111 final long startTime = SystemClock.currentThreadTimeMillis(); 4112 final Debug.MemoryInfo memInfo = new Debug.MemoryInfo(); 4113 Debug.getMemoryInfo(pids[i], memInfo); 4114 final long duration = SystemClock.currentThreadTimeMillis() - startTime; 4115 mi.set(memInfo); 4116 if (proc != null) { 4117 synchronized (mAppProfiler.mProfilerLock) { 4118 profile.setLastMemInfo(memInfo); 4119 profile.setLastMemInfoTime(SystemClock.uptimeMillis()); 4120 if (profile.getThread() != null && profile.getSetAdj() == oomAdj) { 4121 // Record this for posterity if the process has been stable. 4122 profile.addPss(mi.getTotalPss(), 4123 mi.getTotalUss(), mi.getTotalRss(), false, 4124 ProcessStats.ADD_PSS_EXTERNAL_SLOW, duration); 4125 } 4126 } 4127 } 4128 } 4129 return infos; 4130 } 4131 4132 @Override getProcessPss(int[] pids)4133 public long[] getProcessPss(int[] pids) { 4134 enforceNotIsolatedCaller("getProcessPss"); 4135 4136 final int callingPid = Binder.getCallingPid(); 4137 final int callingUid = Binder.getCallingUid(); 4138 final int userId = UserHandle.getUserId(callingUid); 4139 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 4140 callingUid) == PackageManager.PERMISSION_GRANTED; 4141 // Check REAL_GET_TASKS to see if they are allowed to access other uids 4142 final boolean allUids = mAtmInternal.isGetTasksAllowed( 4143 "getProcessPss", callingPid, callingUid); 4144 4145 final long[] pss = new long[pids.length]; 4146 for (int i=pids.length-1; i>=0; i--) { 4147 ProcessRecord proc; 4148 int oomAdj; 4149 synchronized (mProcLock) { 4150 synchronized (mPidsSelfLocked) { 4151 proc = mPidsSelfLocked.get(pids[i]); 4152 oomAdj = proc != null ? proc.mState.getSetAdj() : 0; 4153 } 4154 } 4155 if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) { 4156 // The caller is not allow to get information about this other process... 4157 // just leave it empty. 4158 continue; 4159 } 4160 final long[] tmpUss = new long[3]; 4161 final long startTime = SystemClock.currentThreadTimeMillis(); 4162 final long pi = pss[i] = Debug.getPss(pids[i], tmpUss, null); 4163 final long duration = SystemClock.currentThreadTimeMillis() - startTime; 4164 if (proc != null) { 4165 final ProcessProfileRecord profile = proc.mProfile; 4166 synchronized (mAppProfiler.mProfilerLock) { 4167 if (profile.getThread() != null && profile.getSetAdj() == oomAdj) { 4168 // Record this for posterity if the process has been stable. 4169 profile.addPss(pi, tmpUss[0], tmpUss[2], false, 4170 ProcessStats.ADD_PSS_EXTERNAL, duration); 4171 } 4172 } 4173 } 4174 } 4175 return pss; 4176 } 4177 4178 @Override killApplicationProcess(String processName, int uid)4179 public void killApplicationProcess(String processName, int uid) { 4180 if (processName == null) { 4181 return; 4182 } 4183 4184 int callerUid = Binder.getCallingUid(); 4185 // Only the system server can kill an application 4186 if (callerUid == SYSTEM_UID) { 4187 synchronized (this) { 4188 ProcessRecord app = getProcessRecordLocked(processName, uid); 4189 IApplicationThread thread; 4190 if (app != null && (thread = app.getThread()) != null) { 4191 try { 4192 thread.scheduleSuicide(); 4193 } catch (RemoteException e) { 4194 // If the other end already died, then our work here is done. 4195 } 4196 } else { 4197 Slog.w(TAG, "Process/uid not found attempting kill of " 4198 + processName + " / " + uid); 4199 } 4200 } 4201 } else { 4202 throw new SecurityException(callerUid + " cannot kill app process: " + 4203 processName); 4204 } 4205 } 4206 4207 @GuardedBy("this") forceStopPackageLocked(final String packageName, int uid, String reason)4208 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 4209 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 4210 false, true, false, false, false, UserHandle.getUserId(uid), reason); 4211 } 4212 4213 @GuardedBy("this") finishForceStopPackageLocked(final String packageName, int uid)4214 private void finishForceStopPackageLocked(final String packageName, int uid) { 4215 int flags = 0; 4216 if (!mProcessesReady) { 4217 flags = Intent.FLAG_RECEIVER_REGISTERED_ONLY 4218 | Intent.FLAG_RECEIVER_FOREGROUND; 4219 } 4220 mPackageManagerInt.sendPackageRestartedBroadcast(packageName, uid, flags); 4221 } 4222 cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4223 private void cleanupDisabledPackageComponentsLocked( 4224 String packageName, int userId, String[] changedClasses) { 4225 4226 Set<String> disabledClasses = null; 4227 boolean packageDisabled = false; 4228 IPackageManager pm = AppGlobals.getPackageManager(); 4229 4230 if (changedClasses == null) { 4231 // Nothing changed... 4232 return; 4233 } 4234 4235 // Determine enable/disable state of the package and its components. 4236 int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4237 for (int i = changedClasses.length - 1; i >= 0; i--) { 4238 final String changedClass = changedClasses[i]; 4239 4240 if (changedClass.equals(packageName)) { 4241 try { 4242 // Entire package setting changed 4243 enabled = pm.getApplicationEnabledSetting(packageName, 4244 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4245 } catch (Exception e) { 4246 // No such package/component; probably racing with uninstall. In any 4247 // event it means we have nothing further to do here. 4248 return; 4249 } 4250 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4251 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4252 if (packageDisabled) { 4253 // Entire package is disabled. 4254 // No need to continue to check component states. 4255 disabledClasses = null; 4256 break; 4257 } 4258 } else { 4259 try { 4260 enabled = pm.getComponentEnabledSetting( 4261 new ComponentName(packageName, changedClass), 4262 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4263 } catch (Exception e) { 4264 // As above, probably racing with uninstall. 4265 return; 4266 } 4267 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4268 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) { 4269 if (disabledClasses == null) { 4270 disabledClasses = new ArraySet<>(changedClasses.length); 4271 } 4272 disabledClasses.add(changedClass); 4273 } 4274 } 4275 } 4276 4277 if (!packageDisabled && disabledClasses == null) { 4278 // Nothing to do here... 4279 return; 4280 } 4281 4282 mAtmInternal.cleanupDisabledPackageComponents( 4283 packageName, disabledClasses, userId, mBooted); 4284 4285 // Clean-up disabled services. 4286 mServices.bringDownDisabledPackageServicesLocked( 4287 packageName, disabledClasses, userId, false /* evenPersistent */, 4288 false /* fullStop */, true /* doIt */); 4289 4290 // Clean-up disabled providers. 4291 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4292 mCpHelper.getProviderMap().collectPackageProvidersLocked( 4293 packageName, disabledClasses, true, false, userId, providers); 4294 for (int i = providers.size() - 1; i >= 0; i--) { 4295 mCpHelper.removeDyingProviderLocked(null, providers.get(i), true); 4296 } 4297 4298 // Clean-up disabled broadcast receivers. 4299 mBroadcastQueue.cleanupDisabledPackageReceiversLocked( 4300 packageName, disabledClasses, userId); 4301 4302 } 4303 clearBroadcastQueueForUserLocked(int userId)4304 final boolean clearBroadcastQueueForUserLocked(int userId) { 4305 boolean didSomething = mBroadcastQueue.cleanupDisabledPackageReceiversLocked( 4306 null, null, userId); 4307 return didSomething; 4308 } 4309 4310 @GuardedBy("this") forceStopAppZygoteLocked(String packageName, int appId, int userId)4311 final void forceStopAppZygoteLocked(String packageName, int appId, int userId) { 4312 if (packageName == null) { 4313 return; 4314 } 4315 if (appId < 0) { 4316 appId = UserHandle.getAppId(getPackageManagerInternal().getPackageUid(packageName, 4317 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM)); 4318 } 4319 4320 mProcessList.killAppZygotesLocked(packageName, appId, userId, true /* force */); 4321 } 4322 stopAppForUserInternal(final String packageName, @UserIdInt final int userId)4323 void stopAppForUserInternal(final String packageName, @UserIdInt final int userId) { 4324 final int uid = getPackageManagerInternal().getPackageUid(packageName, 4325 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, userId); 4326 if (uid < 0) { 4327 Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId 4328 + " but does not exist in that user"); 4329 return; 4330 } 4331 4332 // Policy: certain classes of app are not subject to user-invoked stop 4333 if (getPackageManagerInternal().isPackageStateProtected(packageName, userId)) { 4334 Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId 4335 + " but it is protected"); 4336 return; 4337 } 4338 4339 Slog.i(TAG, "Stopping app for user: " + packageName + "/" + userId); 4340 4341 // A specific subset of the work done in forceStopPackageLocked(), because we are 4342 // intentionally not rendering the app nonfunctional; we're just halting its current 4343 // execution. 4344 final int appId = UserHandle.getAppId(uid); 4345 synchronized (this) { 4346 synchronized (mProcLock) { 4347 mAtmInternal.onForceStopPackage(packageName, true, false, userId); 4348 4349 mProcessList.killPackageProcessesLSP(packageName, appId, userId, 4350 ProcessList.INVALID_ADJ, true, false, true, 4351 false, true /* setRemoved */, false, 4352 ApplicationExitInfo.REASON_USER_REQUESTED, 4353 ApplicationExitInfo.SUBREASON_STOP_APP, 4354 "fully stop " + packageName + "/" + userId + " by user request"); 4355 } 4356 4357 mServices.bringDownDisabledPackageServicesLocked( 4358 packageName, null, userId, false, true, true); 4359 mServices.onUidRemovedLocked(uid); 4360 4361 if (mBooted) { 4362 mAtmInternal.resumeTopActivities(true); 4363 } 4364 } 4365 } 4366 4367 @GuardedBy("this") forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, int userId, String reasonString)4368 final boolean forceStopPackageLocked(String packageName, int appId, 4369 boolean callerWillRestart, boolean purgeCache, boolean doit, 4370 boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, 4371 int userId, String reasonString) { 4372 int reason = packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED 4373 : ApplicationExitInfo.REASON_USER_REQUESTED; 4374 return forceStopPackageLocked(packageName, appId, callerWillRestart, purgeCache, doit, 4375 evenPersistent, uninstalling, packageStateStopped, userId, reasonString, reason); 4376 4377 } 4378 4379 @GuardedBy("this") forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, int userId, String reasonString, int reason)4380 final boolean forceStopPackageLocked(String packageName, int appId, 4381 boolean callerWillRestart, boolean purgeCache, boolean doit, 4382 boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, 4383 int userId, String reasonString, int reason) { 4384 int i; 4385 4386 if (userId == UserHandle.USER_ALL && packageName == null) { 4387 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 4388 } 4389 4390 final int uid = getPackageManagerInternal().getPackageUid(packageName, 4391 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM); 4392 if (appId < 0 && packageName != null) { 4393 appId = UserHandle.getAppId(uid); 4394 } 4395 4396 boolean didSomething; 4397 if (doit) { 4398 if (packageName != null) { 4399 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId 4400 + " user=" + userId + ": " + reasonString); 4401 } else { 4402 Slog.i(TAG, "Force stopping u" + userId + ": " + reasonString); 4403 } 4404 4405 mAppErrors.resetProcessCrashTime(packageName == null, appId, userId); 4406 } 4407 4408 synchronized (mProcLock) { 4409 // Notify first that the package is stopped, so its process won't be restarted 4410 // unexpectedly if there is an activity of the package without attached process 4411 // becomes visible when killing its other processes with visible activities. 4412 didSomething = mAtmInternal.onForceStopPackage( 4413 packageName, doit, evenPersistent, userId); 4414 int subReason; 4415 if (reason == ApplicationExitInfo.REASON_USER_REQUESTED) { 4416 subReason = ApplicationExitInfo.SUBREASON_FORCE_STOP; 4417 } else { 4418 subReason = ApplicationExitInfo.SUBREASON_UNKNOWN; 4419 } 4420 4421 didSomething |= mProcessList.killPackageProcessesLSP(packageName, appId, userId, 4422 ProcessList.INVALID_ADJ, callerWillRestart, false /* allowRestart */, doit, 4423 evenPersistent, true /* setRemoved */, uninstalling, 4424 reason, 4425 subReason, 4426 (packageName == null ? ("stop user " + userId) : ("stop " + packageName)) 4427 + " due to " + reasonString); 4428 } 4429 4430 if (mServices.bringDownDisabledPackageServicesLocked( 4431 packageName, null /* filterByClasses */, userId, evenPersistent, true, doit)) { 4432 if (!doit) { 4433 return true; 4434 } 4435 didSomething = true; 4436 } 4437 mServices.onUidRemovedLocked(uid); 4438 4439 if (packageName == null) { 4440 // Remove all sticky broadcasts from this user. 4441 synchronized (mStickyBroadcasts) { 4442 mStickyBroadcasts.remove(userId); 4443 } 4444 } 4445 4446 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4447 if (mCpHelper.getProviderMap().collectPackageProvidersLocked(packageName, null, doit, 4448 evenPersistent, userId, providers)) { 4449 if (!doit) { 4450 return true; 4451 } 4452 didSomething = true; 4453 } 4454 for (i = providers.size() - 1; i >= 0; i--) { 4455 mCpHelper.removeDyingProviderLocked(null, providers.get(i), true); 4456 } 4457 4458 // Remove transient permissions granted from/to this package/user 4459 mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false); 4460 4461 if (doit) { 4462 didSomething |= mBroadcastQueue.cleanupDisabledPackageReceiversLocked( 4463 packageName, null, userId); 4464 } 4465 4466 boolean clearPendingIntentsForStoppedApp = false; 4467 try { 4468 clearPendingIntentsForStoppedApp = (packageStateStopped 4469 && android.content.pm.Flags.stayStopped()); 4470 } catch (IllegalStateException e) { 4471 // It's unlikely for a package to be force-stopped early in the boot cycle. So, if we 4472 // check for 'packageStateStopped' which should evaluate to 'false', then this should 4473 // ensure we are not accessing the flag early in the boot cycle. As an additional 4474 // safety measure, catch the exception and ignore to avoid causing a device restart. 4475 clearPendingIntentsForStoppedApp = false; 4476 } 4477 if (packageName == null || uninstalling || clearPendingIntentsForStoppedApp) { 4478 final int cancelReason; 4479 if (packageName == null) { 4480 cancelReason = PendingIntentRecord.CANCEL_REASON_USER_STOPPED; 4481 } else if (uninstalling) { 4482 cancelReason = PendingIntentRecord.CANCEL_REASON_OWNER_UNINSTALLED; 4483 } else { 4484 cancelReason = PendingIntentRecord.CANCEL_REASON_OWNER_FORCE_STOPPED; 4485 } 4486 didSomething |= mPendingIntentController.removePendingIntentsForPackage( 4487 packageName, userId, appId, doit, cancelReason); 4488 } 4489 4490 if (doit) { 4491 if (purgeCache && packageName != null) { 4492 AttributeCache ac = AttributeCache.instance(); 4493 if (ac != null) { 4494 ac.removePackage(packageName); 4495 } 4496 } 4497 if (mBooted) { 4498 mAtmInternal.resumeTopActivities(true /* scheduleIdle */); 4499 } 4500 } 4501 4502 return didSomething; 4503 } 4504 4505 @GuardedBy("this") handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout)4506 void handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout) { 4507 final int pid = app.getPid(); 4508 boolean gone = isKillTimeout || removePidLocked(pid, app); 4509 4510 if (gone) { 4511 if (isKillTimeout) { 4512 // It's still alive... maybe blocked at uninterruptible sleep ? 4513 final ProcessRecord successor = app.mSuccessor; 4514 if (successor == null) { 4515 // There might be a race, nothing to do here. 4516 return; 4517 } 4518 Slog.wtf(TAG, app.toString() + " " + app.getDyingPid() 4519 + " refused to die while trying to launch " + successor 4520 + ", cancelling the process start"); 4521 4522 // It doesn't make sense to proceed with launching the new instance while the old 4523 // instance is still alive, abort the launch. 4524 app.mSuccessorStartRunnable = null; 4525 app.mSuccessor = null; 4526 successor.mPredecessor = null; 4527 4528 // We're going to cleanup the successor process record, which wasn't started at all. 4529 app = successor; 4530 } else { 4531 final String msg = "Process " + app + " failed to attach"; 4532 Slog.w(TAG, msg); 4533 EventLogTags.writeAmProcessStartTimeout(app.userId, pid, app.uid, app.processName); 4534 if (app.getActiveInstrumentation() != null) { 4535 final Bundle info = new Bundle(); 4536 info.putString("shortMsg", "failed to attach"); 4537 info.putString("longMsg", msg); 4538 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 4539 } 4540 } 4541 synchronized (mProcLock) { 4542 mProcessList.removeProcessNameLocked(app.processName, app.uid); 4543 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 4544 // Take care of any launching providers waiting for this process. 4545 mCpHelper.cleanupAppInLaunchingProvidersLocked(app, true); 4546 // Take care of any services that are waiting for the process. 4547 mServices.processStartTimedOutLocked(app); 4548 // Take care of any broadcasts waiting for the process. 4549 mBroadcastQueue.onApplicationTimeoutLocked(app); 4550 if (!isKillTimeout) { 4551 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 4552 app.killLocked("start timeout", 4553 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true); 4554 removeLruProcessLocked(app); 4555 } 4556 if (app.isolated) { 4557 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 4558 mProcessList.mAppExitInfoTracker.mIsolatedUidRecords.removeIsolatedUid( 4559 app.uid, app.info.uid); 4560 getPackageManagerInternal().removeIsolatedUid(app.uid); 4561 } 4562 } 4563 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4564 if (!isKillTimeout && backupTarget != null && backupTarget.app.getPid() == pid) { 4565 Slog.w(TAG, "Unattached app died before backup, skipping"); 4566 final int userId = app.userId; 4567 final String packageName = app.info.packageName; 4568 mHandler.post(new Runnable() { 4569 @Override 4570 public void run() { 4571 try { 4572 IBackupManager bm = IBackupManager.Stub.asInterface( 4573 ServiceManager.getService(Context.BACKUP_SERVICE)); 4574 bm.agentDisconnectedForUser(userId, packageName); 4575 } catch (RemoteException e) { 4576 // Can't happen; the backup manager is local 4577 } 4578 } 4579 }); 4580 } 4581 } else { 4582 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 4583 } 4584 } 4585 4586 @GuardedBy("this") attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4587 private void attachApplicationLocked(@NonNull IApplicationThread thread, 4588 int pid, int callingUid, long startSeq) { 4589 // Find the application record that is being attached... either via 4590 // the pid if we are running in multiple processes, or just pull the 4591 // next app record if we are emulating process with anonymous threads. 4592 ProcessRecord app; 4593 long startTime = SystemClock.uptimeMillis(); 4594 long bindApplicationTimeMillis; 4595 long bindApplicationTimeNanos; 4596 if (pid != MY_PID && pid >= 0) { 4597 synchronized (mPidsSelfLocked) { 4598 app = mPidsSelfLocked.get(pid); 4599 } 4600 if (app != null && (app.getStartUid() != callingUid || app.getStartSeq() != startSeq)) { 4601 String processName = null; 4602 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4603 if (pending != null) { 4604 processName = pending.processName; 4605 } 4606 final String msg = "attachApplicationLocked process:" + processName 4607 + " startSeq:" + startSeq 4608 + " pid:" + pid 4609 + " belongs to another existing app:" + app.processName 4610 + " startSeq:" + app.getStartSeq(); 4611 Slog.wtf(TAG, msg); 4612 // SafetyNet logging for b/131105245. 4613 EventLog.writeEvent(0x534e4554, "131105245", app.getStartUid(), msg); 4614 // If there is already an app occupying that pid that hasn't been cleaned up 4615 cleanUpApplicationRecordLocked(app, pid, false, false, -1, 4616 true /*replacingPid*/, false /* fromBinderDied */); 4617 removePidLocked(pid, app); 4618 app = null; 4619 } 4620 } else { 4621 app = null; 4622 } 4623 4624 // It's possible that process called attachApplication before we got a chance to 4625 // update the internal state. 4626 if (app == null && startSeq > 0) { 4627 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4628 if (pending != null && pending.getStartUid() == callingUid 4629 && pending.getStartSeq() == startSeq 4630 && mProcessList.handleProcessStartedLocked(pending, pid, 4631 pending.isUsingWrapper(), startSeq, true)) { 4632 app = pending; 4633 } 4634 } 4635 4636 if (app == null) { 4637 Slog.w(TAG, "No pending application record for pid " + pid 4638 + " (IApplicationThread " + thread + "); dropping process"); 4639 EventLogTags.writeAmDropProcess(pid); 4640 if (pid > 0 && pid != MY_PID) { 4641 killProcessQuiet(pid); 4642 //TODO: killProcessGroup(app.info.uid, pid); 4643 // We can't log the app kill info for this process since we don't 4644 // know who it is, so just skip the logging. 4645 } else { 4646 try { 4647 thread.scheduleExit(); 4648 } catch (Exception e) { 4649 // Ignore exceptions. 4650 } 4651 } 4652 return; 4653 } 4654 4655 // If this application record is still attached to a previous 4656 // process, clean it up now. 4657 if (app.getThread() != null) { 4658 handleAppDiedLocked(app, pid, true, true, false /* fromBinderDied */); 4659 } 4660 4661 // Tell the process all about itself. 4662 4663 if (DEBUG_ALL) Slog.v( 4664 TAG, "Binding process pid " + pid + " to record " + app); 4665 4666 final String processName = app.processName; 4667 try { 4668 AppDeathRecipient adr = new AppDeathRecipient( 4669 app, pid, thread); 4670 thread.asBinder().linkToDeath(adr, 0); 4671 app.setDeathRecipient(adr); 4672 } catch (RemoteException e) { 4673 app.resetPackageList(mProcessStats); 4674 mProcessList.startProcessLocked(app, 4675 new HostingRecord(HostingRecord.HOSTING_TYPE_LINK_FAIL, processName), 4676 ZYGOTE_POLICY_FLAG_EMPTY); 4677 return; 4678 } 4679 4680 EventLogTags.writeAmProcBound(app.userId, pid, app.processName); 4681 4682 synchronized (mProcLock) { 4683 mOomAdjuster.setAttachingProcessStatesLSP(app); 4684 clearProcessForegroundLocked(app); 4685 app.setDebugging(false); 4686 app.setKilledByAm(false); 4687 app.setKilled(false); 4688 // We carefully use the same state that PackageManager uses for 4689 // filtering, since we use this flag to decide if we need to install 4690 // providers when user is unlocked later 4691 app.setUnlocked(StorageManager.isCeStorageUnlocked(app.userId)); 4692 } 4693 4694 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4695 List<ProviderInfo> providers = normalMode 4696 ? mCpHelper.generateApplicationProvidersLocked(app) 4697 : null; 4698 4699 if (providers != null && mCpHelper.checkAppInLaunchingProvidersLocked(app)) { 4700 Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG); 4701 msg.obj = app; 4702 mHandler.sendMessageDelayed(msg, 4703 ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS); 4704 } 4705 4706 checkTime(startTime, "attachApplicationLocked: before bindApplication"); 4707 4708 if (!normalMode) { 4709 Slog.i(TAG, "Launching preboot mode app: " + app); 4710 } 4711 4712 if (DEBUG_ALL) Slog.v( 4713 TAG, "New app record " + app 4714 + " thread=" + thread.asBinder() + " pid=" + pid); 4715 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4716 try { 4717 int testMode = ApplicationThreadConstants.DEBUG_OFF; 4718 if (mDebugApp != null && mDebugApp.equals(processName)) { 4719 if (mWaitForDebugger) { 4720 if (mSuspendUponWait) { 4721 testMode = ApplicationThreadConstants.DEBUG_SUSPEND; 4722 } else { 4723 testMode = ApplicationThreadConstants.DEBUG_WAIT; 4724 } 4725 } else { 4726 testMode = ApplicationThreadConstants.DEBUG_ON; 4727 } 4728 app.setDebugging(true); 4729 if (mDebugTransient) { 4730 mDebugApp = mOrigDebugApp; 4731 mWaitForDebugger = mOrigWaitForDebugger; 4732 } 4733 } 4734 4735 boolean enableTrackAllocation = false; 4736 synchronized (mProcLock) { 4737 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) { 4738 enableTrackAllocation = true; 4739 mTrackAllocationApp = null; 4740 } 4741 } 4742 4743 // If the app is being launched for restore or full backup, set it up specially 4744 boolean isRestrictedBackupMode = false; 4745 if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) { 4746 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID 4747 && ((backupTarget.backupMode == BackupRecord.RESTORE_FULL) 4748 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL)); 4749 } 4750 4751 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 4752 4753 if (instr != null) { 4754 notifyPackageUse(instr.mClass.getPackageName(), 4755 PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION); 4756 } 4757 ProtoLog.v(WM_DEBUG_CONFIGURATION, "Binding proc %s with config %s", 4758 processName, app.getWindowProcessController().getConfiguration()); 4759 ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info; 4760 app.setCompat(compatibilityInfoForPackage(appInfo)); 4761 4762 ProfilerInfo profilerInfo = mAppProfiler.setupProfilerInfoLocked(thread, app, instr); 4763 4764 // We deprecated Build.SERIAL and it is not accessible to 4765 // Instant Apps and target APIs higher than O MR1. Since access to the serial 4766 // is now behind a permission we push down the value. 4767 final String buildSerial = (!appInfo.isInstantApp() 4768 && appInfo.targetSdkVersion < Build.VERSION_CODES.P) 4769 ? sTheRealBuildSerial : Build.UNKNOWN; 4770 4771 // Figure out whether the app needs to run in autofill compat mode. 4772 AutofillOptions autofillOptions = null; 4773 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 4774 final AutofillManagerInternal afm = LocalServices.getService( 4775 AutofillManagerInternal.class); 4776 if (afm != null) { 4777 autofillOptions = afm.getAutofillOptions( 4778 app.info.packageName, app.info.longVersionCode, app.userId); 4779 } 4780 } 4781 ContentCaptureOptions contentCaptureOptions = null; 4782 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 4783 final ContentCaptureManagerInternal ccm = 4784 LocalServices.getService(ContentCaptureManagerInternal.class); 4785 if (ccm != null) { 4786 contentCaptureOptions = ccm.getOptionsForPackage(app.userId, 4787 app.info.packageName); 4788 } 4789 } 4790 SharedMemory serializedSystemFontMap = null; 4791 final FontManagerInternal fm = LocalServices.getService(FontManagerInternal.class); 4792 if (fm != null) { 4793 serializedSystemFontMap = fm.getSerializedSystemFontMap(); 4794 } 4795 4796 checkTime(startTime, "attachApplicationLocked: immediately before bindApplication"); 4797 bindApplicationTimeMillis = SystemClock.uptimeMillis(); 4798 bindApplicationTimeNanos = SystemClock.uptimeNanos(); 4799 mAtmInternal.preBindApplication(app.getWindowProcessController()); 4800 final ActiveInstrumentation instr2 = app.getActiveInstrumentation(); 4801 if (mPlatformCompat != null) { 4802 mPlatformCompat.resetReporting(app.info); 4803 } 4804 final ProviderInfoList providerList = ProviderInfoList.fromList(providers); 4805 app.mProfile.mLastCpuDelayTime.set(app.getCpuDelayTime()); 4806 if (app.getIsolatedEntryPoint() != null) { 4807 // This is an isolated process which should just call an entry point instead of 4808 // being bound to an application. 4809 thread.runIsolatedEntryPoint( 4810 app.getIsolatedEntryPoint(), app.getIsolatedEntryPointArgs()); 4811 } else { 4812 boolean isSdkInSandbox = false; 4813 ComponentName instrumentationName = null; 4814 Bundle instrumentationArgs = null; 4815 IInstrumentationWatcher instrumentationWatcher = null; 4816 IUiAutomationConnection instrumentationUiConnection = null; 4817 if (instr2 != null) { 4818 isSdkInSandbox = instr2.mIsSdkInSandbox; 4819 instrumentationName = instr2.mClass; 4820 instrumentationArgs = instr2.mArguments; 4821 instrumentationWatcher = instr2.mWatcher; 4822 instrumentationUiConnection = instr2.mUiAutomationConnection; 4823 } 4824 thread.bindApplication( 4825 processName, 4826 appInfo, 4827 app.sdkSandboxClientAppVolumeUuid, 4828 app.sdkSandboxClientAppPackage, 4829 isSdkInSandbox, 4830 providerList, 4831 instrumentationName, 4832 profilerInfo, 4833 instrumentationArgs, 4834 instrumentationWatcher, 4835 instrumentationUiConnection, 4836 testMode, 4837 mBinderTransactionTrackingEnabled, 4838 enableTrackAllocation, 4839 isRestrictedBackupMode || !normalMode, 4840 app.isPersistent(), 4841 new Configuration(app.getWindowProcessController().getConfiguration()), 4842 app.getCompat(), 4843 getCommonServicesLocked(app.isolated), 4844 mCoreSettingsObserver.getCoreSettingsLocked(), 4845 buildSerial, 4846 autofillOptions, 4847 contentCaptureOptions, 4848 app.getDisabledCompatChanges(), 4849 app.getLoggableCompatChanges(), 4850 serializedSystemFontMap, 4851 app.getStartElapsedTime(), 4852 app.getStartUptime()); 4853 } 4854 4855 Message msg = mHandler.obtainMessage(BIND_APPLICATION_TIMEOUT_SOFT_MSG); 4856 msg.obj = app; 4857 msg.arg1 = BIND_APPLICATION_TIMEOUT; 4858 mHandler.sendMessageDelayed(msg, msg.arg1 /* BIND_APPLICATION_TIMEOUT */); 4859 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4860 4861 if (profilerInfo != null) { 4862 profilerInfo.closeFd(); 4863 profilerInfo = null; 4864 } 4865 4866 app.setBindApplicationTime(bindApplicationTimeMillis); 4867 mProcessList.getAppStartInfoTracker() 4868 .addTimestampToStart(app, bindApplicationTimeNanos, 4869 ApplicationStartInfo.START_TIMESTAMP_BIND_APPLICATION); 4870 4871 // Make app active after binding application or client may be running requests (e.g 4872 // starting activities) before it is ready. 4873 synchronized (mProcLock) { 4874 app.makeActive(thread, mProcessStats); 4875 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication"); 4876 } 4877 app.setPendingFinishAttach(true); 4878 4879 updateLruProcessLocked(app, false, null); 4880 checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked"); 4881 4882 updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN); 4883 checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked"); 4884 4885 final long now = SystemClock.uptimeMillis(); 4886 synchronized (mAppProfiler.mProfilerLock) { 4887 app.mProfile.setLastRequestedGc(now); 4888 app.mProfile.setLastLowMemory(now); 4889 } 4890 4891 // Remove this record from the list of starting applications. 4892 mPersistentStartingProcesses.remove(app); 4893 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) { 4894 Slog.v(TAG_PROCESSES, "Attach application locked removing on hold: " + app); 4895 } 4896 mProcessesOnHold.remove(app); 4897 4898 if (!mConstants.mEnableWaitForFinishAttachApplication) { 4899 finishAttachApplicationInner(startSeq, callingUid, pid); 4900 } 4901 maybeSendBootCompletedLocked(app); 4902 } catch (Exception e) { 4903 // We need kill the process group here. (b/148588589) 4904 Slog.wtf(TAG, "Exception thrown during bind of " + app, e); 4905 app.resetPackageList(mProcessStats); 4906 app.unlinkDeathRecipient(); 4907 app.killLocked("error during bind", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 4908 true); 4909 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */); 4910 return; 4911 } 4912 } 4913 4914 @Override attachApplication(IApplicationThread thread, long startSeq)4915 public final void attachApplication(IApplicationThread thread, long startSeq) { 4916 if (thread == null) { 4917 throw new SecurityException("Invalid application interface"); 4918 } 4919 synchronized (this) { 4920 int callingPid = Binder.getCallingPid(); 4921 final int callingUid = Binder.getCallingUid(); 4922 final long origId = Binder.clearCallingIdentity(); 4923 attachApplicationLocked(thread, callingPid, callingUid, startSeq); 4924 Binder.restoreCallingIdentity(origId); 4925 } 4926 } 4927 finishAttachApplicationInner(long startSeq, int uid, int pid)4928 private void finishAttachApplicationInner(long startSeq, int uid, int pid) { 4929 final long startTime = SystemClock.uptimeMillis(); 4930 // Find the application record that is being attached... either via 4931 // the pid if we are running in multiple processes, or just pull the 4932 // next app record if we are emulating process with anonymous threads. 4933 final ProcessRecord app; 4934 synchronized (mPidsSelfLocked) { 4935 app = mPidsSelfLocked.get(pid); 4936 } 4937 4938 if (app != null && app.getStartUid() == uid && app.getStartSeq() == startSeq) { 4939 mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_SOFT_MSG, app); 4940 mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_HARD_MSG, app); 4941 } else { 4942 Slog.wtf(TAG, "Mismatched or missing ProcessRecord: " + app + ". Pid: " + pid 4943 + ". Uid: " + uid); 4944 if (pid > 0) { 4945 killProcess(pid); 4946 killProcessGroup(uid, pid); 4947 } 4948 mProcessList.noteAppKill(pid, uid, 4949 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 4950 ApplicationExitInfo.SUBREASON_UNKNOWN, 4951 "wrong startSeq"); 4952 synchronized (this) { 4953 app.killLocked("unexpected process record", 4954 ApplicationExitInfo.REASON_OTHER, true); 4955 } 4956 return; 4957 } 4958 4959 synchronized (this) { 4960 // Mark the finish attach application phase as completed 4961 app.setPendingFinishAttach(false); 4962 4963 final boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4964 final String processName = app.processName; 4965 boolean badApp = false; 4966 boolean didSomething = false; 4967 4968 // See if the top visible activity is waiting to run in this process... 4969 if (normalMode) { 4970 try { 4971 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); 4972 } catch (Exception e) { 4973 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); 4974 badApp = true; 4975 } 4976 } 4977 4978 // Find any services that should be running in this process... 4979 if (!badApp) { 4980 try { 4981 didSomething |= mServices.attachApplicationLocked(app, processName); 4982 checkTime(startTime, "finishAttachApplicationInner: " 4983 + "after mServices.attachApplicationLocked"); 4984 } catch (Exception e) { 4985 Slog.wtf(TAG, "Exception thrown starting services in " + app, e); 4986 badApp = true; 4987 } 4988 } 4989 4990 // Check if a next-broadcast receiver is in this process... 4991 if (!badApp) { 4992 try { 4993 didSomething |= mBroadcastQueue.onApplicationAttachedLocked(app); 4994 checkTime(startTime, "finishAttachApplicationInner: " 4995 + "after dispatching broadcasts"); 4996 } catch (BroadcastDeliveryFailedException e) { 4997 // If the app died trying to launch the receiver we declare it 'bad' 4998 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e); 4999 badApp = true; 5000 } 5001 } 5002 5003 // Check whether the next backup agent is in this process... 5004 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 5005 if (!badApp && backupTarget != null && backupTarget.app == app) { 5006 if (DEBUG_BACKUP) { 5007 Slog.v(TAG_BACKUP, 5008 "New app is backup target, launching agent for " + app); 5009 } 5010 5011 notifyPackageUse(backupTarget.appInfo.packageName, 5012 PackageManager.NOTIFY_PACKAGE_USE_BACKUP); 5013 try { 5014 app.getThread().scheduleCreateBackupAgent(backupTarget.appInfo, 5015 backupTarget.backupMode, backupTarget.userId, 5016 backupTarget.backupDestination); 5017 } catch (Exception e) { 5018 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e); 5019 badApp = true; 5020 } 5021 } 5022 5023 if (badApp) { 5024 app.killLocked("error during init", 5025 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true); 5026 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */); 5027 return; 5028 } 5029 5030 if (!didSomething) { 5031 updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN); 5032 checkTime(startTime, "finishAttachApplicationInner: after updateOomAdjLocked"); 5033 } 5034 5035 final HostingRecord hostingRecord = app.getHostingRecord(); 5036 final String shortAction = getShortAction(hostingRecord.getAction()); 5037 FrameworkStatsLog.write( 5038 FrameworkStatsLog.PROCESS_START_TIME, 5039 app.info.uid, 5040 pid, 5041 app.info.packageName, 5042 FrameworkStatsLog.PROCESS_START_TIME__TYPE__COLD, 5043 app.getStartElapsedTime(), 5044 (int) (app.getBindApplicationTime() - app.getStartUptime()), 5045 (int) (SystemClock.uptimeMillis() - app.getStartUptime()), 5046 hostingRecord.getType(), 5047 hostingRecord.getName(), 5048 shortAction, 5049 HostingRecord.getHostingTypeIdStatsd(hostingRecord.getType()), 5050 HostingRecord.getTriggerTypeForStatsd(hostingRecord.getTriggerType())); 5051 } 5052 } 5053 5054 @Override finishAttachApplication(long startSeq, long timestampApplicationOnCreateNs)5055 public final void finishAttachApplication(long startSeq, long timestampApplicationOnCreateNs) { 5056 final int pid = Binder.getCallingPid(); 5057 final int uid = Binder.getCallingUid(); 5058 5059 if (!mConstants.mEnableWaitForFinishAttachApplication) { 5060 Slog.i(TAG, "Flag disabled. Ignoring finishAttachApplication from uid: " 5061 + uid + ". pid: " + pid); 5062 return; 5063 } 5064 5065 if (pid == MY_PID && uid == SYSTEM_UID) { 5066 return; 5067 } 5068 5069 final long origId = Binder.clearCallingIdentity(); 5070 try { 5071 finishAttachApplicationInner(startSeq, uid, pid); 5072 } finally { 5073 Binder.restoreCallingIdentity(origId); 5074 } 5075 5076 if (android.app.Flags.appStartInfoTimestamps() && timestampApplicationOnCreateNs > 0) { 5077 addStartInfoTimestampInternal(ApplicationStartInfo.START_TIMESTAMP_APPLICATION_ONCREATE, 5078 timestampApplicationOnCreateNs, UserHandle.getUserId(uid), uid); 5079 } 5080 } 5081 handleBindApplicationTimeoutSoft(ProcessRecord app, int softTimeoutMillis)5082 private void handleBindApplicationTimeoutSoft(ProcessRecord app, int softTimeoutMillis) { 5083 // Similar logic as the broadcast delivery timeout: 5084 // instead of immediately triggering an ANR, extend the timeout by 5085 // the amount of time the process was runnable-but-waiting; we're 5086 // only willing to do this once before triggering an hard ANR. 5087 final long cpuDelayTime = app.getCpuDelayTime() - app.mProfile.mLastCpuDelayTime.get(); 5088 final long hardTimeoutMillis = MathUtils.constrain(cpuDelayTime, 0, softTimeoutMillis); 5089 5090 if (hardTimeoutMillis == 0) { 5091 handleBindApplicationTimeoutHard(app); 5092 return; 5093 } 5094 5095 Slog.i(TAG, "Extending process start timeout by " + hardTimeoutMillis + "ms for " + app); 5096 Trace.instant(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplicationTimeSoft " 5097 + app.processName + "(" + app.getPid() + ")"); 5098 final Message msg = mHandler.obtainMessage(BIND_APPLICATION_TIMEOUT_HARD_MSG, app); 5099 mHandler.sendMessageDelayed(msg, hardTimeoutMillis); 5100 } 5101 handleBindApplicationTimeoutHard(ProcessRecord app)5102 private void handleBindApplicationTimeoutHard(ProcessRecord app) { 5103 final String anrMessage; 5104 synchronized (app) { 5105 anrMessage = "Process " + app + " failed to complete startup"; 5106 } 5107 5108 mAnrHelper.appNotResponding(app, TimeoutRecord.forAppStart(anrMessage)); 5109 } 5110 handleFollowUpOomAdjusterUpdate()5111 private void handleFollowUpOomAdjusterUpdate() { 5112 // Remove any existing duplicate messages on the handler here while no lock is being held. 5113 // If another follow up update is needed, it will be scheduled by OomAdjuster. 5114 mHandler.removeMessages(FOLLOW_UP_OOMADJUSTER_UPDATE_MSG); 5115 synchronized (this) { 5116 mOomAdjuster.updateOomAdjFollowUpTargetsLocked(); 5117 } 5118 } 5119 5120 /** 5121 * @return The last part of the string of an intent's action. 5122 */ getShortAction(@ullable String action)5123 static @Nullable String getShortAction(@Nullable String action) { 5124 String shortAction = action; 5125 if (action != null) { 5126 int index = action.lastIndexOf('.'); 5127 if (index != -1 && index != action.length() - 1) { 5128 shortAction = action.substring(index + 1); 5129 } 5130 } 5131 return shortAction; 5132 } 5133 checkTime(long startTime, String where)5134 void checkTime(long startTime, String where) { 5135 long now = SystemClock.uptimeMillis(); 5136 if ((now - startTime) > 50) { 5137 // If we are taking more than 50ms, log about it. 5138 Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where); 5139 } 5140 } 5141 5142 /** 5143 * Send LOCKED_BOOT_COMPLETED and BOOT_COMPLETED to the package explicitly when unstopped, 5144 * or when the package first starts in private space 5145 */ maybeSendBootCompletedLocked(ProcessRecord app)5146 private void maybeSendBootCompletedLocked(ProcessRecord app) { 5147 boolean sendBroadcast = false; 5148 if (android.os.Flags.allowPrivateProfile() 5149 && android.multiuser.Flags.enablePrivateSpaceFeatures()) { 5150 final UserManagerInternal umInternal = 5151 LocalServices.getService(UserManagerInternal.class); 5152 UserInfo userInfo = umInternal.getUserInfo(app.userId); 5153 5154 if (userInfo != null && userInfo.isPrivateProfile()) { 5155 // Packages in private space get deferred boot completed whenever they start the 5156 // first time since profile start 5157 if (!mPrivateSpaceBootCompletedPackages.contains(app.info.packageName)) { 5158 mPrivateSpaceBootCompletedPackages.add(app.info.packageName); 5159 sendBroadcast = true; 5160 } // else, stopped packages in private space may still hit the logic below 5161 } 5162 } 5163 5164 final boolean wasForceStopped = app.wasForceStopped() 5165 || app.getWindowProcessController().wasForceStopped(); 5166 if (android.app.Flags.appRestrictionsApi() && wasForceStopped) { 5167 noteAppRestrictionEnabled(app.info.packageName, app.uid, 5168 RESTRICTION_LEVEL_FORCE_STOPPED, false, 5169 RESTRICTION_REASON_USAGE, "unknown", RESTRICTION_SOURCE_USER, 0L); 5170 } 5171 5172 if (!sendBroadcast) { 5173 if (!android.content.pm.Flags.stayStopped()) return; 5174 // Nothing to do if it wasn't previously stopped 5175 if (!wasForceStopped) { 5176 return; 5177 } 5178 } 5179 5180 // Send LOCKED_BOOT_COMPLETED, if necessary 5181 if (app.getApplicationInfo().isEncryptionAware()) { 5182 sendBootBroadcastToAppLocked(app, new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED), 5183 REASON_LOCKED_BOOT_COMPLETED); 5184 } 5185 // Send BOOT_COMPLETED if the user is unlocked 5186 if (StorageManager.isCeStorageUnlocked(app.userId)) { 5187 sendBootBroadcastToAppLocked(app, new Intent(Intent.ACTION_BOOT_COMPLETED), 5188 REASON_BOOT_COMPLETED); 5189 } 5190 // The stopped state is reset in ProcessRecord when the pid changes, to deal with 5191 // any re-use of the ProcessRecord. 5192 } 5193 5194 /** Send a boot_completed broadcast to app */ sendBootBroadcastToAppLocked(ProcessRecord app, Intent intent, @PowerExemptionManager.ReasonCode int reason)5195 private void sendBootBroadcastToAppLocked(ProcessRecord app, Intent intent, 5196 @PowerExemptionManager.ReasonCode int reason) { 5197 intent.setPackage(app.info.packageName); 5198 intent.putExtra(Intent.EXTRA_USER_HANDLE, app.userId); 5199 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT 5200 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND 5201 | Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 5202 5203 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, 5204 new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED}, 5205 null, null, AppOpsManager.OP_NONE, 5206 null, true, 5207 false, MY_PID, SYSTEM_UID, 5208 SYSTEM_UID, MY_PID, app.userId); 5209 } 5210 5211 @Override showBootMessage(final CharSequence msg, final boolean always)5212 public void showBootMessage(final CharSequence msg, final boolean always) { 5213 if (Binder.getCallingUid() != myUid()) { 5214 throw new SecurityException(); 5215 } 5216 mWindowManager.showBootMessage(msg, always); 5217 } 5218 finishBooting()5219 final void finishBooting() { 5220 TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing", 5221 Trace.TRACE_TAG_ACTIVITY_MANAGER); 5222 t.traceBegin("FinishBooting"); 5223 5224 synchronized (this) { 5225 if (!mBootAnimationComplete) { 5226 mCallFinishBooting = true; 5227 return; 5228 } 5229 mCallFinishBooting = false; 5230 } 5231 5232 // Let the ART runtime in zygote and system_server know that the boot completed. 5233 ZYGOTE_PROCESS.bootCompleted(); 5234 VMRuntime.bootCompleted(); 5235 5236 IntentFilter pkgFilter = new IntentFilter(); 5237 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 5238 pkgFilter.addDataScheme("package"); 5239 mContext.registerReceiver(new BroadcastReceiver() { 5240 @Override 5241 public void onReceive(Context context, Intent intent) { 5242 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 5243 if (pkgs != null) { 5244 for (String pkg : pkgs) { 5245 synchronized (ActivityManagerService.this) { 5246 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 5247 false, 0, "query restart")) { 5248 setResultCode(Activity.RESULT_OK); 5249 return; 5250 } 5251 } 5252 } 5253 } 5254 } 5255 }, pkgFilter); 5256 5257 // Inform checkpointing systems of success 5258 try { 5259 // This line is needed to CTS test for the correct exception handling 5260 // See b/138952436#comment36 for context 5261 Slog.i(TAG, "About to commit checkpoint"); 5262 IStorageManager storageManager = InstallLocationUtils.getStorageManager(); 5263 storageManager.commitChanges(); 5264 } catch (Exception e) { 5265 PowerManager pm = (PowerManager) 5266 mInjector.getContext().getSystemService(Context.POWER_SERVICE); 5267 pm.reboot("Checkpoint commit failed"); 5268 } 5269 5270 // Let system services know. 5271 mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED); 5272 5273 synchronized (this) { 5274 // Ensure that any processes we had put on hold are now started 5275 // up. 5276 final int NP = mProcessesOnHold.size(); 5277 if (NP > 0) { 5278 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mProcessesOnHold); 5279 for (int ip = 0; ip < NP; ip++) { 5280 if (DEBUG_PROCESSES) { 5281 Slog.v(TAG_PROCESSES, "Starting process on hold: " + procs.get(ip)); 5282 } 5283 mProcessList.startProcessLocked(procs.get(ip), 5284 new HostingRecord(HostingRecord.HOSTING_TYPE_ON_HOLD), 5285 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 5286 } 5287 } 5288 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 5289 return; 5290 } 5291 // Start looking for apps that are abusing wake locks. 5292 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 5293 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 5294 // Check if we are performing userspace reboot before setting sys.boot_completed to 5295 // avoid race with init reseting sys.init.userspace_reboot.in_progress once sys 5296 // .boot_completed is 1. 5297 if (InitProperties.userspace_reboot_in_progress().orElse(false)) { 5298 UserspaceRebootLogger.noteUserspaceRebootSuccess(); 5299 } 5300 // Tell anyone interested that we are done booting! 5301 SystemProperties.set("sys.boot_completed", "1"); 5302 SystemProperties.set("dev.bootcomplete", "1"); 5303 5304 // Start PSI monitoring in LMKD if it was skipped earlier. 5305 ProcessList.startPsiMonitoringAfterBoot(); 5306 5307 mUserController.onBootComplete( 5308 new IIntentReceiver.Stub() { 5309 @Override 5310 public void performReceive(Intent intent, int resultCode, 5311 String data, Bundle extras, boolean ordered, 5312 boolean sticky, int sendingUser) { 5313 mBootCompletedTimestamp = SystemClock.uptimeMillis(); 5314 // Defer the full Pss collection as the system is really busy now. 5315 mHandler.postDelayed(() -> { 5316 synchronized (mProcLock) { 5317 mAppProfiler.requestPssAllProcsLPr( 5318 SystemClock.uptimeMillis(), true, false); 5319 } 5320 }, mConstants.FULL_PSS_MIN_INTERVAL); 5321 } 5322 }); 5323 maybeLogUserspaceRebootEvent(); 5324 mUserController.scheduleStartProfiles(); 5325 } 5326 // UART is on if init's console service is running, send a warning notification. 5327 showConsoleNotificationIfActive(); 5328 showMteOverrideNotificationIfActive(); 5329 5330 t.traceEnd(); 5331 } 5332 showConsoleNotificationIfActive()5333 private void showConsoleNotificationIfActive() { 5334 if (!SystemProperties.get("init.svc.console").equals("running")) { 5335 return; 5336 } 5337 String title = mContext 5338 .getString(com.android.internal.R.string.console_running_notification_title); 5339 String message = mContext 5340 .getString(com.android.internal.R.string.console_running_notification_message); 5341 Notification notification = 5342 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 5343 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 5344 .setWhen(0) 5345 .setOngoing(true) 5346 .setTicker(title) 5347 .setDefaults(0) // please be quiet 5348 .setColor(mContext.getColor( 5349 com.android.internal.R.color 5350 .system_notification_accent_color)) 5351 .setContentTitle(title) 5352 .setContentText(message) 5353 .setVisibility(Notification.VISIBILITY_PUBLIC) 5354 .build(); 5355 5356 NotificationManager notificationManager = 5357 mContext.getSystemService(NotificationManager.class); 5358 notificationManager.notifyAsUser( 5359 null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL); 5360 5361 } 5362 showMteOverrideNotificationIfActive()5363 private void showMteOverrideNotificationIfActive() { 5364 String bootctl = SystemProperties.get("arm64.memtag.bootctl"); 5365 // If MTE is on, there is one in three cases: 5366 // * a fullmte build: ro.arm64.memtag.bootctl_supported is not set 5367 // * memtag: arm64.memtag.bootctl contains "memtag" 5368 // * memtag-once 5369 // In the condition below we detect memtag-once by exclusion. 5370 if (Arrays.asList(bootctl.split(",")).contains("memtag") 5371 || !SystemProperties.getBoolean("ro.arm64.memtag.bootctl_supported", false) 5372 || !com.android.internal.os.Zygote.nativeSupportsMemoryTagging()) { 5373 return; 5374 } 5375 String title = mContext 5376 .getString(com.android.internal.R.string.mte_override_notification_title); 5377 String message = mContext 5378 .getString(com.android.internal.R.string.mte_override_notification_message); 5379 Notification notification = 5380 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 5381 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 5382 .setOngoing(true) 5383 .setTicker(title) 5384 .setDefaults(0) // please be quiet 5385 .setColor(mContext.getColor( 5386 com.android.internal.R.color 5387 .system_notification_accent_color)) 5388 .setContentTitle(title) 5389 .setContentText(message) 5390 .setVisibility(Notification.VISIBILITY_PUBLIC) 5391 .build(); 5392 5393 NotificationManager notificationManager = 5394 mContext.getSystemService(NotificationManager.class); 5395 notificationManager.notifyAsUser( 5396 null, SystemMessage.NOTE_MTE_OVERRIDE_ENABLED, notification, UserHandle.ALL); 5397 } 5398 5399 @Override bootAnimationComplete()5400 public void bootAnimationComplete() { 5401 if (DEBUG_ALL) Slog.d(TAG, "bootAnimationComplete: Callers=" + Debug.getCallers(4)); 5402 5403 final boolean callFinishBooting; 5404 synchronized (this) { 5405 callFinishBooting = mCallFinishBooting; 5406 mBootAnimationComplete = true; 5407 } 5408 if (callFinishBooting) { 5409 finishBooting(); 5410 } 5411 } 5412 5413 /** 5414 * Starts Home if there is no completion signal from ThemeOverlayController 5415 */ scheduleHomeTimeout()5416 private void scheduleHomeTimeout() { 5417 if (!isHomeLaunchDelayable()) { 5418 Slog.d(TAG, "ThemeHomeDelay: Home launch is not delayable, skipping timeout creation"); 5419 return; 5420 } 5421 5422 if (!mHasHomeDelay.compareAndSet(false, true)) return; 5423 5424 mHandler.postDelayed(() -> { 5425 int userId = mUserController.getCurrentUserId(); 5426 if (!isThemeOverlayReady(userId)) { 5427 Slog.d(TAG, 5428 "ThemeHomeDelay: ThemeOverlayController not responding, launching " 5429 + "Home after " + HOME_LAUNCH_TIMEOUT_MS + "ms" 5430 + " with user " + userId); 5431 setThemeOverlayReady(userId); 5432 } 5433 }, HOME_LAUNCH_TIMEOUT_MS); 5434 5435 } 5436 5437 /** 5438 * Used by ThemeOverlayController to notify when color 5439 * palette is ready. 5440 * 5441 * @param userId The ID of the user where ThemeOverlayController is ready. 5442 * @hide 5443 */ 5444 @Override setThemeOverlayReady(@serIdInt int userId)5445 public void setThemeOverlayReady(@UserIdInt int userId) { 5446 if (!isHomeLaunchDelayable()) { 5447 Slog.d(TAG, "ThemeHomeDelay: Home launch is not delayable, " 5448 + "ignoring setThemeOverlayReady() call"); 5449 return; 5450 } 5451 5452 enforceCallingPermission(Manifest.permission.SET_THEME_OVERLAY_CONTROLLER_READY, 5453 "setThemeOverlayReady"); 5454 Slog.d(TAG, "ThemeHomeDelay: userId " + userId 5455 + " notified ThemeOverlayController completeness"); 5456 boolean updateUser; 5457 synchronized (mThemeOverlayReadyUsers) { 5458 updateUser = mThemeOverlayReadyUsers.add(userId); 5459 Slog.d(TAG, "ThemeHomeDelay: updateUser " + userId + " isUpdatable: " + updateUser); 5460 } 5461 5462 if (updateUser) { 5463 Slog.d(TAG, "ThemeHomeDelay: updating user " + userId); 5464 mAtmInternal.startHomeOnAllDisplays(userId, "setThemeOverlayReady"); 5465 } 5466 } 5467 5468 /** 5469 * Returns current state of ThemeOverlayController color 5470 * palette readiness. 5471 * 5472 * @hide 5473 */ isThemeOverlayReady(int userId)5474 public boolean isThemeOverlayReady(int userId) { 5475 synchronized (mThemeOverlayReadyUsers) { 5476 return mThemeOverlayReadyUsers.contains(userId); 5477 } 5478 } 5479 5480 /** Checks whether the home launch delay feature is enabled. */ isHomeLaunchDelayable()5481 private boolean isHomeLaunchDelayable() { 5482 // This feature is disabled on Auto since it seems to add an unacceptably long boot delay 5483 // without even solving the underlying issue (it merely hits the timeout). 5484 return enableHomeDelay() && 5485 !mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE); 5486 } 5487 ensureBootCompleted()5488 final void ensureBootCompleted() { 5489 boolean booting; 5490 boolean enableScreen; 5491 synchronized (this) { 5492 booting = mBooting; 5493 mBooting = false; 5494 enableScreen = !mBooted; 5495 mBooted = true; 5496 } 5497 5498 if (booting) { 5499 finishBooting(); 5500 } 5501 5502 if (enableScreen) { 5503 mAtmInternal.enableScreenAfterBoot(mBooted); 5504 } 5505 } 5506 5507 /** 5508 * @deprecated Use {@link #getIntentSenderWithFeature} instead 5509 */ 5510 @Deprecated 5511 @Override getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5512 public IIntentSender getIntentSender(int type, 5513 String packageName, IBinder token, String resultWho, 5514 int requestCode, Intent[] intents, String[] resolvedTypes, 5515 int flags, Bundle bOptions, int userId) { 5516 return getIntentSenderWithFeature(type, packageName, null, token, resultWho, requestCode, 5517 intents, resolvedTypes, flags, bOptions, userId); 5518 } 5519 5520 @Override getIntentSenderWithFeature(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5521 public IIntentSender getIntentSenderWithFeature(int type, String packageName, String featureId, 5522 IBinder token, String resultWho, int requestCode, Intent[] intents, 5523 String[] resolvedTypes, int flags, Bundle bOptions, int userId) { 5524 enforceNotIsolatedCaller("getIntentSender"); 5525 5526 return getIntentSenderWithFeatureAsApp(type, packageName, featureId, token, resultWho, 5527 requestCode, intents, resolvedTypes, flags, bOptions, userId, 5528 Binder.getCallingUid()); 5529 } 5530 5531 /** 5532 * System-internal callers can invoke this with owningUid being the app's own identity 5533 * rather than the public API's behavior of always assigning ownership to the actual 5534 * caller identity. This will create an IntentSender as though the package/userid/uid app 5535 * were the caller, so that the ultimate PendingIntent is triggered with only the app's 5536 * capabilities and not the system's. Used in cases like notification groups where 5537 * the OS must synthesize a PendingIntent on an app's behalf. 5538 */ getIntentSenderWithFeatureAsApp(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid)5539 public IIntentSender getIntentSenderWithFeatureAsApp(int type, String packageName, 5540 String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, 5541 String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid) { 5542 // NOTE: The service lock isn't held in this method because nothing in the method requires 5543 // the service lock to be held. 5544 5545 // Refuse possible leaked file descriptors 5546 if (intents != null) { 5547 if (intents.length < 1) { 5548 throw new IllegalArgumentException("Intents array length must be >= 1"); 5549 } 5550 for (int i=0; i<intents.length; i++) { 5551 Intent intent = intents[i]; 5552 if (intent != null) { 5553 if (intent.hasFileDescriptors()) { 5554 throw new IllegalArgumentException("File descriptors passed in Intent"); 5555 } 5556 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 5557 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 5558 throw new IllegalArgumentException( 5559 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 5560 } 5561 boolean isActivityResultType = 5562 type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT; 5563 if (PendingIntent.isNewMutableDisallowedImplicitPendingIntent(flags, intent, 5564 isActivityResultType)) { 5565 boolean isChangeEnabled = CompatChanges.isChangeEnabled( 5566 PendingIntent.BLOCK_MUTABLE_IMPLICIT_PENDING_INTENT, 5567 packageName, UserHandle.of(userId)); 5568 String resolvedType = resolvedTypes == null 5569 || i >= resolvedTypes.length ? null : resolvedTypes[i]; 5570 SaferIntentUtils.reportUnsafeIntentEvent( 5571 UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__NEW_MUTABLE_IMPLICIT_PENDING_INTENT_RETRIEVED, 5572 owningUid, Process.INVALID_PID, 5573 intent, resolvedType, isChangeEnabled); 5574 if (isChangeEnabled) { 5575 String msg = packageName + ": Targeting U+ (version " 5576 + Build.VERSION_CODES.UPSIDE_DOWN_CAKE + " and above) disallows" 5577 + " creating or retrieving a PendingIntent with FLAG_MUTABLE," 5578 + " an implicit Intent within and without FLAG_NO_CREATE and" 5579 + " FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT for" 5580 + " security reasons. To retrieve an already existing" 5581 + " PendingIntent, use FLAG_NO_CREATE, however, to create a" 5582 + " new PendingIntent with an implicit Intent use" 5583 + " FLAG_IMMUTABLE."; 5584 throw new IllegalArgumentException(msg); 5585 } 5586 } 5587 intents[i] = new Intent(intent); 5588 intents[i].removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH); 5589 } 5590 } 5591 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 5592 throw new IllegalArgumentException( 5593 "Intent array length does not match resolvedTypes length"); 5594 } 5595 } 5596 if (bOptions != null) { 5597 if (bOptions.hasFileDescriptors()) { 5598 throw new IllegalArgumentException("File descriptors passed in options"); 5599 } 5600 } 5601 5602 int origUserId = userId; 5603 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), owningUid, userId, 5604 type == ActivityManager.INTENT_SENDER_BROADCAST, 5605 ALLOW_NON_FULL, "getIntentSender", null); 5606 if (origUserId == UserHandle.USER_CURRENT) { 5607 // We don't want to evaluate this until the pending intent is 5608 // actually executed. However, we do want to always do the 5609 // security checking for it above. 5610 userId = UserHandle.USER_CURRENT; 5611 } 5612 5613 if (owningUid != 0 && owningUid != SYSTEM_UID) { 5614 if (!getPackageManagerInternal().isSameApp( 5615 packageName, 5616 MATCH_DEBUG_TRIAGED_MISSING, 5617 owningUid, 5618 UserHandle.getUserId(owningUid))) { 5619 String msg = "Permission Denial: getIntentSender() from pid=" 5620 + Binder.getCallingPid() 5621 + ", uid=" + owningUid 5622 + " is not allowed to send as package " + packageName; 5623 Slog.w(TAG, msg); 5624 throw new SecurityException(msg); 5625 } 5626 } 5627 5628 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 5629 return mAtmInternal.getIntentSender(type, packageName, featureId, owningUid, 5630 userId, token, resultWho, requestCode, intents, resolvedTypes, flags, 5631 bOptions); 5632 } 5633 return mPendingIntentController.getIntentSender(type, packageName, featureId, 5634 owningUid, userId, token, resultWho, requestCode, intents, resolvedTypes, 5635 flags, bOptions); 5636 } 5637 5638 @Override sendIntentSender(IApplicationThread caller, IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5639 public int sendIntentSender(IApplicationThread caller, IIntentSender target, 5640 IBinder allowlistToken, int code, Intent intent, String resolvedType, 5641 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 5642 if (target instanceof PendingIntentRecord) { 5643 final PendingIntentRecord originalRecord = (PendingIntentRecord) target; 5644 5645 // In multi-display scenarios, there can be background users who execute the 5646 // PendingIntent. In these scenarios, we don't want to use the foreground user as the 5647 // current user. 5648 final PendingIntentRecord.Key originalKey = originalRecord.key; 5649 final UserManagerInternal umInternal = 5650 LocalServices.getService(UserManagerInternal.class); 5651 final int callingUserId = UserHandle.getCallingUserId(); 5652 if (UserManager.isVisibleBackgroundUsersEnabled() 5653 && originalKey.userId == UserHandle.USER_CURRENT 5654 && callingUserId != UserHandle.USER_SYSTEM 5655 && umInternal.isUserVisible(callingUserId)) { 5656 EventLogTags.writeAmIntentSenderRedirectUser(callingUserId); 5657 final PendingIntentRecord.Key key = new PendingIntentRecord.Key(originalKey.type, 5658 originalKey.packageName, originalKey.featureId, originalKey.activity, 5659 originalKey.who, originalKey.requestCode, originalKey.allIntents, 5660 originalKey.allResolvedTypes, originalKey.flags, originalKey.options, 5661 callingUserId); 5662 5663 final PendingIntentRecord newRecord = new PendingIntentRecord( 5664 originalRecord.controller, key, originalRecord.uid); 5665 5666 return newRecord.sendWithResult(caller, code, intent, resolvedType, allowlistToken, 5667 finishedReceiver, requiredPermission, options); 5668 } 5669 5670 return originalRecord.sendWithResult(caller, code, intent, resolvedType, allowlistToken, 5671 finishedReceiver, requiredPermission, options); 5672 } else { 5673 if (intent == null) { 5674 // Weird case: someone has given us their own custom IIntentSender, and now 5675 // they have someone else trying to send to it but of course this isn't 5676 // really a PendingIntent, so there is no base Intent, and the caller isn't 5677 // supplying an Intent... but we never want to dispatch a null Intent to 5678 // a receiver, so um... let's make something up. 5679 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call"); 5680 intent = new Intent(Intent.ACTION_MAIN); 5681 } 5682 try { 5683 if (allowlistToken != null) { 5684 final int callingUid = Binder.getCallingUid(); 5685 final String packageName; 5686 final long token = Binder.clearCallingIdentity(); 5687 try { 5688 packageName = AppGlobals.getPackageManager().getNameForUid(callingUid); 5689 } finally { 5690 Binder.restoreCallingIdentity(token); 5691 } 5692 Slog.wtf(TAG, "Send a non-null allowlistToken to a non-PI target." 5693 + " Calling package: " + packageName + "; intent: " + intent 5694 + "; options: " + options); 5695 } 5696 target.send(code, intent, resolvedType, null, null, 5697 requiredPermission, options); 5698 } catch (RemoteException e) { 5699 } 5700 // Platform code can rely on getting a result back when the send is done, but if 5701 // this intent sender is from outside of the system we can't rely on it doing that. 5702 // So instead we don't give it the result receiver, and instead just directly 5703 // report the finish immediately. 5704 if (finishedReceiver != null) { 5705 try { 5706 finishedReceiver.performReceive(intent, 0, 5707 null, null, false, false, UserHandle.getCallingUserId()); 5708 } catch (RemoteException e) { 5709 } 5710 } 5711 return 0; 5712 } 5713 } 5714 5715 @Override cancelIntentSender(IIntentSender sender)5716 public void cancelIntentSender(IIntentSender sender) { 5717 mPendingIntentController.cancelIntentSender(sender); 5718 } 5719 5720 @Override registerIntentSenderCancelListenerEx( IIntentSender sender, IResultReceiver receiver)5721 public boolean registerIntentSenderCancelListenerEx( 5722 IIntentSender sender, IResultReceiver receiver) { 5723 return mPendingIntentController.registerIntentSenderCancelListener(sender, receiver); 5724 } 5725 5726 @Override unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5727 public void unregisterIntentSenderCancelListener(IIntentSender sender, 5728 IResultReceiver receiver) { 5729 mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver); 5730 } 5731 5732 @Override getInfoForIntentSender(IIntentSender sender)5733 public PendingIntentInfo getInfoForIntentSender(IIntentSender sender) { 5734 if (sender instanceof PendingIntentRecord) { 5735 final PendingIntentRecord res = (PendingIntentRecord) sender; 5736 final String packageName = res.key.packageName; 5737 final int uid = res.uid; 5738 final boolean shouldFilter = getPackageManagerInternal().filterAppAccess( 5739 packageName, Binder.getCallingUid(), UserHandle.getUserId(uid)); 5740 return new PendingIntentInfo( 5741 shouldFilter ? null : packageName, 5742 shouldFilter ? INVALID_UID : uid, 5743 (res.key.flags & PendingIntent.FLAG_IMMUTABLE) != 0, 5744 res.key.type); 5745 } else { 5746 return new PendingIntentInfo(null, INVALID_UID, false, 5747 ActivityManager.INTENT_SENDER_UNKNOWN); 5748 } 5749 } 5750 5751 @Override isIntentSenderTargetedToPackage(IIntentSender pendingResult)5752 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 5753 if (!(pendingResult instanceof PendingIntentRecord)) { 5754 return false; 5755 } 5756 try { 5757 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5758 if (res.key.allIntents == null) { 5759 return false; 5760 } 5761 for (int i=0; i<res.key.allIntents.length; i++) { 5762 Intent intent = res.key.allIntents[i]; 5763 if (intent.getPackage() != null && intent.getComponent() != null) { 5764 return false; 5765 } 5766 } 5767 return true; 5768 } catch (ClassCastException e) { 5769 } 5770 return false; 5771 } 5772 5773 @Override isIntentSenderAnActivity(IIntentSender pendingResult)5774 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 5775 if (!(pendingResult instanceof PendingIntentRecord)) { 5776 return false; 5777 } 5778 try { 5779 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5780 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 5781 return true; 5782 } 5783 return false; 5784 } catch (ClassCastException e) { 5785 } 5786 return false; 5787 } 5788 5789 @Override getIntentForIntentSender(IIntentSender pendingResult)5790 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 5791 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5792 "getIntentForIntentSender()"); 5793 if (!(pendingResult instanceof PendingIntentRecord)) { 5794 return null; 5795 } 5796 try { 5797 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5798 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 5799 } catch (ClassCastException e) { 5800 } 5801 return null; 5802 } 5803 5804 @Override queryIntentComponentsForIntentSender( IIntentSender pendingResult, int matchFlags)5805 public ParceledListSlice<ResolveInfo> queryIntentComponentsForIntentSender( 5806 IIntentSender pendingResult, int matchFlags) { 5807 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5808 "queryIntentComponentsForIntentSender()"); 5809 Objects.requireNonNull(pendingResult); 5810 final PendingIntentRecord res; 5811 try { 5812 res = (PendingIntentRecord) pendingResult; 5813 } catch (ClassCastException e) { 5814 return null; 5815 } 5816 final Intent intent = res.key.requestIntent; 5817 if (intent == null) { 5818 return null; 5819 } 5820 final int userId = res.key.userId; 5821 final int uid = res.uid; 5822 final String resolvedType = res.key.requestResolvedType; 5823 switch (res.key.type) { 5824 case ActivityManager.INTENT_SENDER_ACTIVITY: 5825 return new ParceledListSlice<>(mPackageManagerInt.queryIntentActivities( 5826 intent, resolvedType, matchFlags, uid, userId)); 5827 case ActivityManager.INTENT_SENDER_SERVICE: 5828 case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE: 5829 return new ParceledListSlice<>(mPackageManagerInt.queryIntentServices( 5830 intent, matchFlags, uid, userId)); 5831 case ActivityManager.INTENT_SENDER_BROADCAST: 5832 return new ParceledListSlice<>(mPackageManagerInt.queryIntentReceivers( 5833 intent, resolvedType, matchFlags, uid, Process.INVALID_PID, userId, false)); 5834 default: // ActivityManager.INTENT_SENDER_ACTIVITY_RESULT 5835 throw new IllegalStateException("Unsupported intent sender type: " + res.key.type); 5836 } 5837 } 5838 5839 @Override getTagForIntentSender(IIntentSender pendingResult, String prefix)5840 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) { 5841 if (!(pendingResult instanceof PendingIntentRecord)) { 5842 return null; 5843 } 5844 try { 5845 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5846 synchronized (this) { 5847 return getTagForIntentSenderLocked(res, prefix); 5848 } 5849 } catch (ClassCastException e) { 5850 } 5851 return null; 5852 } 5853 getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5854 String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) { 5855 final Intent intent = res.key.requestIntent; 5856 if (intent != null) { 5857 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null 5858 || res.lastTagPrefix.equals(prefix))) { 5859 return res.lastTag; 5860 } 5861 res.lastTagPrefix = prefix; 5862 final StringBuilder sb = new StringBuilder(128); 5863 if (prefix != null) { 5864 sb.append(prefix); 5865 } 5866 if (intent.getAction() != null) { 5867 sb.append(intent.getAction()); 5868 } else if (intent.getComponent() != null) { 5869 intent.getComponent().appendShortString(sb); 5870 } else { 5871 sb.append("?"); 5872 } 5873 return res.lastTag = sb.toString(); 5874 } 5875 return null; 5876 } 5877 5878 @Override setProcessLimit(int max)5879 public void setProcessLimit(int max) { 5880 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5881 "setProcessLimit()"); 5882 synchronized (this) { 5883 mConstants.setOverrideMaxCachedProcesses(max); 5884 trimApplicationsLocked(true, OOM_ADJ_REASON_PROCESS_END); 5885 } 5886 } 5887 5888 @Override getProcessLimit()5889 public int getProcessLimit() { 5890 synchronized (this) { 5891 return mConstants.getOverrideMaxCachedProcesses(); 5892 } 5893 } 5894 importanceTokenDied(ImportanceToken token)5895 void importanceTokenDied(ImportanceToken token) { 5896 synchronized (ActivityManagerService.this) { 5897 ProcessRecord pr = null; 5898 synchronized (mPidsSelfLocked) { 5899 ImportanceToken cur 5900 = mImportantProcesses.get(token.pid); 5901 if (cur != token) { 5902 return; 5903 } 5904 mImportantProcesses.remove(token.pid); 5905 pr = mPidsSelfLocked.get(token.pid); 5906 if (pr == null) { 5907 return; 5908 } 5909 pr.mState.setForcingToImportant(null); 5910 clearProcessForegroundLocked(pr); 5911 } 5912 updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY); 5913 } 5914 } 5915 5916 @Override setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5917 public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) { 5918 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5919 "setProcessImportant()"); 5920 synchronized(this) { 5921 boolean changed = false; 5922 5923 ProcessRecord pr = null; 5924 synchronized (mPidsSelfLocked) { 5925 pr = mPidsSelfLocked.get(pid); 5926 if (pr == null && isForeground) { 5927 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 5928 return; 5929 } 5930 ImportanceToken oldToken = mImportantProcesses.get(pid); 5931 if (oldToken != null) { 5932 oldToken.token.unlinkToDeath(oldToken, 0); 5933 mImportantProcesses.remove(pid); 5934 if (pr != null) { 5935 pr.mState.setForcingToImportant(null); 5936 } 5937 changed = true; 5938 } 5939 if (isForeground && token != null) { 5940 ImportanceToken newToken = new ImportanceToken(pid, token, reason) { 5941 @Override 5942 public void binderDied() { 5943 importanceTokenDied(this); 5944 } 5945 }; 5946 try { 5947 token.linkToDeath(newToken, 0); 5948 mImportantProcesses.put(pid, newToken); 5949 pr.mState.setForcingToImportant(newToken); 5950 changed = true; 5951 } catch (RemoteException e) { 5952 // If the process died while doing this, we will later 5953 // do the cleanup with the process death link. 5954 } 5955 } 5956 } 5957 5958 if (changed) { 5959 updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY); 5960 } 5961 } 5962 } 5963 isAppForeground(int uid)5964 private boolean isAppForeground(int uid) { 5965 synchronized (mProcLock) { 5966 UidRecord uidRec = mProcessList.mActiveUids.get(uid); 5967 if (uidRec == null || uidRec.isIdle()) { 5968 return false; 5969 } 5970 return uidRec.getCurProcState() <= PROCESS_STATE_IMPORTANT_FOREGROUND; 5971 } 5972 } 5973 isAppBad(final String processName, final int uid)5974 private boolean isAppBad(final String processName, final int uid) { 5975 return mAppErrors.isBadProcess(processName, uid); 5976 } 5977 5978 // NOTE: this is an internal method used by the OnShellCommand implementation only and should 5979 // be guarded by permission checking. getUidState(int uid)5980 int getUidState(int uid) { 5981 synchronized (mProcLock) { 5982 return mProcessList.getUidProcStateLOSP(uid); 5983 } 5984 } 5985 5986 @GuardedBy("this") getUidStateLocked(int uid)5987 int getUidStateLocked(int uid) { 5988 return mProcessList.getUidProcStateLOSP(uid); 5989 } 5990 5991 @GuardedBy("this") getUidProcessCapabilityLocked(int uid)5992 int getUidProcessCapabilityLocked(int uid) { 5993 return mProcessList.getUidProcessCapabilityLOSP(uid); 5994 } 5995 5996 // ========================================================= 5997 // PROCESS INFO 5998 // ========================================================= 5999 6000 static class ProcessInfoService extends IProcessInfoService.Stub { 6001 final ActivityManagerService mActivityManagerService; ProcessInfoService(ActivityManagerService activityManagerService)6002 ProcessInfoService(ActivityManagerService activityManagerService) { 6003 mActivityManagerService = activityManagerService; 6004 } 6005 6006 @Override getProcessStatesFromPids( int[] pids, int[] states)6007 public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) { 6008 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 6009 /*in*/ pids, /*out*/ states, null); 6010 } 6011 6012 @Override getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)6013 public void getProcessStatesAndOomScoresFromPids( 6014 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 6015 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 6016 /*in*/ pids, /*out*/ states, /*out*/ scores); 6017 } 6018 } 6019 6020 /** 6021 * For each PID in the given input array, write the current process state 6022 * for that process into the states array, or -1 to indicate that no 6023 * process with the given PID exists. If scores array is provided, write 6024 * the oom score for the process into the scores array, with INVALID_ADJ 6025 * indicating the PID doesn't exist. 6026 */ getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)6027 public void getProcessStatesAndOomScoresForPIDs( 6028 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 6029 if (scores != null) { 6030 enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE, 6031 "getProcessStatesAndOomScoresForPIDs()"); 6032 } 6033 6034 if (pids == null) { 6035 throw new NullPointerException("pids"); 6036 } else if (states == null) { 6037 throw new NullPointerException("states"); 6038 } else if (pids.length != states.length) { 6039 throw new IllegalArgumentException("pids and states arrays have different lengths!"); 6040 } else if (scores != null && pids.length != scores.length) { 6041 throw new IllegalArgumentException("pids and scores arrays have different lengths!"); 6042 } 6043 6044 synchronized (mProcLock) { 6045 int newestTimeIndex = -1; 6046 long newestTime = Long.MIN_VALUE; 6047 for (int i = 0; i < pids.length; i++) { 6048 final ProcessRecord pr; 6049 synchronized (mPidsSelfLocked) { 6050 pr = mPidsSelfLocked.get(pids[i]); 6051 } 6052 if (pr != null) { 6053 final long pendingTopTime = 6054 mPendingStartActivityUids.getPendingTopPidTime(pr.uid, pids[i]); 6055 if (pendingTopTime != PendingStartActivityUids.INVALID_TIME) { 6056 // The uid in mPendingStartActivityUids gets the TOP process state. 6057 states[i] = PROCESS_STATE_TOP; 6058 if (scores != null) { 6059 // The uid in mPendingStartActivityUids gets a better score. 6060 scores[i] = ProcessList.FOREGROUND_APP_ADJ - 1; 6061 } 6062 if (pendingTopTime > newestTime) { 6063 newestTimeIndex = i; 6064 newestTime = pendingTopTime; 6065 } 6066 } else { 6067 states[i] = pr.mState.getCurProcState(); 6068 if (scores != null) { 6069 scores[i] = pr.mState.getCurAdj(); 6070 } 6071 } 6072 } else { 6073 states[i] = PROCESS_STATE_NONEXISTENT; 6074 if (scores != null) { 6075 scores[i] = ProcessList.INVALID_ADJ; 6076 } 6077 } 6078 } 6079 // The uid with the newest timestamp in mPendingStartActivityUids gets the best 6080 // score. 6081 if (newestTimeIndex != -1) { 6082 if (scores != null) { 6083 scores[newestTimeIndex] = ProcessList.FOREGROUND_APP_ADJ - 2; 6084 } 6085 } 6086 } 6087 } 6088 6089 // ========================================================= 6090 // PERMISSIONS 6091 // ========================================================= 6092 6093 static class PermissionController extends IPermissionController.Stub { 6094 ActivityManagerService mActivityManagerService; PermissionController(ActivityManagerService activityManagerService)6095 PermissionController(ActivityManagerService activityManagerService) { 6096 mActivityManagerService = activityManagerService; 6097 } 6098 6099 @Override checkPermission(String permission, int pid, int uid)6100 public boolean checkPermission(String permission, int pid, int uid) { 6101 return mActivityManagerService.checkPermission(permission, pid, 6102 uid) == PackageManager.PERMISSION_GRANTED; 6103 } 6104 6105 @Override noteOp(String op, int uid, String packageName)6106 public int noteOp(String op, int uid, String packageName) { 6107 // TODO moltmann: Allow to specify featureId 6108 return mActivityManagerService.mAppOpsService 6109 .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName, null, 6110 false, "", false).getOpMode(); 6111 } 6112 6113 @Override getPackagesForUid(int uid)6114 public String[] getPackagesForUid(int uid) { 6115 return mActivityManagerService.mContext.getPackageManager() 6116 .getPackagesForUid(uid); 6117 } 6118 6119 @Override isRuntimePermission(String permission)6120 public boolean isRuntimePermission(String permission) { 6121 try { 6122 PermissionInfo info = mActivityManagerService.mContext.getPackageManager() 6123 .getPermissionInfo(permission, 0); 6124 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 6125 == PermissionInfo.PROTECTION_DANGEROUS; 6126 } catch (NameNotFoundException nnfe) { 6127 Slog.e(TAG, "No such permission: "+ permission, nnfe); 6128 } 6129 return false; 6130 } 6131 6132 @Override getPackageUid(String packageName, int flags)6133 public int getPackageUid(String packageName, int flags) { 6134 try { 6135 return mActivityManagerService.mContext.getPackageManager() 6136 .getPackageUid(packageName, flags); 6137 } catch (NameNotFoundException nnfe) { 6138 return -1; 6139 } 6140 } 6141 } 6142 6143 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 6144 @Override checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)6145 public int checkComponentPermission(String permission, int pid, int uid, 6146 int owningUid, boolean exported) { 6147 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 6148 owningUid, exported); 6149 } 6150 6151 @Override getAMSLock()6152 public Object getAMSLock() { 6153 return ActivityManagerService.this; 6154 } 6155 } 6156 6157 /** 6158 * Allows if {@code pid} is {@link #MY_PID}, then denies if the {@code pid} has been denied 6159 * provided non-{@code null} {@code permission} before. Otherwise calls into 6160 * {@link ActivityManager#checkComponentPermission(String, int, int, int, boolean)}. 6161 */ 6162 @PackageManager.PermissionResult 6163 @PermissionMethod checkComponentPermission(@ermissionName String permission, int pid, int uid, int owningUid, boolean exported)6164 public static int checkComponentPermission(@PermissionName String permission, int pid, int uid, 6165 int owningUid, boolean exported) { 6166 return checkComponentPermission(permission, pid, uid, Context.DEVICE_ID_DEFAULT, 6167 owningUid, exported); 6168 } 6169 6170 /** 6171 * Allows if {@code pid} is {@link #MY_PID}, then denies if the {@code pid} has been denied 6172 * provided non-{@code null} {@code permission} before. Otherwise calls into 6173 * {@link ActivityManager#checkComponentPermission(String, int, int, int, boolean)}. 6174 */ 6175 @PackageManager.PermissionResult 6176 @PermissionMethod checkComponentPermission(@ermissionName String permission, int pid, int uid, int deviceId, int owningUid, boolean exported)6177 public static int checkComponentPermission(@PermissionName String permission, int pid, int uid, 6178 int deviceId, int owningUid, boolean exported) { 6179 if (pid == MY_PID) { 6180 return PackageManager.PERMISSION_GRANTED; 6181 } 6182 // If there is an explicit permission being checked, and this is coming from a process 6183 // that has been denied access to that permission, then just deny. Ultimately this may 6184 // not be quite right -- it means that even if the caller would have access for another 6185 // reason (such as being the owner of the component it is trying to access), it would still 6186 // fail. This also means the system and root uids would be able to deny themselves 6187 // access to permissions, which... well okay. ¯\_(ツ)_/¯ 6188 if (permission != null) { 6189 synchronized (sActiveProcessInfoSelfLocked) { 6190 ProcessInfo procInfo = sActiveProcessInfoSelfLocked.get(pid); 6191 if (procInfo != null && procInfo.deniedPermissions != null 6192 && procInfo.deniedPermissions.contains(permission)) { 6193 return PackageManager.PERMISSION_DENIED; 6194 } 6195 } 6196 } 6197 return ActivityManager.checkComponentPermission(permission, uid, deviceId, 6198 owningUid, exported); 6199 } 6200 enforceDebuggable(ProcessRecord proc)6201 private void enforceDebuggable(ProcessRecord proc) { 6202 if (!Build.IS_DEBUGGABLE && !proc.isDebuggable()) { 6203 throw new SecurityException("Process not debuggable: " + proc.info.packageName); 6204 } 6205 } 6206 enforceDebuggable(ApplicationInfo info)6207 private void enforceDebuggable(ApplicationInfo info) { 6208 if (!Build.IS_DEBUGGABLE && (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 6209 throw new SecurityException("Process not debuggable: " + info.packageName); 6210 } 6211 } 6212 6213 /** 6214 * As the only public entry point for permissions checking, this method 6215 * can enforce the semantic that requesting a check on a null global 6216 * permission is automatically denied. (Internally a null permission 6217 * string is used when calling {@link #checkComponentPermission} in cases 6218 * when only uid-based security is needed.) 6219 * 6220 * This can be called with or without the global lock held. 6221 */ 6222 @Override 6223 @PackageManager.PermissionResult 6224 @PermissionMethod checkPermission(@ermissionName String permission, int pid, int uid)6225 public int checkPermission(@PermissionName String permission, int pid, int uid) { 6226 return checkPermissionForDevice(permission, pid, uid, Context.DEVICE_ID_DEFAULT); 6227 } 6228 6229 /** 6230 * As the only public entry point for permissions checking, this method 6231 * can enforce the semantic that requesting a check on a null global 6232 * permission is automatically denied. (Internally a null permission 6233 * string is used when calling {@link #checkComponentPermission} in cases 6234 * when only uid-based security is needed.) 6235 * 6236 * This can be called with or without the global lock held. 6237 */ 6238 @Override 6239 @PackageManager.PermissionResult 6240 @PermissionMethod checkPermissionForDevice(@ermissionName String permission, int pid, int uid, int deviceId)6241 public int checkPermissionForDevice(@PermissionName String permission, int pid, int uid, 6242 int deviceId) { 6243 if (permission == null) { 6244 return PackageManager.PERMISSION_DENIED; 6245 } 6246 return checkComponentPermission(permission, pid, uid, deviceId, -1, true); 6247 } 6248 6249 /** 6250 * Binder IPC calls go through the public entry point. 6251 * This can be called with or without the global lock held. 6252 */ 6253 @PackageManager.PermissionResult 6254 @PermissionMethod checkCallingPermission(@ermissionName String permission)6255 int checkCallingPermission(@PermissionName String permission) { 6256 return checkPermission(permission, 6257 Binder.getCallingPid(), 6258 Binder.getCallingUid()); 6259 } 6260 6261 /** 6262 * This can be called with or without the global lock held. 6263 */ 6264 @PermissionMethod enforceCallingPermission(@ermissionName String permission, String func)6265 void enforceCallingPermission(@PermissionName String permission, String func) { 6266 if (checkCallingPermission(permission) 6267 == PackageManager.PERMISSION_GRANTED) { 6268 return; 6269 } 6270 6271 String msg = "Permission Denial: " + func + " from pid=" 6272 + Binder.getCallingPid() 6273 + ", uid=" + Binder.getCallingUid() 6274 + " requires " + permission; 6275 Slog.w(TAG, msg); 6276 throw new SecurityException(msg); 6277 } 6278 6279 /** 6280 * This can be called with or without the global lock held. 6281 */ 6282 @PermissionMethod(anyOf = true) enforceCallingHasAtLeastOnePermission(String func, String... permissions)6283 private void enforceCallingHasAtLeastOnePermission(String func, String... permissions) { 6284 for (String permission : permissions) { 6285 if (checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) { 6286 return; 6287 } 6288 } 6289 6290 String msg = "Permission Denial: " + func + " from pid=" 6291 + Binder.getCallingPid() 6292 + ", uid=" + Binder.getCallingUid() 6293 + " requires one of " + Arrays.toString(permissions); 6294 Slog.w(TAG, msg); 6295 throw new SecurityException(msg); 6296 } 6297 6298 /** 6299 * This can be called with or without the global lock held. 6300 */ 6301 @PermissionMethod enforcePermission(@ermissionName String permission, int pid, int uid, String func)6302 void enforcePermission(@PermissionName String permission, int pid, int uid, String func) { 6303 if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) { 6304 return; 6305 } 6306 6307 String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid 6308 + " requires " + permission; 6309 Slog.w(TAG, msg); 6310 throw new SecurityException(msg); 6311 } 6312 isAppStartModeDisabled(int uid, String packageName)6313 public boolean isAppStartModeDisabled(int uid, String packageName) { 6314 synchronized (mProcLock) { 6315 return getAppStartModeLOSP(uid, packageName, 0, -1, false, true, false) 6316 == ActivityManager.APP_START_MODE_DISABLED; 6317 } 6318 } 6319 isInRestrictedBucket(int userId, String packageName, long nowElapsed)6320 private boolean isInRestrictedBucket(int userId, String packageName, long nowElapsed) { 6321 return UsageStatsManager.STANDBY_BUCKET_RESTRICTED 6322 <= mUsageStatsService.getAppStandbyBucket(packageName, userId, nowElapsed); 6323 } 6324 6325 // Unified app-op and target sdk check 6326 @GuardedBy(anyOf = {"this", "mProcLock"}) appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6327 int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) { 6328 // Apps that target O+ are always subject to background check 6329 if (packageTargetSdk >= Build.VERSION_CODES.O) { 6330 if (DEBUG_BACKGROUND_CHECK) { 6331 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted"); 6332 } 6333 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 6334 } 6335 // It's a legacy app. If it's in the RESTRICTED bucket, always restrict on battery. 6336 if (mOnBattery // Short-circuit in common case. 6337 && mConstants.FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS 6338 && isInRestrictedBucket( 6339 UserHandle.getUserId(uid), packageName, SystemClock.elapsedRealtime())) { 6340 if (DEBUG_BACKGROUND_CHECK) { 6341 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " in RESTRICTED bucket"); 6342 } 6343 return ActivityManager.APP_START_MODE_DELAYED; 6344 } 6345 // Not in the RESTRICTED bucket so policy is based on AppOp check. 6346 int appop = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_RUN_IN_BACKGROUND, 6347 uid, packageName, null, ""); 6348 if (DEBUG_BACKGROUND_CHECK) { 6349 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop); 6350 } 6351 switch (appop) { 6352 case AppOpsManager.MODE_ALLOWED: 6353 // If force-background-check is enabled, restrict all apps that aren't allowlisted. 6354 if (mForceBackgroundCheck && 6355 !UserHandle.isCore(uid) && 6356 !isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ true)) { 6357 if (DEBUG_BACKGROUND_CHECK) { 6358 Slog.i(TAG, "Force background check: " + 6359 uid + "/" + packageName + " restricted"); 6360 } 6361 return ActivityManager.APP_START_MODE_DELAYED; 6362 } 6363 return ActivityManager.APP_START_MODE_NORMAL; 6364 case AppOpsManager.MODE_IGNORED: 6365 return ActivityManager.APP_START_MODE_DELAYED; 6366 default: 6367 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 6368 } 6369 } 6370 6371 // Service launch is available to apps with run-in-background exemptions but 6372 // some other background operations are not. If we're doing a check 6373 // of service-launch policy, allow those callers to proceed unrestricted. 6374 @GuardedBy(anyOf = {"this", "mProcLock"}) appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6375 int appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) { 6376 // Persistent app? 6377 if (mPackageManagerInt.isPackagePersistent(packageName)) { 6378 if (DEBUG_BACKGROUND_CHECK) { 6379 Slog.i(TAG, "App " + uid + "/" + packageName 6380 + " is persistent; not restricted in background"); 6381 } 6382 return ActivityManager.APP_START_MODE_NORMAL; 6383 } 6384 6385 // Non-persistent but background whitelisted? 6386 if (uidOnBackgroundAllowlistLOSP(uid)) { 6387 if (DEBUG_BACKGROUND_CHECK) { 6388 Slog.i(TAG, "App " + uid + "/" + packageName 6389 + " on background allowlist; not restricted in background"); 6390 } 6391 return ActivityManager.APP_START_MODE_NORMAL; 6392 } 6393 6394 // Is this app on the battery whitelist? 6395 if (isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ false)) { 6396 if (DEBUG_BACKGROUND_CHECK) { 6397 Slog.i(TAG, "App " + uid + "/" + packageName 6398 + " on idle allowlist; not restricted in background"); 6399 } 6400 return ActivityManager.APP_START_MODE_NORMAL; 6401 } 6402 6403 // None of the service-policy criteria apply, so we apply the common criteria 6404 return appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk); 6405 } 6406 6407 @GuardedBy(anyOf = {"this", "mProcLock"}) getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6408 int getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, 6409 int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) { 6410 if (mInternal.isPendingTopUid(uid)) { 6411 return ActivityManager.APP_START_MODE_NORMAL; 6412 } 6413 UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 6414 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg=" 6415 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle=" 6416 + (uidRec != null ? uidRec.isIdle() : false)); 6417 if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.isIdle()) { 6418 boolean ephemeral; 6419 if (uidRec == null) { 6420 ephemeral = getPackageManagerInternal().isPackageEphemeral( 6421 UserHandle.getUserId(uid), packageName); 6422 } else { 6423 ephemeral = uidRec.isEphemeral(); 6424 } 6425 6426 if (ephemeral) { 6427 // We are hard-core about ephemeral apps not running in the background. 6428 return ActivityManager.APP_START_MODE_DISABLED; 6429 } else { 6430 if (disabledOnly) { 6431 // The caller is only interested in whether app starts are completely 6432 // disabled for the given package (that is, it is an instant app). So 6433 // we don't need to go further, which is all just seeing if we should 6434 // apply a "delayed" mode for a regular app. 6435 return ActivityManager.APP_START_MODE_NORMAL; 6436 } 6437 final int startMode = (alwaysRestrict) 6438 ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk) 6439 : appServicesRestrictedInBackgroundLOSP(uid, packageName, 6440 packageTargetSdk); 6441 if (DEBUG_BACKGROUND_CHECK) { 6442 Slog.d(TAG, "checkAllowBackground: uid=" + uid 6443 + " pkg=" + packageName + " startMode=" + startMode 6444 + " onallowlist=" + isOnDeviceIdleAllowlistLOSP(uid, false) 6445 + " onallowlist(ei)=" + isOnDeviceIdleAllowlistLOSP(uid, true)); 6446 } 6447 if (startMode == ActivityManager.APP_START_MODE_DELAYED) { 6448 // This is an old app that has been forced into a "compatible as possible" 6449 // mode of background check. To increase compatibility, we will allow other 6450 // foreground apps to cause its services to start. 6451 if (callingPid >= 0) { 6452 ProcessRecord proc; 6453 synchronized (mPidsSelfLocked) { 6454 proc = mPidsSelfLocked.get(callingPid); 6455 } 6456 if (proc != null && !ActivityManager.isProcStateBackground( 6457 proc.mState.getCurProcState())) { 6458 // Whoever is instigating this is in the foreground, so we will allow it 6459 // to go through. 6460 return ActivityManager.APP_START_MODE_NORMAL; 6461 } 6462 } 6463 } 6464 return startMode; 6465 } 6466 } 6467 return ActivityManager.APP_START_MODE_NORMAL; 6468 } 6469 6470 /** 6471 * @return whether a UID is in the system, user or temp doze allowlist. 6472 */ 6473 @GuardedBy(anyOf = {"this", "mProcLock"}) isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo)6474 boolean isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo) { 6475 final int appId = UserHandle.getAppId(uid); 6476 6477 final int[] allowlist = allowExceptIdleToo 6478 ? mDeviceIdleExceptIdleAllowlist 6479 : mDeviceIdleAllowlist; 6480 6481 return Arrays.binarySearch(allowlist, appId) >= 0 6482 || Arrays.binarySearch(mDeviceIdleTempAllowlist, appId) >= 0 6483 || mPendingTempAllowlist.get(uid) != null; 6484 } 6485 6486 /** 6487 * Is the uid allowlisted to start FGS? 6488 * @param uid 6489 * @return a TempAllowListEntry if the uid is allowed. 6490 * null if the uid is not allowed. 6491 */ 6492 @Nullable 6493 @GuardedBy(anyOf = {"this", "mProcLock"}) isAllowlistedForFgsStartLOSP(int uid)6494 FgsTempAllowListItem isAllowlistedForFgsStartLOSP(int uid) { 6495 if (Arrays.binarySearch(mDeviceIdleExceptIdleAllowlist, UserHandle.getAppId(uid)) >= 0) { 6496 return FAKE_TEMP_ALLOW_LIST_ITEM; 6497 } 6498 final Pair<Long, FgsTempAllowListItem> entry = mFgsStartTempAllowList.get(uid); 6499 return entry == null ? null : entry.second; 6500 } 6501 6502 private static class GetBackgroundStartPrivilegesFunctor implements Consumer<ProcessRecord> { 6503 private BackgroundStartPrivileges mBackgroundStartPrivileges = 6504 BackgroundStartPrivileges.NONE; 6505 private int mUid; 6506 prepare(int uid)6507 void prepare(int uid) { 6508 mUid = uid; 6509 mBackgroundStartPrivileges = BackgroundStartPrivileges.NONE; 6510 } 6511 6512 @NonNull getResult()6513 BackgroundStartPrivileges getResult() { 6514 return mBackgroundStartPrivileges; 6515 } 6516 accept(ProcessRecord pr)6517 public void accept(ProcessRecord pr) { 6518 if (pr.uid == mUid) { 6519 mBackgroundStartPrivileges = 6520 mBackgroundStartPrivileges.merge(pr.getBackgroundStartPrivileges()); 6521 } 6522 } 6523 } 6524 6525 private final GetBackgroundStartPrivilegesFunctor mGetBackgroundStartPrivilegesFunctor = 6526 new GetBackgroundStartPrivilegesFunctor(); 6527 6528 /** 6529 * Returns the current complete {@link BackgroundStartPrivileges} of the UID. 6530 */ 6531 @NonNull getBackgroundStartPrivileges(int uid)6532 private BackgroundStartPrivileges getBackgroundStartPrivileges(int uid) { 6533 synchronized (mProcLock) { 6534 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 6535 if (uidRecord == null) { 6536 return BackgroundStartPrivileges.NONE; 6537 } 6538 mGetBackgroundStartPrivilegesFunctor.prepare(uid); 6539 uidRecord.forEachProcess(mGetBackgroundStartPrivilegesFunctor); 6540 return mGetBackgroundStartPrivilegesFunctor.getResult(); 6541 } 6542 } 6543 6544 /** 6545 * Returns true if the reasonCode is included in the base set of reasons an app may be 6546 * allowed to schedule a 6547 * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}. 6548 * This is a shortcut and <b>DOES NOT</b> include all reasons. 6549 * Use {@link #canScheduleUserInitiatedJobs(int, int, String)} to cover all cases. 6550 */ doesReasonCodeAllowSchedulingUserInitiatedJobs(int reasonCode, int uid)6551 static boolean doesReasonCodeAllowSchedulingUserInitiatedJobs(int reasonCode, int uid) { 6552 switch (reasonCode) { 6553 case REASON_PROC_STATE_PERSISTENT: 6554 case REASON_PROC_STATE_PERSISTENT_UI: 6555 case REASON_PROC_STATE_TOP: 6556 case REASON_PROC_STATE_BTOP: 6557 case REASON_UID_VISIBLE: 6558 case REASON_SYSTEM_UID: 6559 case REASON_START_ACTIVITY_FLAG: 6560 case REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD: 6561 case REASON_COMPANION_DEVICE_MANAGER: 6562 case REASON_BACKGROUND_ACTIVITY_PERMISSION: 6563 case REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION: 6564 return true; 6565 case REASON_SYSTEM_ALERT_WINDOW_PERMISSION: 6566 if (!Flags.fgsDisableSaw() 6567 || !CompatChanges.isChangeEnabled(FGS_SAW_RESTRICTIONS, uid)) { 6568 return true; 6569 } else { 6570 // With the new SAW restrictions starting Android V, only allow the app to 6571 // schedule a user-initiated job if it's currently showing an overlay window 6572 // in additional to holding the permission - this additional logic will be 6573 // checked in #canScheduleUserInitiatedJobs(int, int, String) below since this 6574 // method is simply a shortcut for checking based on the reason codes. 6575 } 6576 } 6577 return false; 6578 } 6579 6580 /** 6581 * Returns true if the ProcessRecord has some conditions that allow the app to schedule a 6582 * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}. 6583 * This is a shortcut and <b>DOES NOT</b> include all reasons. 6584 * Use {@link #canScheduleUserInitiatedJobs(int, int, String)} to cover all cases. 6585 */ 6586 @GuardedBy(anyOf = {"this", "mProcLock"}) isProcessInStateToScheduleUserInitiatedJobsLocked( @ullable ProcessRecord pr, long nowElapsed, int uid)6587 private boolean isProcessInStateToScheduleUserInitiatedJobsLocked( 6588 @Nullable ProcessRecord pr, long nowElapsed, int uid) { 6589 if (pr == null) { 6590 return false; 6591 } 6592 6593 final BackgroundStartPrivileges backgroundStartPrivileges = 6594 pr.getBackgroundStartPrivileges(); 6595 // Is the allow activity background start flag on? 6596 if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) { 6597 // REASON_START_ACTIVITY_FLAG; 6598 return true; 6599 } 6600 6601 final ProcessStateRecord state = pr.mState; 6602 final int procstate = state.getCurProcState(); 6603 if (procstate <= PROCESS_STATE_BOUND_TOP) { 6604 if (doesReasonCodeAllowSchedulingUserInitiatedJobs( 6605 getReasonCodeFromProcState(procstate), uid)) { 6606 return true; 6607 } 6608 } 6609 6610 final long lastInvisibleTime = state.getLastInvisibleTime(); 6611 if (lastInvisibleTime > 0 && lastInvisibleTime < Long.MAX_VALUE) { 6612 final long timeSinceVisibleMs = nowElapsed - lastInvisibleTime; 6613 if (timeSinceVisibleMs < mConstants.mVisibleToInvisibleUijScheduleGraceDurationMs) { 6614 // REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD 6615 return true; 6616 } 6617 } 6618 6619 final ProcessServiceRecord psr = pr.mServices; 6620 if (psr != null && psr.hasForegroundServices()) { 6621 for (int s = psr.numberOfRunningServices() - 1; s >= 0; --s) { 6622 final ServiceRecord sr = psr.getRunningServiceAt(s); 6623 if (sr.isForeground && sr.mAllowUiJobScheduling) { 6624 return true; 6625 } 6626 } 6627 } 6628 6629 return false; 6630 } 6631 6632 /** 6633 * Returns whether the app in question is in a state where we allow scheduling a 6634 * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}. 6635 */ 6636 // TODO(262260570): log allow reason to an atom canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)6637 boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName) { 6638 synchronized (this) { 6639 final ProcessRecord processRecord; 6640 synchronized (mPidsSelfLocked) { 6641 processRecord = mPidsSelfLocked.get(pid); 6642 } 6643 6644 final long nowElapsed = SystemClock.elapsedRealtime(); 6645 final BackgroundStartPrivileges backgroundStartPrivileges; 6646 if (processRecord != null) { 6647 if (isProcessInStateToScheduleUserInitiatedJobsLocked( 6648 processRecord, nowElapsed, uid)) { 6649 return true; 6650 } 6651 backgroundStartPrivileges = processRecord.getBackgroundStartPrivileges(); 6652 } else { 6653 backgroundStartPrivileges = getBackgroundStartPrivileges(uid); 6654 } 6655 // Is the allow activity background start flag on? 6656 if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) { 6657 // REASON_START_ACTIVITY_FLAG; 6658 return true; 6659 } 6660 6661 // We allow scheduling a user-initiated job when the app is in the TOP or a 6662 // Background Activity Launch approved state. These are cases that indicate the user 6663 // has interacted with the app and therefore it is reasonable to believe the app may 6664 // attempt to schedule a user-initiated job in response to the user interaction. 6665 // As of Android UDC, the conditions required to grant a while-in-use permission 6666 // covers the majority of those cases, and so we piggyback on that logic as the base. 6667 // Missing cases are added after. 6668 if (mServices.canAllowWhileInUsePermissionInFgsLocked( 6669 pid, uid, pkgName, processRecord, backgroundStartPrivileges)) { 6670 return true; 6671 } 6672 6673 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 6674 final boolean hasSawPermission = mAtmInternal.hasSystemAlertWindowPermission(uid, pid, 6675 pkgName); 6676 final boolean strictSawCheckEnabled = Flags.fgsDisableSaw() 6677 && CompatChanges.isChangeEnabled(FGS_SAW_RESTRICTIONS, uid); 6678 if (uidRecord != null) { 6679 for (int i = uidRecord.getNumOfProcs() - 1; i >= 0; --i) { 6680 ProcessRecord pr = uidRecord.getProcessRecordByIndex(i); 6681 if (isProcessInStateToScheduleUserInitiatedJobsLocked(pr, nowElapsed, uid)) { 6682 return true; 6683 } else if (hasSawPermission && strictSawCheckEnabled) { 6684 // isProcessInStateToScheduleUserInitiatedJobsLocked() doesn't do a strict 6685 // check for the SAW permission which is enabled from V onwards, so perform 6686 // that here (pre-V versions will be checked in the conditional below) 6687 // Starting Android V, only allow the app to schedule a user-initiated job 6688 // if it's granted the permission and currently showing an overlay window 6689 if (pr != null && pr.mState.hasOverlayUi()) { 6690 return true; 6691 } 6692 } 6693 } 6694 } 6695 6696 if (hasSawPermission && !strictSawCheckEnabled) { 6697 // REASON_SYSTEM_ALERT_WINDOW_PERMISSION (pre-V) 6698 return true; 6699 } 6700 6701 final int userId = UserHandle.getUserId(uid); 6702 final boolean isCompanionApp = mInternal.isAssociatedCompanionApp(userId, uid); 6703 if (isCompanionApp) { 6704 if (checkPermission(REQUEST_COMPANION_RUN_IN_BACKGROUND, pid, uid) 6705 == PERMISSION_GRANTED) { 6706 // REASON_COMPANION_DEVICE_MANAGER; 6707 return true; 6708 } 6709 } 6710 } 6711 6712 return false; 6713 } 6714 6715 /** 6716 * @return allowlist tag for a uid from mPendingTempAllowlist, null if not currently on 6717 * the allowlist 6718 */ 6719 @GuardedBy(anyOf = {"this", "mProcLock"}) getPendingTempAllowlistTagForUidLOSP(int uid)6720 String getPendingTempAllowlistTagForUidLOSP(int uid) { 6721 final PendingTempAllowlist ptw = mPendingTempAllowlist.get(uid); 6722 return ptw != null ? ptw.tag : null; 6723 } 6724 6725 @VisibleForTesting grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId)6726 public void grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId) { 6727 getPackageManagerInternal() 6728 .grantImplicitAccess(userId, intent, recipientAppId, visibleUid, true /*direct*/); 6729 } 6730 6731 /** 6732 * @param uri This uri must NOT contain an embedded userId. 6733 * @param userId The userId in which the uri is to be resolved. 6734 */ 6735 @Override checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6736 public int checkUriPermission(Uri uri, int pid, int uid, 6737 final int modeFlags, int userId, IBinder callerToken) { 6738 return checkUriPermission(uri, pid, uid, modeFlags, userId, 6739 /* isFullAccessForContentUri */ false, "checkUriPermission"); 6740 } 6741 6742 /** 6743 * @param uri This uri must NOT contain an embedded userId. 6744 * @param userId The userId in which the uri is to be resolved. 6745 */ 6746 @Override checkContentUriPermissionFull(Uri uri, int pid, int uid, final int modeFlags, int userId)6747 public int checkContentUriPermissionFull(Uri uri, int pid, int uid, 6748 final int modeFlags, int userId) { 6749 return checkUriPermission(uri, pid, uid, modeFlags, userId, 6750 /* isFullAccessForContentUri */ true, "checkContentUriPermissionFull"); 6751 } 6752 checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, boolean isFullAccessForContentUri, String methodName)6753 private int checkUriPermission(Uri uri, int pid, int uid, 6754 final int modeFlags, int userId, boolean isFullAccessForContentUri, String methodName) { 6755 enforceNotIsolatedCaller(methodName); 6756 6757 // Our own process gets to do everything. 6758 if (pid == MY_PID) { 6759 return PackageManager.PERMISSION_GRANTED; 6760 } 6761 if (uid != ROOT_UID) { // bypass the root 6762 if (mPackageManagerInt.filterAppAccess(uid, Binder.getCallingUid())) { 6763 return PackageManager.PERMISSION_DENIED; 6764 } 6765 } 6766 boolean granted = mUgmInternal.checkUriPermission(new GrantUri(userId, uri, modeFlags), uid, 6767 modeFlags, isFullAccessForContentUri); 6768 6769 return granted ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED; 6770 } 6771 6772 @Override checkUriPermissions(@onNull List<Uri> uris, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6773 public int[] checkUriPermissions(@NonNull List<Uri> uris, int pid, int uid, 6774 final int modeFlags, int userId, IBinder callerToken) { 6775 final int size = uris.size(); 6776 int[] res = new int[size]; 6777 // Default value DENIED. 6778 Arrays.fill(res, PackageManager.PERMISSION_DENIED); 6779 6780 for (int i = 0; i < size; i++) { 6781 final Uri uri = uris.get(i); 6782 final int userIdFromUri = ContentProvider.getUserIdFromUri(uri, userId); 6783 res[i] = checkUriPermission(ContentProvider.getUriWithoutUserId(uri), pid, uid, 6784 modeFlags, userIdFromUri, callerToken); 6785 } 6786 return res; 6787 } 6788 6789 /** 6790 * @param uri This uri must NOT contain an embedded userId. 6791 * @param userId The userId in which the uri is to be resolved. 6792 */ 6793 @Override grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6794 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 6795 final int modeFlags, int userId) { 6796 enforceNotIsolatedCaller("grantUriPermission"); 6797 GrantUri grantUri = new GrantUri(userId, uri, modeFlags); 6798 synchronized (this) { 6799 final ProcessRecord r = getRecordForAppLOSP(caller); 6800 if (r == null) { 6801 throw new SecurityException("Unable to find app for caller " 6802 + caller 6803 + " when granting permission to uri " + grantUri); 6804 } 6805 if (targetPkg == null) { 6806 throw new IllegalArgumentException("null target"); 6807 } 6808 final int callingUserId = UserHandle.getUserId(r.uid); 6809 if (mPackageManagerInt.filterAppAccess(targetPkg, r.uid, callingUserId)) { 6810 return; 6811 } 6812 6813 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 6814 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 6815 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 6816 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 6817 6818 final Intent intent = new Intent(); 6819 intent.setData(ContentProvider.maybeAddUserId(uri, userId)); 6820 intent.setFlags(modeFlags); 6821 6822 final NeededUriGrants needed = mUgmInternal.checkGrantUriPermissionFromIntent(intent, 6823 r.uid, targetPkg, callingUserId); 6824 mUgmInternal.grantUriPermissionUncheckedFromIntent(needed, null); 6825 } 6826 } 6827 6828 /** 6829 * @param uri This uri must NOT contain an embedded userId. 6830 * @param userId The userId in which the uri is to be resolved. 6831 */ 6832 @Override revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6833 public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, 6834 final int modeFlags, int userId) { 6835 enforceNotIsolatedCaller("revokeUriPermission"); 6836 synchronized (this) { 6837 final ProcessRecord r = getRecordForAppLOSP(caller); 6838 if (r == null) { 6839 throw new SecurityException("Unable to find app for caller " 6840 + caller 6841 + " when revoking permission to uri " + uri); 6842 } 6843 if (uri == null) { 6844 Slog.w(TAG, "revokeUriPermission: null uri"); 6845 return; 6846 } 6847 6848 if (!Intent.isAccessUriMode(modeFlags)) { 6849 return; 6850 } 6851 6852 final String authority = uri.getAuthority(); 6853 final ProviderInfo pi = mCpHelper.getProviderInfoLocked(authority, userId, 6854 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 6855 if (pi == null) { 6856 Slog.w(TAG, "No content provider found for permission revoke: " 6857 + uri.toSafeString()); 6858 return; 6859 } 6860 6861 mUgmInternal.revokeUriPermission(targetPackage, r.uid, 6862 new GrantUri(userId, uri, modeFlags), modeFlags); 6863 } 6864 } 6865 6866 @Override showWaitingForDebugger(IApplicationThread who, boolean waiting)6867 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 6868 synchronized (mProcLock) { 6869 final ProcessRecord app = who != null ? getRecordForAppLOSP(who) : null; 6870 if (app == null) return; 6871 6872 Message msg = Message.obtain(); 6873 msg.what = WAIT_FOR_DEBUGGER_UI_MSG; 6874 msg.obj = app; 6875 msg.arg1 = waiting ? 1 : 0; 6876 mUiHandler.sendMessage(msg); 6877 } 6878 } 6879 6880 @Override getMemoryInfo(ActivityManager.MemoryInfo outInfo)6881 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 6882 mProcessList.getMemoryInfo(outInfo); 6883 } 6884 6885 // ========================================================= 6886 // TASK MANAGEMENT 6887 // ========================================================= 6888 6889 @Override getTasks(int maxNum)6890 public List<RunningTaskInfo> getTasks(int maxNum) { 6891 return mActivityTaskManager.getTasks(maxNum); 6892 } 6893 6894 @Override cancelTaskWindowTransition(int taskId)6895 public void cancelTaskWindowTransition(int taskId) { 6896 mActivityTaskManager.cancelTaskWindowTransition(taskId); 6897 } 6898 6899 @Override setTaskResizeable(int taskId, int resizeableMode)6900 public void setTaskResizeable(int taskId, int resizeableMode) { 6901 mActivityTaskManager.setTaskResizeable(taskId, resizeableMode); 6902 } 6903 6904 @Override resizeTask(int taskId, Rect bounds, int resizeMode)6905 public void resizeTask(int taskId, Rect bounds, int resizeMode) { 6906 mActivityTaskManager.resizeTask(taskId, bounds, resizeMode); 6907 } 6908 6909 @Override getTaskBounds(int taskId)6910 public Rect getTaskBounds(int taskId) { 6911 return mActivityTaskManager.getTaskBounds(taskId); 6912 } 6913 6914 @Override removeTask(int taskId)6915 public boolean removeTask(int taskId) { 6916 return mActivityTaskManager.removeTask(taskId); 6917 } 6918 6919 @Override moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6920 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, 6921 int flags, Bundle bOptions) { 6922 mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions); 6923 } 6924 6925 /** 6926 * Attempts to move a task backwards in z-order (the order of activities within the task is 6927 * unchanged). 6928 * 6929 * There are several possible results of this call: 6930 * - if the task is locked, then we will show the lock toast 6931 * - if there is a task behind the provided task, then that task is made visible and resumed as 6932 * this task is moved to the back 6933 * - otherwise, if there are no other tasks in the stack: 6934 * - if this task is in the pinned stack, then we remove the stack completely, which will 6935 * have the effect of moving the task to the top or bottom of the fullscreen stack 6936 * (depending on whether it is visible) 6937 * - otherwise, we simply return home and hide this task 6938 * 6939 * @param token A reference to the activity we wish to move 6940 * @param nonRoot If false then this only works if the activity is the root 6941 * of a task; if true it will work for any activity in a task. 6942 * @return Returns true if the move completed, false if not. 6943 */ 6944 @Override moveActivityTaskToBack(IBinder token, boolean nonRoot)6945 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 6946 return ActivityClient.getInstance().moveActivityTaskToBack(token, nonRoot); 6947 } 6948 6949 @Override moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)6950 public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) { 6951 mActivityTaskManager.moveTaskToRootTask(taskId, rootTaskId, toTop); 6952 } 6953 6954 @Override getRecentTasks(int maxNum, int flags, int userId)6955 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, 6956 int userId) { 6957 return mActivityTaskManager.getRecentTasks(maxNum, flags, userId); 6958 } 6959 6960 @Override getAllRootTaskInfos()6961 public List<RootTaskInfo> getAllRootTaskInfos() { 6962 return mActivityTaskManager.getAllRootTaskInfos(); 6963 } 6964 6965 @Override getTaskForActivity(IBinder token, boolean onlyRoot)6966 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 6967 return ActivityClient.getInstance().getTaskForActivity(token, onlyRoot); 6968 } 6969 6970 @Override updateLockTaskPackages(int userId, String[] packages)6971 public void updateLockTaskPackages(int userId, String[] packages) { 6972 mActivityTaskManager.updateLockTaskPackages(userId, packages); 6973 } 6974 6975 @Override isInLockTaskMode()6976 public boolean isInLockTaskMode() { 6977 return mActivityTaskManager.isInLockTaskMode(); 6978 } 6979 6980 @Override getLockTaskModeState()6981 public int getLockTaskModeState() { 6982 return mActivityTaskManager.getLockTaskModeState(); 6983 } 6984 6985 @Override startSystemLockTaskMode(int taskId)6986 public void startSystemLockTaskMode(int taskId) throws RemoteException { 6987 mActivityTaskManager.startSystemLockTaskMode(taskId); 6988 } 6989 6990 /** 6991 * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The 6992 * PackageManager could be unavailable at construction time and therefore needs to be accessed 6993 * on demand. 6994 */ 6995 @VisibleForTesting getPackageManager()6996 public IPackageManager getPackageManager() { 6997 return AppGlobals.getPackageManager(); 6998 } 6999 7000 @VisibleForTesting getPackageManagerInternal()7001 public PackageManagerInternal getPackageManagerInternal() { 7002 // Intentionally hold no locks: in case of race conditions, the mPackageManagerInt will 7003 // be set to the same value anyway. 7004 if (mPackageManagerInt == null) { 7005 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class); 7006 } 7007 return mPackageManagerInt; 7008 } 7009 getPermissionManagerInternal()7010 private PermissionManagerServiceInternal getPermissionManagerInternal() { 7011 // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will 7012 // be set to the same value anyway. 7013 if (mPermissionManagerInt == null) { 7014 mPermissionManagerInt = 7015 LocalServices.getService(PermissionManagerServiceInternal.class); 7016 } 7017 return mPermissionManagerInt; 7018 } 7019 getAccessCheckDelegateHelper()7020 private AccessCheckDelegateHelper getAccessCheckDelegateHelper() { 7021 // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will 7022 // be set to the same value anyway. 7023 if (mAccessCheckDelegateHelper == null) { 7024 mAccessCheckDelegateHelper = new AccessCheckDelegateHelper(mProcLock, 7025 mActiveInstrumentation, mAppOpsService, getPermissionManagerInternal()); 7026 } 7027 return mAccessCheckDelegateHelper; 7028 } 7029 7030 /** Returns whether the given package was ever launched since install */ wasPackageEverLaunched(String packageName, @UserIdInt int userId)7031 boolean wasPackageEverLaunched(String packageName, @UserIdInt int userId) { 7032 boolean wasLaunched = false; 7033 try { 7034 wasLaunched = getPackageManagerInternal().wasPackageEverLaunched(packageName, userId); 7035 } catch (Exception e) { 7036 // If the package state record doesn't exist yet, assume it was never launched 7037 } 7038 return wasLaunched; 7039 } 7040 getTestUtilityServiceLocked()7041 private TestUtilityService getTestUtilityServiceLocked() { 7042 if (mTestUtilityService == null) { 7043 mTestUtilityService = 7044 LocalServices.getService(TestUtilityService.class); 7045 } 7046 return mTestUtilityService; 7047 } 7048 7049 @Override appNotResponding(final String reason)7050 public void appNotResponding(final String reason) { 7051 appNotResponding(reason, /*isContinuousAnr*/ false); 7052 } 7053 appNotResponding(final String reason, boolean isContinuousAnr)7054 public void appNotResponding(final String reason, boolean isContinuousAnr) { 7055 TimeoutRecord timeoutRecord = TimeoutRecord.forApp("App requested: " + reason); 7056 final int callingPid = Binder.getCallingPid(); 7057 7058 timeoutRecord.mLatencyTracker.waitingOnPidLockStarted(); 7059 synchronized (mPidsSelfLocked) { 7060 timeoutRecord.mLatencyTracker.waitingOnPidLockEnded(); 7061 final ProcessRecord app = mPidsSelfLocked.get(callingPid); 7062 if (app == null) { 7063 throw new SecurityException("Unknown process: " + callingPid); 7064 } 7065 7066 mAnrHelper.appNotResponding(app, null, app.info, null, null, false, 7067 timeoutRecord, isContinuousAnr); 7068 } 7069 } 7070 appNotResponding(@onNull ProcessRecord anrProcess, @NonNull TimeoutRecord timeoutRecord)7071 void appNotResponding(@NonNull ProcessRecord anrProcess, @NonNull TimeoutRecord timeoutRecord) { 7072 mAnrHelper.appNotResponding(anrProcess, timeoutRecord); 7073 } 7074 appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)7075 private void appNotResponding(@NonNull String processName, int uid, 7076 @NonNull TimeoutRecord timeoutRecord) { 7077 Objects.requireNonNull(processName); 7078 Objects.requireNonNull(timeoutRecord); 7079 7080 synchronized (this) { 7081 final ProcessRecord app = getProcessRecordLocked(processName, uid); 7082 if (app == null) { 7083 Slog.e(TAG, "Unknown process: " + processName); 7084 return; 7085 } 7086 mAnrHelper.appNotResponding(app, timeoutRecord); 7087 } 7088 } 7089 startPersistentApps(int matchFlags)7090 void startPersistentApps(int matchFlags) { 7091 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return; 7092 7093 synchronized (this) { 7094 try { 7095 final List<ApplicationInfo> apps = AppGlobals.getPackageManager() 7096 .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList(); 7097 for (ApplicationInfo app : apps) { 7098 if (!"android".equals(app.packageName)) { 7099 final ProcessRecord proc = addAppLocked( 7100 app, null, false, null /* ABI override */, 7101 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 7102 if (proc != null) { 7103 proc.mProfile.addHostingComponentType( 7104 HOSTING_COMPONENT_TYPE_PERSISTENT); 7105 } 7106 } 7107 } 7108 } catch (RemoteException ex) { 7109 } 7110 } 7111 } 7112 7113 // ========================================================= 7114 // CONTENT PROVIDERS 7115 // ========================================================= 7116 getContentProviderHelper()7117 public ContentProviderHelper getContentProviderHelper() { 7118 return mCpHelper; 7119 } 7120 7121 @Override getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)7122 public final ContentProviderHolder getContentProvider( 7123 IApplicationThread caller, String callingPackage, String name, int userId, 7124 boolean stable) { 7125 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProvider: ", name); 7126 try { 7127 return mCpHelper.getContentProvider(caller, callingPackage, name, userId, stable); 7128 } finally { 7129 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7130 } 7131 } 7132 7133 @Override getContentProviderExternal( String name, int userId, IBinder token, String tag)7134 public ContentProviderHolder getContentProviderExternal( 7135 String name, int userId, IBinder token, String tag) { 7136 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProviderExternal: ", name); 7137 try { 7138 return mCpHelper.getContentProviderExternal(name, userId, token, tag); 7139 } finally { 7140 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7141 } 7142 } 7143 7144 /** 7145 * Drop a content provider from a ProcessRecord's bookkeeping 7146 */ 7147 @Override removeContentProvider(IBinder connection, boolean stable)7148 public void removeContentProvider(IBinder connection, boolean stable) { 7149 mCpHelper.removeContentProvider(connection, stable); 7150 } 7151 7152 /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */ 7153 @Deprecated 7154 @Override removeContentProviderExternal(String name, IBinder token)7155 public void removeContentProviderExternal(String name, IBinder token) { 7156 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternal: ", name); 7157 try { 7158 removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId()); 7159 } finally { 7160 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7161 } 7162 } 7163 7164 @Override removeContentProviderExternalAsUser(String name, IBinder token, int userId)7165 public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) { 7166 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternalAsUser: ", name); 7167 try { 7168 mCpHelper.removeContentProviderExternalAsUser(name, token, userId); 7169 } finally { 7170 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7171 } 7172 } 7173 7174 @Override publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)7175 public final void publishContentProviders(IApplicationThread caller, 7176 List<ContentProviderHolder> providers) { 7177 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 7178 final int maxLength = 256; 7179 final StringBuilder sb = new StringBuilder(maxLength); 7180 sb.append("publishContentProviders: "); 7181 if (providers != null) { 7182 boolean first = true; 7183 for (int i = 0, size = providers.size(); i < size; i++) { 7184 final ContentProviderHolder holder = providers.get(i); 7185 if (holder != null && holder.info != null && holder.info.authority != null) { 7186 final int len = holder.info.authority.length(); 7187 if (sb.length() + len > maxLength) { 7188 sb.append("[[TRUNCATED]]"); 7189 break; 7190 } 7191 if (!first) { 7192 sb.append(';'); 7193 } else { 7194 first = false; 7195 } 7196 sb.append(holder.info.authority); 7197 } 7198 } 7199 } 7200 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString()); 7201 } 7202 try { 7203 mCpHelper.publishContentProviders(caller, providers); 7204 } finally { 7205 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7206 } 7207 } 7208 7209 @Override refContentProvider(IBinder connection, int stable, int unstable)7210 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 7211 return mCpHelper.refContentProvider(connection, stable, unstable); 7212 } 7213 7214 @Override unstableProviderDied(IBinder connection)7215 public void unstableProviderDied(IBinder connection) { 7216 mCpHelper.unstableProviderDied(connection); 7217 } 7218 7219 @Override appNotRespondingViaProvider(IBinder connection)7220 public void appNotRespondingViaProvider(IBinder connection) { 7221 mCpHelper.appNotRespondingViaProvider(connection); 7222 } 7223 7224 /** 7225 * Filters calls to getType based on permission. If the caller has required permission, 7226 * then it returns the contentProvider#getType. 7227 * Else, it returns the contentProvider#getTypeAnonymous, which does not 7228 * reveal any internal information which should be protected by any permission. 7229 */ 7230 @Override getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback)7231 public void getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback) { 7232 mCpHelper.getMimeTypeFilterAsync(uri, userId, resultCallback); 7233 } 7234 7235 // ========================================================= 7236 // GLOBAL MANAGEMENT 7237 // ========================================================= 7238 7239 @GuardedBy(anyOf = {"this", "mProcLock"}) uidOnBackgroundAllowlistLOSP(final int uid)7240 private boolean uidOnBackgroundAllowlistLOSP(final int uid) { 7241 final int appId = UserHandle.getAppId(uid); 7242 final int[] allowlist = mBackgroundAppIdAllowlist; 7243 for (int i = 0, len = allowlist.length; i < len; i++) { 7244 if (appId == allowlist[i]) { 7245 return true; 7246 } 7247 } 7248 return false; 7249 } 7250 7251 @Override isBackgroundRestricted(String packageName)7252 public boolean isBackgroundRestricted(String packageName) { 7253 final int callingUid = Binder.getCallingUid(); 7254 final IPackageManager pm = AppGlobals.getPackageManager(); 7255 try { 7256 final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 7257 UserHandle.getUserId(callingUid)); 7258 if (packageUid != callingUid) { 7259 throw new IllegalArgumentException("Uid " + callingUid 7260 + " cannot query restriction state for package " + packageName); 7261 } 7262 } catch (RemoteException exc) { 7263 // Ignore. 7264 } 7265 return isBackgroundRestrictedNoCheck(callingUid, packageName); 7266 } 7267 7268 @VisibleForTesting isBackgroundRestrictedNoCheck(final int uid, final String packageName)7269 public boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) { 7270 final int mode = getAppOpsManager().checkOpNoThrow(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, 7271 uid, packageName); 7272 return mode != AppOpsManager.MODE_ALLOWED; 7273 } 7274 7275 @Override backgroundAllowlistUid(final int uid)7276 public void backgroundAllowlistUid(final int uid) { 7277 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 7278 throw new SecurityException("Only the OS may call backgroundAllowlistUid()"); 7279 } 7280 7281 if (DEBUG_BACKGROUND_CHECK) { 7282 Slog.i(TAG, "Adding uid " + uid + " to bg uid allowlist"); 7283 } 7284 synchronized (this) { 7285 synchronized (mProcLock) { 7286 final int num = mBackgroundAppIdAllowlist.length; 7287 int[] newList = new int[num + 1]; 7288 System.arraycopy(mBackgroundAppIdAllowlist, 0, newList, 0, num); 7289 newList[num] = UserHandle.getAppId(uid); 7290 mBackgroundAppIdAllowlist = newList; 7291 } 7292 } 7293 } 7294 7295 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)7296 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 7297 String abiOverride, int zygotePolicyFlags) { 7298 return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */, 7299 abiOverride, zygotePolicyFlags); 7300 } 7301 7302 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags)7303 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 7304 boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags) { 7305 return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks, 7306 false /* disableTestApiChecks */, abiOverride, zygotePolicyFlags); 7307 } 7308 7309 // TODO: Move to ProcessList? 7310 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)7311 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 7312 boolean disableHiddenApiChecks, boolean disableTestApiChecks, 7313 String abiOverride, int zygotePolicyFlags) { 7314 return addAppLocked( 7315 info, 7316 customProcess, 7317 isolated, 7318 /* isSdkSandbox= */ false, 7319 /* sdkSandboxUid= */ 0, 7320 /* sdkSandboxClientAppPackage= */ null, 7321 disableHiddenApiChecks, 7322 disableTestApiChecks, 7323 abiOverride, 7324 zygotePolicyFlags); 7325 } 7326 addAppLocked( ApplicationInfo info, String customProcess, boolean isolated, boolean isSdkSandbox, int sdkSandboxUid, @Nullable String sdkSandboxClientAppPackage, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)7327 final ProcessRecord addAppLocked( 7328 ApplicationInfo info, 7329 String customProcess, 7330 boolean isolated, 7331 boolean isSdkSandbox, 7332 int sdkSandboxUid, 7333 @Nullable String sdkSandboxClientAppPackage, 7334 boolean disableHiddenApiChecks, 7335 boolean disableTestApiChecks, 7336 String abiOverride, 7337 int zygotePolicyFlags) { 7338 ProcessRecord app; 7339 if (!isolated) { 7340 app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName, 7341 info.uid); 7342 } else { 7343 app = null; 7344 } 7345 7346 if (app == null) { 7347 app = mProcessList.newProcessRecordLocked( 7348 info, 7349 customProcess, 7350 isolated, 7351 /* isolatedUid= */0, 7352 isSdkSandbox, 7353 sdkSandboxUid, 7354 sdkSandboxClientAppPackage, 7355 new HostingRecord(HostingRecord.HOSTING_TYPE_ADDED_APPLICATION, 7356 customProcess != null ? customProcess : info.processName)); 7357 updateLruProcessLocked(app, false, null); 7358 updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN); 7359 } 7360 7361 // Report usage as process is persistent and being started. 7362 mUsageStatsService.reportEvent(info.packageName, UserHandle.getUserId(app.uid), 7363 Event.APP_COMPONENT_USED); 7364 7365 // This package really, really can not be stopped. 7366 // TODO: how set package stopped state should work for sdk sandboxes? 7367 if (!isSdkSandbox) { 7368 try { 7369 mPackageManagerInt.setPackageStoppedState( 7370 info.packageName, false, UserHandle.getUserId(app.uid)); 7371 } catch (IllegalArgumentException e) { 7372 Slog.w(TAG, "Failed trying to unstop package " 7373 + info.packageName + ": " + e); 7374 } 7375 } 7376 7377 if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 7378 app.setPersistent(true); 7379 app.mState.setMaxAdj(ProcessList.PERSISTENT_PROC_ADJ); 7380 } 7381 if (app.getThread() == null && mPersistentStartingProcesses.indexOf(app) < 0) { 7382 mPersistentStartingProcesses.add(app); 7383 mProcessList.startProcessLocked(app, new HostingRecord( 7384 HostingRecord.HOSTING_TYPE_ADDED_APPLICATION, 7385 customProcess != null ? customProcess : app.processName), 7386 zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks, 7387 abiOverride); 7388 } 7389 7390 return app; 7391 } 7392 unhandledBack()7393 public void unhandledBack() { 7394 mActivityTaskManager.unhandledBack(); 7395 } 7396 7397 // TODO: Replace this method with one that returns a bound IContentProvider. openContentUri(String uriString)7398 public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException { 7399 enforceNotIsolatedCaller("openContentUri"); 7400 final int userId = UserHandle.getCallingUserId(); 7401 final Uri uri = Uri.parse(uriString); 7402 String name = uri.getAuthority(); 7403 ContentProviderHolder cph = mCpHelper.getContentProviderExternalUnchecked(name, null, 7404 Binder.getCallingUid(), "*opencontent*", userId); 7405 ParcelFileDescriptor pfd = null; 7406 if (cph != null) { 7407 try { 7408 // This method is exposed to the VNDK and to avoid changing its 7409 // signature we just use the first package in the UID. For shared 7410 // UIDs we may blame the wrong app but that is Okay as they are 7411 // in the same security/privacy sandbox. 7412 final int uid = Binder.getCallingUid(); 7413 // Here we handle some of the special UIDs (mediaserver, systemserver, etc) 7414 final String packageName = AppOpsManager.resolvePackageName(uid, 7415 /*packageName*/ null); 7416 final AndroidPackage androidPackage; 7417 if (packageName != null) { 7418 androidPackage = mPackageManagerInt.getPackage(packageName); 7419 } else { 7420 androidPackage = mPackageManagerInt.getPackage(uid); 7421 } 7422 if (androidPackage == null) { 7423 Log.e(TAG, "Cannot find package for uid: " + uid); 7424 return null; 7425 } 7426 7427 final ApplicationInfo appInfo = mPackageManagerInt.getApplicationInfo( 7428 androidPackage.getPackageName(), /*flags*/0, Process.SYSTEM_UID, 7429 UserHandle.USER_SYSTEM); 7430 if (!appInfo.isVendor() && !appInfo.isSystemApp() && !appInfo.isSystemExt() 7431 && !appInfo.isProduct()) { 7432 Log.e(TAG, "openContentUri may only be used by vendor/system/product."); 7433 return null; 7434 } 7435 7436 final AttributionSource attributionSource = new AttributionSource( 7437 Binder.getCallingUid(), androidPackage.getPackageName(), null); 7438 pfd = cph.provider.openFile(attributionSource, uri, "r", null); 7439 } catch (FileNotFoundException e) { 7440 // do nothing; pfd will be returned null 7441 } finally { 7442 // Ensure we're done with the provider. 7443 mCpHelper.removeContentProviderExternalUnchecked(name, null, userId); 7444 } 7445 } else { 7446 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 7447 } 7448 return pfd; 7449 } 7450 reportGlobalUsageEvent(int event)7451 void reportGlobalUsageEvent(int event) { 7452 final int currentUserId = mUserController.getCurrentUserId(); 7453 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, currentUserId, event); 7454 int[] profiles = mUserController.getCurrentProfileIds(); 7455 if (profiles != null) { 7456 for (int i = profiles.length - 1; i >= 0; i--) { 7457 if (profiles[i] == currentUserId) { 7458 continue; 7459 } 7460 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, profiles[i], event); 7461 } 7462 } 7463 } 7464 reportCurWakefulnessUsageEvent()7465 void reportCurWakefulnessUsageEvent() { 7466 reportGlobalUsageEvent(mWakefulness.get() == PowerManagerInternal.WAKEFULNESS_AWAKE 7467 ? UsageEvents.Event.SCREEN_INTERACTIVE 7468 : UsageEvents.Event.SCREEN_NON_INTERACTIVE); 7469 } 7470 onWakefulnessChanged(int wakefulness)7471 void onWakefulnessChanged(int wakefulness) { 7472 synchronized (this) { 7473 boolean wasAwake = mWakefulness.getAndSet(wakefulness) 7474 == PowerManagerInternal.WAKEFULNESS_AWAKE; 7475 boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE; 7476 7477 if (wasAwake != isAwake) { 7478 // Also update state in a special way for running foreground services UI. 7479 mServices.updateScreenStateLocked(isAwake); 7480 reportCurWakefulnessUsageEvent(); 7481 mActivityTaskManager.onScreenAwakeChanged(isAwake); 7482 mOomAdjuster.onWakefulnessChanged(wakefulness); 7483 7484 updateOomAdjLocked(OOM_ADJ_REASON_UI_VISIBILITY); 7485 } 7486 } 7487 } 7488 7489 @Override notifyCleartextNetwork(int uid, byte[] firstPacket)7490 public void notifyCleartextNetwork(int uid, byte[] firstPacket) { 7491 mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget(); 7492 } 7493 7494 @Override shutdown(int timeout)7495 public boolean shutdown(int timeout) { 7496 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 7497 != PackageManager.PERMISSION_GRANTED) { 7498 throw new SecurityException("Requires permission " 7499 + android.Manifest.permission.SHUTDOWN); 7500 } 7501 7502 final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout); 7503 7504 mAppOpsService.shutdown(); 7505 if (mUsageStatsService != null) { 7506 mUsageStatsService.prepareShutdown(); 7507 } 7508 mBatteryStatsService.shutdown(); 7509 mProcessStats.shutdown(); 7510 7511 return timedout; 7512 } 7513 7514 @Override notifyLockedProfile(@serIdInt int userId)7515 public void notifyLockedProfile(@UserIdInt int userId) { 7516 mAtmInternal.notifyLockedProfile(userId); 7517 } 7518 7519 @Override startConfirmDeviceCredentialIntent(Intent intent, Bundle options)7520 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) { 7521 mAtmInternal.startConfirmDeviceCredentialIntent(intent, options); 7522 } 7523 7524 @Override stopAppSwitches()7525 public void stopAppSwitches() { 7526 mActivityTaskManager.stopAppSwitches(); 7527 } 7528 7529 @Override resumeAppSwitches()7530 public void resumeAppSwitches() { 7531 mActivityTaskManager.resumeAppSwitches(); 7532 } 7533 setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)7534 public void setDebugApp(String packageName, boolean waitForDebugger, 7535 boolean persistent) { 7536 setDebugApp(packageName, waitForDebugger, persistent, false); 7537 } 7538 setDebugApp(String packageName, boolean waitForDebugger, boolean persistent, boolean suspendUponWait)7539 private void setDebugApp(String packageName, boolean waitForDebugger, 7540 boolean persistent, boolean suspendUponWait) { 7541 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 7542 "setDebugApp()"); 7543 7544 final long ident = Binder.clearCallingIdentity(); 7545 try { 7546 // Note that this is not really thread safe if there are multiple 7547 // callers into it at the same time, but that's not a situation we 7548 // care about. 7549 if (persistent) { 7550 final ContentResolver resolver = mContext.getContentResolver(); 7551 Settings.Global.putString( 7552 resolver, Settings.Global.DEBUG_APP, 7553 packageName); 7554 Settings.Global.putInt( 7555 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 7556 waitForDebugger ? 1 : 0); 7557 } 7558 7559 synchronized (this) { 7560 if (!persistent) { 7561 mOrigDebugApp = mDebugApp; 7562 mOrigWaitForDebugger = mWaitForDebugger; 7563 } 7564 mDebugApp = packageName; 7565 mWaitForDebugger = waitForDebugger; 7566 mSuspendUponWait = suspendUponWait; 7567 mDebugTransient = !persistent; 7568 if (packageName != null) { 7569 forceStopPackageLocked(packageName, -1, false, false, true, true, 7570 false, false, UserHandle.USER_ALL, "set debug app"); 7571 } 7572 } 7573 } finally { 7574 Binder.restoreCallingIdentity(ident); 7575 } 7576 } 7577 7578 /** 7579 * Set or remove an agent to be run whenever an app with the given process name starts. 7580 * 7581 * This method will not check whether the given process name matches a debuggable app. That 7582 * would require scanning all current packages, and a rescan when new packages are installed 7583 * or updated. 7584 * 7585 * Instead, do the check when an application is started and matched to a stored agent. 7586 * 7587 * @param packageName the process name of the app. 7588 * @param agent the agent string to be used, or null to remove any previously set agent. 7589 */ 7590 @Override setAgentApp(@onNull String packageName, @Nullable String agent)7591 public void setAgentApp(@NonNull String packageName, @Nullable String agent) { 7592 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 7593 // its own permission. 7594 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7595 != PackageManager.PERMISSION_GRANTED) { 7596 throw new SecurityException( 7597 "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7598 } 7599 7600 synchronized (mAppProfiler.mProfilerLock) { 7601 mAppProfiler.setAgentAppLPf(packageName, agent); 7602 } 7603 } 7604 setTrackAllocationApp(ApplicationInfo app, String processName)7605 void setTrackAllocationApp(ApplicationInfo app, String processName) { 7606 enforceDebuggable(app); 7607 7608 synchronized (mProcLock) { 7609 mTrackAllocationApp = processName; 7610 } 7611 } 7612 setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo, ApplicationInfo sdkSandboxClientApp)7613 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo, 7614 ApplicationInfo sdkSandboxClientApp) { 7615 synchronized (mAppProfiler.mProfilerLock) { 7616 if (!Build.IS_DEBUGGABLE) { 7617 boolean isAppDebuggable = (app.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 7618 boolean isAppProfileable = app.isProfileableByShell(); 7619 7620 if (sdkSandboxClientApp != null) { 7621 isAppDebuggable |= 7622 (sdkSandboxClientApp.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 7623 isAppProfileable |= sdkSandboxClientApp.isProfileableByShell(); 7624 } 7625 if (!isAppDebuggable && !isAppProfileable) { 7626 throw new SecurityException("Process not debuggable, " 7627 + "and not profileable by shell: " + app.packageName); 7628 } 7629 } 7630 mAppProfiler.setProfileAppLPf(processName, profilerInfo); 7631 } 7632 } 7633 setNativeDebuggingAppLocked(ApplicationInfo app, String processName)7634 void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) { 7635 enforceDebuggable(app); 7636 mNativeDebuggingApp = processName; 7637 } 7638 7639 @Override setAlwaysFinish(boolean enabled)7640 public void setAlwaysFinish(boolean enabled) { 7641 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 7642 "setAlwaysFinish()"); 7643 7644 final long ident = Binder.clearCallingIdentity(); 7645 try { 7646 Settings.Global.putInt( 7647 mContext.getContentResolver(), 7648 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 7649 7650 synchronized (this) { 7651 mAlwaysFinishActivities = enabled; 7652 } 7653 } finally { 7654 Binder.restoreCallingIdentity(ident); 7655 } 7656 } 7657 7658 @Override setActivityController(IActivityController controller, boolean imAMonkey)7659 public void setActivityController(IActivityController controller, boolean imAMonkey) { 7660 if (controller != null) { 7661 Binder.allowBlocking(controller.asBinder()); 7662 } 7663 mActivityTaskManager.setActivityController(controller, imAMonkey); 7664 } 7665 7666 @Override setUserIsMonkey(boolean userIsMonkey)7667 public void setUserIsMonkey(boolean userIsMonkey) { 7668 synchronized (mProcLock) { 7669 synchronized (mPidsSelfLocked) { 7670 final int callingPid = Binder.getCallingPid(); 7671 ProcessRecord proc = mPidsSelfLocked.get(callingPid); 7672 if (proc == null) { 7673 throw new SecurityException("Unknown process: " + callingPid); 7674 } 7675 if (proc.getActiveInstrumentation() == null 7676 || proc.getActiveInstrumentation().mUiAutomationConnection == null) { 7677 throw new SecurityException("Only an instrumentation process " 7678 + "with a UiAutomation can call setUserIsMonkey"); 7679 } 7680 } 7681 mUserIsMonkey = userIsMonkey; 7682 } 7683 } 7684 7685 @Override isUserAMonkey()7686 public boolean isUserAMonkey() { 7687 synchronized (mProcLock) { 7688 // If there is a controller also implies the user is a monkey. 7689 return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey(); 7690 } 7691 } 7692 7693 @Override requestSystemServerHeapDump()7694 public void requestSystemServerHeapDump() { 7695 if (!Build.IS_DEBUGGABLE) { 7696 Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build"); 7697 return; 7698 } 7699 if (Binder.getCallingUid() != SYSTEM_UID) { 7700 // This also intentionally excludes secondary profiles from calling this. 7701 throw new SecurityException( 7702 "Only the system process is allowed to request a system heap dump"); 7703 } 7704 ProcessRecord pr; 7705 synchronized (mPidsSelfLocked) { 7706 pr = mPidsSelfLocked.get(myPid()); 7707 } 7708 if (pr == null) { 7709 Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid()); 7710 return; 7711 } 7712 synchronized (mAppProfiler.mProfilerLock) { 7713 mAppProfiler.startHeapDumpLPf(pr.mProfile, true); 7714 } 7715 } 7716 7717 /** 7718 * Takes a bugreport using bug report API ({@code BugreportManager}) with no pre-set 7719 * title and description 7720 */ 7721 @Override requestBugReport(@ugreportParams.BugreportMode int bugreportType)7722 public void requestBugReport(@BugreportParams.BugreportMode int bugreportType) { 7723 requestBugReportWithDescription(null, null, bugreportType, 0L); 7724 } 7725 7726 /** 7727 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 7728 * triggered by sending a broadcast to Shell. 7729 */ 7730 @Override requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType)7731 public void requestBugReportWithDescription(@Nullable String shareTitle, 7732 @Nullable String shareDescription, int bugreportType) { 7733 requestBugReportWithDescription(shareTitle, shareDescription, bugreportType, /*nonce*/ 0L); 7734 } 7735 7736 /** 7737 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 7738 * triggered by sending a broadcast to Shell. 7739 */ requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType, long nonce)7740 public void requestBugReportWithDescription(@Nullable String shareTitle, 7741 @Nullable String shareDescription, int bugreportType, long nonce) { 7742 requestBugReportWithDescription(shareTitle, shareDescription, bugreportType, nonce, null); 7743 } 7744 7745 /** 7746 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 7747 * triggered by sending a broadcast to Shell. Optionally adds an extra attachment. 7748 */ requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType, long nonce, @Nullable Uri extraAttachment)7749 public void requestBugReportWithDescription(@Nullable String shareTitle, 7750 @Nullable String shareDescription, int bugreportType, long nonce, 7751 @Nullable Uri extraAttachment) { 7752 String type = null; 7753 switch (bugreportType) { 7754 case BugreportParams.BUGREPORT_MODE_FULL: 7755 type = "bugreportfull"; 7756 break; 7757 case BugreportParams.BUGREPORT_MODE_INTERACTIVE: 7758 type = "bugreportplus"; 7759 break; 7760 case BugreportParams.BUGREPORT_MODE_REMOTE: 7761 type = "bugreportremote"; 7762 break; 7763 case BugreportParams.BUGREPORT_MODE_WEAR: 7764 type = "bugreportwear"; 7765 break; 7766 case BugreportParams.BUGREPORT_MODE_TELEPHONY: 7767 type = "bugreporttelephony"; 7768 break; 7769 case BugreportParams.BUGREPORT_MODE_WIFI: 7770 type = "bugreportwifi"; 7771 break; 7772 case BugreportParams.BUGREPORT_MODE_ONBOARDING: 7773 type = "bugreportonboarding"; 7774 break; 7775 default: 7776 throw new IllegalArgumentException( 7777 "Provided bugreport type is not correct, value: " 7778 + bugreportType); 7779 } 7780 // Always log caller, even if it does not have permission to dump. 7781 Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid()); 7782 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 7783 7784 if (!TextUtils.isEmpty(shareTitle)) { 7785 if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) { 7786 String errorStr = "shareTitle should be less than " 7787 + MAX_BUGREPORT_TITLE_SIZE + " characters"; 7788 throw new IllegalArgumentException(errorStr); 7789 } 7790 if (!TextUtils.isEmpty(shareDescription)) { 7791 if (shareDescription.length() > MAX_BUGREPORT_DESCRIPTION_SIZE) { 7792 String errorStr = "shareDescription should be less than " 7793 + MAX_BUGREPORT_DESCRIPTION_SIZE + " characters"; 7794 throw new IllegalArgumentException(errorStr); 7795 } 7796 } 7797 Slog.d(TAG, "Bugreport notification title " + shareTitle 7798 + " description " + shareDescription); 7799 } 7800 // Create intent to trigger Bugreport API via Shell 7801 Intent triggerShellBugreport = new Intent(); 7802 triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED); 7803 triggerShellBugreport.setPackage(SHELL_APP_PACKAGE); 7804 triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType); 7805 triggerShellBugreport.putExtra(EXTRA_BUGREPORT_NONCE, nonce); 7806 if (extraAttachment != null) { 7807 triggerShellBugreport.putExtra(EXTRA_EXTRA_ATTACHMENT_URI, extraAttachment); 7808 triggerShellBugreport.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7809 } 7810 triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 7811 triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 7812 if (shareTitle != null) { 7813 triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle); 7814 } 7815 if (shareDescription != null) { 7816 triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription); 7817 } 7818 final long identity = Binder.clearCallingIdentity(); 7819 try { 7820 // Send broadcast to shell to trigger bugreport using Bugreport API 7821 // Always start the shell process on the current user to ensure that 7822 // the foreground user can see all bugreport notifications. 7823 // In case of BUGREPORT_MODE_REMOTE send the broadcast to SYSTEM user as the device 7824 // owner apps are running on the SYSTEM user. 7825 if (bugreportType == BugreportParams.BUGREPORT_MODE_REMOTE) { 7826 mContext.sendBroadcastAsUser(triggerShellBugreport, UserHandle.SYSTEM); 7827 } else { 7828 mContext.sendBroadcastAsUser(triggerShellBugreport, 7829 getCurrentUser().getUserHandle()); 7830 } 7831 } finally { 7832 Binder.restoreCallingIdentity(identity); 7833 } 7834 } 7835 7836 /** 7837 * Takes a telephony bugreport with title and description 7838 */ 7839 @Override requestTelephonyBugReport(String shareTitle, String shareDescription)7840 public void requestTelephonyBugReport(String shareTitle, String shareDescription) { 7841 requestBugReportWithDescription(shareTitle, shareDescription, 7842 BugreportParams.BUGREPORT_MODE_TELEPHONY); 7843 } 7844 7845 /** 7846 * Takes a minimal bugreport of Wifi-related state with pre-set title and description 7847 */ 7848 @Override requestWifiBugReport(String shareTitle, String shareDescription)7849 public void requestWifiBugReport(String shareTitle, String shareDescription) { 7850 requestBugReportWithDescription(shareTitle, shareDescription, 7851 BugreportParams.BUGREPORT_MODE_WIFI); 7852 } 7853 7854 /** 7855 * Takes an interactive bugreport with a progress notification 7856 */ 7857 @Override requestInteractiveBugReport()7858 public void requestInteractiveBugReport() { 7859 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE); 7860 } 7861 7862 /** 7863 * Takes an interactive bugreport with a progress notification. Also attaches given file uri. 7864 */ 7865 @Override requestBugReportWithExtraAttachment(@onNull Uri extraAttachment)7866 public void requestBugReportWithExtraAttachment(@NonNull Uri extraAttachment) { 7867 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE, 0L, 7868 extraAttachment); 7869 } 7870 7871 /** 7872 * Takes an interactive bugreport with a progress notification. Also, shows the given title and 7873 * description on the final share notification 7874 */ 7875 @Override requestInteractiveBugReportWithDescription(String shareTitle, String shareDescription)7876 public void requestInteractiveBugReportWithDescription(String shareTitle, 7877 String shareDescription) { 7878 requestBugReportWithDescription(shareTitle, shareDescription, 7879 BugreportParams.BUGREPORT_MODE_INTERACTIVE); 7880 } 7881 7882 /** 7883 * Takes a bugreport with minimal user interference 7884 */ 7885 @Override requestFullBugReport()7886 public void requestFullBugReport() { 7887 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_FULL); 7888 } 7889 7890 /** 7891 * Takes a bugreport remotely 7892 */ 7893 @Override requestRemoteBugReport(long nonce)7894 public void requestRemoteBugReport(long nonce) { 7895 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE, nonce); 7896 } 7897 7898 /** 7899 * Launches a bugreport-whitelisted app to handle a bugreport. 7900 * 7901 * <p>Allows a bug report handler app to take bugreports on the user's behalf. The handler can 7902 * be predefined in the config, meant to be launched with the primary user. The user can 7903 * override this with a different (or same) handler app on possibly a different user. This is 7904 * useful for capturing bug reports from work profile, for instance. 7905 * 7906 * @return true if there is a bugreport-whitelisted app to handle a bugreport, or false 7907 * otherwise. 7908 */ 7909 @Override launchBugReportHandlerApp()7910 public boolean launchBugReportHandlerApp() { 7911 7912 Context currentUserContext = mContext.createContextAsUser(getCurrentUser().getUserHandle(), 7913 /* flags= */ 0); 7914 if (!BugReportHandlerUtil.isBugReportHandlerEnabled(currentUserContext)) { 7915 return false; 7916 } 7917 7918 // Always log caller, even if it does not have permission to dump. 7919 Slog.i(TAG, "launchBugReportHandlerApp requested by UID " + Binder.getCallingUid()); 7920 enforceCallingPermission(android.Manifest.permission.DUMP, 7921 "launchBugReportHandlerApp"); 7922 7923 return BugReportHandlerUtil.launchBugReportHandlerApp(currentUserContext); 7924 } 7925 7926 /** 7927 * Get packages of bugreport-whitelisted apps to handle a bug report. 7928 * 7929 * @return packages of bugreport-whitelisted apps to handle a bug report. 7930 */ 7931 @Override getBugreportWhitelistedPackages()7932 public List<String> getBugreportWhitelistedPackages() { 7933 enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING, 7934 "getBugreportWhitelistedPackages"); 7935 return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages()); 7936 } 7937 registerProcessObserver(IProcessObserver observer)7938 public void registerProcessObserver(IProcessObserver observer) { 7939 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 7940 "registerProcessObserver()"); 7941 mProcessList.registerProcessObserver(observer); 7942 } 7943 7944 @Override unregisterProcessObserver(IProcessObserver observer)7945 public void unregisterProcessObserver(IProcessObserver observer) { 7946 mProcessList.unregisterProcessObserver(observer); 7947 } 7948 7949 @Override getUidProcessState(int uid, String callingPackage)7950 public int getUidProcessState(int uid, String callingPackage) { 7951 if (!hasUsageStatsPermission(callingPackage)) { 7952 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 7953 "getUidProcessState"); 7954 } 7955 // In case the caller is requesting processState of an app in a different user, 7956 // then verify the caller has INTERACT_ACROSS_USERS_FULL permission 7957 mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 7958 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY, 7959 "getUidProcessState", callingPackage); // Ignore return value 7960 7961 synchronized (mProcLock) { 7962 return getUidProcessStateInnerLOSP(uid); 7963 } 7964 } 7965 7966 @Override getBindingUidProcessState(int targetUid, String callingPackage)7967 public int getBindingUidProcessState(int targetUid, String callingPackage) { 7968 if (!hasUsageStatsPermission(callingPackage)) { 7969 enforceCallingPermission(android.Manifest.permission.GET_BINDING_UID_IMPORTANCE, 7970 "getBindingUidProcessState"); 7971 } 7972 // We don't need to do a cross-user check here (unlike getUidProcessState), 7973 // because we only allow to see UIDs that are actively communicating with the caller. 7974 7975 final int callingUid = Binder.getCallingUid(); 7976 final long token = Binder.clearCallingIdentity(); 7977 try { 7978 synchronized (this) { 7979 final boolean allowed = (callingUid == targetUid) 7980 || hasServiceBindingOrProviderUseLocked(callingUid, targetUid); 7981 if (!allowed) { 7982 return PROCESS_STATE_NONEXISTENT; 7983 } 7984 return getUidProcessStateInnerLOSP(targetUid); 7985 } 7986 } finally { 7987 Binder.restoreCallingIdentity(token); 7988 } 7989 } 7990 7991 @GuardedBy(anyOf = {"this", "mProcLock"}) getUidProcessStateInnerLOSP(int uid)7992 private int getUidProcessStateInnerLOSP(int uid) { 7993 if (mPendingStartActivityUids.isPendingTopUid(uid)) { 7994 return PROCESS_STATE_TOP; 7995 } 7996 return mProcessList.getUidProcStateLOSP(uid); 7997 } 7998 7999 /** 8000 * Ensure that {@code clientUid} has a bound service client to {@code callingUid} 8001 */ 8002 @GuardedBy("this") hasServiceBindingOrProviderUseLocked(int callingUid, int clientUid)8003 private boolean hasServiceBindingOrProviderUseLocked(int callingUid, int clientUid) { 8004 // See if there's a service binding 8005 final Boolean hasBinding = mProcessList.searchEachLruProcessesLOSP( 8006 false, pr -> { 8007 if (pr.uid == callingUid) { 8008 final ProcessServiceRecord psr = pr.mServices; 8009 final int serviceCount = psr.mServices.size(); 8010 for (int svc = 0; svc < serviceCount; svc++) { 8011 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns = 8012 psr.mServices.valueAt(svc).getConnections(); 8013 final int size = conns.size(); 8014 for (int conni = 0; conni < size; conni++) { 8015 final ArrayList<ConnectionRecord> crs = conns.valueAt(conni); 8016 for (int con = 0; con < crs.size(); con++) { 8017 final ConnectionRecord cr = crs.get(con); 8018 final ProcessRecord clientPr = cr.binding.client; 8019 8020 if (clientPr.uid == clientUid) { 8021 return Boolean.TRUE; 8022 } 8023 } 8024 } 8025 } 8026 } 8027 return null; 8028 }); 8029 if (Boolean.TRUE.equals(hasBinding)) { 8030 return true; 8031 } 8032 8033 final Boolean hasProviderClient = mProcessList.searchEachLruProcessesLOSP( 8034 false, pr -> { 8035 if (pr.uid == callingUid) { 8036 final ProcessProviderRecord ppr = pr.mProviders; 8037 for (int provi = ppr.numberOfProviders() - 1; provi >= 0; provi--) { 8038 ContentProviderRecord cpr = ppr.getProviderAt(provi); 8039 8040 for (int i = cpr.connections.size() - 1; i >= 0; i--) { 8041 ContentProviderConnection conn = cpr.connections.get(i); 8042 ProcessRecord client = conn.client; 8043 if (client.uid == clientUid) { 8044 return Boolean.TRUE; 8045 } 8046 } 8047 } 8048 } 8049 return null; 8050 }); 8051 8052 return Boolean.TRUE.equals(hasProviderClient); 8053 } 8054 8055 @Override getUidProcessCapabilities(int uid, String callingPackage)8056 public @ProcessCapability int getUidProcessCapabilities(int uid, String callingPackage) { 8057 if (!hasUsageStatsPermission(callingPackage)) { 8058 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8059 "getUidProcessState"); 8060 } 8061 // In case the caller is requesting processCapabilities of an app in a different user, 8062 // then verify the caller has INTERACT_ACROSS_USERS_FULL permission 8063 mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 8064 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY, 8065 "getUidProcessCapabilities", callingPackage); // Ignore return value 8066 8067 synchronized (mProcLock) { 8068 return mProcessList.getUidProcessCapabilityLOSP(uid); 8069 } 8070 } 8071 8072 @Override registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)8073 public void registerUidObserver(IUidObserver observer, int which, int cutpoint, 8074 String callingPackage) { 8075 registerUidObserverForUids(observer, which, cutpoint, callingPackage, null /* uids */); 8076 } 8077 8078 /** 8079 * Registers a UidObserver with a uid filter. 8080 * 8081 * @param observer The UidObserver implementation to register. 8082 * @param which A bitmask of events to observe. See ActivityManager.UID_OBSERVER_*. 8083 * @param cutpoint The cutpoint for onUidStateChanged events. When the state crosses this 8084 * threshold in either direction, onUidStateChanged will be called. 8085 * @param callingPackage The name of the calling package. 8086 * @param uids A list of uids to watch. If all uids are to be watched, use 8087 * registerUidObserver instead. 8088 * @throws RemoteException 8089 * @return Returns A binder token identifying the UidObserver registration. 8090 */ 8091 @Override registerUidObserverForUids(IUidObserver observer, int which, int cutpoint, String callingPackage, int[] uids)8092 public IBinder registerUidObserverForUids(IUidObserver observer, int which, int cutpoint, 8093 String callingPackage, int[] uids) { 8094 if (!hasUsageStatsPermission(callingPackage)) { 8095 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8096 "registerUidObserver"); 8097 } 8098 return mUidObserverController.register(observer, which, cutpoint, callingPackage, 8099 Binder.getCallingUid(), uids); 8100 } 8101 8102 @Override unregisterUidObserver(IUidObserver observer)8103 public void unregisterUidObserver(IUidObserver observer) { 8104 mUidObserverController.unregister(observer); 8105 } 8106 8107 /** 8108 * Adds a uid to the list of uids that a UidObserver will receive updates about. 8109 * 8110 * @param observerToken The binder token identifying the UidObserver registration. 8111 * @param callingPackage The name of the calling package. 8112 * @param uid The uid to watch. 8113 * @throws RemoteException 8114 */ 8115 @Override addUidToObserver(IBinder observerToken, String callingPackage, int uid)8116 public void addUidToObserver(IBinder observerToken, String callingPackage, int uid) { 8117 if (!hasUsageStatsPermission(callingPackage)) { 8118 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8119 "registerUidObserver"); 8120 } 8121 mUidObserverController.addUidToObserver(observerToken, uid); 8122 } 8123 8124 /** 8125 * Removes a uid from the list of uids that a UidObserver will receive updates about. 8126 * 8127 * @param observerToken The binder token identifying the UidObserver registration. 8128 * @param callingPackage The name of the calling package. 8129 * @param uid The uid to stop watching. 8130 * @throws RemoteException 8131 */ 8132 @Override removeUidFromObserver(IBinder observerToken, String callingPackage, int uid)8133 public void removeUidFromObserver(IBinder observerToken, String callingPackage, int uid) { 8134 if (!hasUsageStatsPermission(callingPackage)) { 8135 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8136 "registerUidObserver"); 8137 } 8138 mUidObserverController.removeUidFromObserver(observerToken, uid); 8139 } 8140 8141 @Override isUidActive(int uid, String callingPackage)8142 public boolean isUidActive(int uid, String callingPackage) { 8143 if (!hasUsageStatsPermission(callingPackage)) { 8144 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8145 "isUidActive"); 8146 } 8147 synchronized (mProcLock) { 8148 if (isUidActiveLOSP(uid)) { 8149 return true; 8150 } 8151 } 8152 return mInternal.isPendingTopUid(uid); 8153 } 8154 8155 @GuardedBy(anyOf = {"this", "mProcLock"}) isUidActiveLOSP(int uid)8156 boolean isUidActiveLOSP(int uid) { 8157 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 8158 return uidRecord != null && !uidRecord.isSetIdle(); 8159 } 8160 8161 @Override getUidLastIdleElapsedTime(int uid, String callingPackage)8162 public long getUidLastIdleElapsedTime(int uid, String callingPackage) { 8163 if (!hasUsageStatsPermission(callingPackage)) { 8164 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8165 "getUidLastIdleElapsedTime"); 8166 } 8167 synchronized (mProcLock) { 8168 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 8169 return uidRecord != null ? uidRecord.getRealLastIdleTime() : 0; 8170 } 8171 } 8172 8173 @GuardedBy("mUidFrozenStateChangedCallbackList") 8174 private final RemoteCallbackList<IUidFrozenStateChangedCallback> 8175 mUidFrozenStateChangedCallbackList = new RemoteCallbackList<>(); 8176 8177 /** 8178 * Register a {@link IUidFrozenStateChangedCallback} to receive Uid frozen state events. 8179 * 8180 * @param callback remote callback object to be registered 8181 */ 8182 @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS) 8183 @Override registerUidFrozenStateChangedCallback( @onNull IUidFrozenStateChangedCallback callback)8184 public void registerUidFrozenStateChangedCallback( 8185 @NonNull IUidFrozenStateChangedCallback callback) { 8186 Preconditions.checkNotNull(callback, "callback cannot be null"); 8187 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8188 "registerUidFrozenStateChangedCallback()"); 8189 synchronized (mUidFrozenStateChangedCallbackList) { 8190 final boolean registered = mUidFrozenStateChangedCallbackList.register(callback); 8191 if (!registered) { 8192 Slog.w(TAG, "Failed to register with RemoteCallbackList!"); 8193 } 8194 } 8195 } 8196 8197 /** 8198 * Unregister a {@link IUidFrozenStateChangedCallback}. 8199 * 8200 * @param callback remote callback object to be unregistered 8201 */ 8202 @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS) 8203 @Override unregisterUidFrozenStateChangedCallback( @onNull IUidFrozenStateChangedCallback callback)8204 public void unregisterUidFrozenStateChangedCallback( 8205 @NonNull IUidFrozenStateChangedCallback callback) { 8206 Preconditions.checkNotNull(callback, "callback cannot be null"); 8207 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8208 "unregisterUidFrozenStateChangedCallback()"); 8209 synchronized (mUidFrozenStateChangedCallbackList) { 8210 mUidFrozenStateChangedCallbackList.unregister(callback); 8211 } 8212 } 8213 8214 /** 8215 * Query the frozen state of a list of UIDs. 8216 * 8217 * @param uids the array of UIDs which the client would like to know the frozen state of. 8218 * @return An array containing the frozen state for each requested UID, by index. Will be set 8219 * to {@link UidFrozenStateChangedCallback#UID_FROZEN_STATE_FROZEN} 8220 * if the UID is frozen. If the UID is not frozen or not found, 8221 * {@link UidFrozenStateChangedCallback#UID_FROZEN_STATE_UNFROZEN} 8222 * will be set. 8223 * 8224 * @hide 8225 */ 8226 @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS) 8227 @Override getUidFrozenState(@onNull int[] uids)8228 public @NonNull int[] getUidFrozenState(@NonNull int[] uids) { 8229 Preconditions.checkNotNull(uids, "uid array cannot be null"); 8230 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8231 "getUidFrozenState()"); 8232 8233 final int[] frozenStates = new int[uids.length]; 8234 synchronized (mProcLock) { 8235 for (int i = 0; i < uids.length; i++) { 8236 final UidRecord uidRec = mProcessList.mActiveUids.get(uids[i]); 8237 if (uidRec != null && uidRec.areAllProcessesFrozen()) { 8238 frozenStates[i] = UID_FROZEN_STATE_FROZEN; 8239 } else { 8240 frozenStates[i] = UID_FROZEN_STATE_UNFROZEN; 8241 } 8242 } 8243 } 8244 return frozenStates; 8245 } 8246 8247 /** 8248 * Notify the system that a UID has been frozen or unfrozen. 8249 * 8250 * @param uids The Uid(s) in question 8251 * @param frozenStates Frozen state for each UID index 8252 * 8253 * @hide 8254 */ reportUidFrozenStateChanged(@onNull int[] uids, @UidFrozenState int[] frozenStates)8255 public void reportUidFrozenStateChanged(@NonNull int[] uids, 8256 @UidFrozenState int[] frozenStates) { 8257 synchronized (mUidFrozenStateChangedCallbackList) { 8258 final int n = mUidFrozenStateChangedCallbackList.beginBroadcast(); 8259 for (int i = 0; i < n; i++) { 8260 try { 8261 mUidFrozenStateChangedCallbackList.getBroadcastItem(i).onUidFrozenStateChanged( 8262 uids, frozenStates); 8263 } catch (RemoteException e) { 8264 /* 8265 * The process at the other end has died or otherwise gone away. 8266 * According to spec, RemoteCallbacklist will take care of unregistering any 8267 * object associated with that process - we are safe to ignore the exception 8268 * here. 8269 */ 8270 } 8271 } 8272 mUidFrozenStateChangedCallbackList.finishBroadcast(); 8273 } 8274 } 8275 8276 @Override setPersistentVrThread(int tid)8277 public void setPersistentVrThread(int tid) { 8278 mActivityTaskManager.setPersistentVrThread(tid); 8279 } 8280 8281 /** 8282 * Schedule the given thread a normal scheduling priority. 8283 * 8284 * @param tid the tid of the thread to adjust the scheduling of. 8285 * @param suppressLogs {@code true} if any error logging should be disabled. 8286 * 8287 * @return {@code true} if this succeeded. 8288 */ scheduleAsRegularPriority(int tid, boolean suppressLogs)8289 public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) { 8290 try { 8291 Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0); 8292 return true; 8293 } catch (IllegalArgumentException e) { 8294 if (!suppressLogs) { 8295 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 8296 } 8297 } catch (SecurityException e) { 8298 if (!suppressLogs) { 8299 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 8300 } 8301 } 8302 return false; 8303 } 8304 8305 /** 8306 * Schedule the given thread an FIFO scheduling priority. 8307 * 8308 * @param tid the tid of the thread to adjust the scheduling of. 8309 * @param suppressLogs {@code true} if any error logging should be disabled. 8310 * 8311 * @return {@code true} if this succeeded. 8312 */ scheduleAsFifoPriority(int tid, boolean suppressLogs)8313 public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) { 8314 try { 8315 Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1); 8316 return true; 8317 } catch (IllegalArgumentException e) { 8318 if (!suppressLogs) { 8319 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 8320 } 8321 } catch (SecurityException e) { 8322 if (!suppressLogs) { 8323 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 8324 } 8325 } 8326 return false; 8327 } 8328 8329 /** 8330 * Switches the priority between SCHED_FIFO and SCHED_OTHER for the main thread and render 8331 * thread of the given process. 8332 */ 8333 @GuardedBy("mProcLock") setFifoPriority(@onNull ProcessRecord app, boolean enable)8334 static void setFifoPriority(@NonNull ProcessRecord app, boolean enable) { 8335 final int pid = app.getPid(); 8336 final int renderThreadTid = app.getRenderThreadTid(); 8337 if (enable) { 8338 scheduleAsFifoPriority(pid, true /* suppressLogs */); 8339 if (renderThreadTid != 0) { 8340 scheduleAsFifoPriority(renderThreadTid, true /* suppressLogs */); 8341 } 8342 } else { 8343 scheduleAsRegularPriority(pid, true /* suppressLogs */); 8344 if (renderThreadTid != 0) { 8345 scheduleAsRegularPriority(renderThreadTid, true /* suppressLogs */); 8346 } 8347 } 8348 } 8349 8350 @Override setRenderThread(int tid)8351 public void setRenderThread(int tid) { 8352 synchronized (mProcLock) { 8353 ProcessRecord proc; 8354 int pid = Binder.getCallingPid(); 8355 if (pid == Process.myPid()) { 8356 demoteSystemServerRenderThread(tid); 8357 return; 8358 } 8359 synchronized (mPidsSelfLocked) { 8360 proc = mPidsSelfLocked.get(pid); 8361 } 8362 if (proc != null && proc.getRenderThreadTid() == 0 && tid > 0) { 8363 // ensure the tid belongs to the process 8364 if (!isThreadInProcess(pid, tid)) { 8365 throw new IllegalArgumentException( 8366 "Render thread does not belong to process"); 8367 } 8368 proc.setRenderThreadTid(tid); 8369 if (DEBUG_OOM_ADJ) { 8370 Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid); 8371 } 8372 // promote to FIFO now 8373 if (proc.mState.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) { 8374 if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band"); 8375 if (proc.useFifoUiScheduling()) { 8376 setThreadScheduler(proc.getRenderThreadTid(), 8377 SCHED_FIFO | SCHED_RESET_ON_FORK, 1); 8378 } else { 8379 setThreadPriority(proc.getRenderThreadTid(), THREAD_PRIORITY_TOP_APP_BOOST); 8380 } 8381 } 8382 } else { 8383 if (DEBUG_OOM_ADJ) { 8384 Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " 8385 + "PID: " + pid + ", TID: " + tid + " FIFO: " + mUseFifoUiScheduling); 8386 } 8387 } 8388 } 8389 } 8390 8391 /** 8392 * We only use RenderThread in system_server to store task snapshots to the disk, which should 8393 * happen in the background. Thus, demote render thread from system_server to a lower priority. 8394 * 8395 * @param tid the tid of the RenderThread 8396 */ demoteSystemServerRenderThread(int tid)8397 private void demoteSystemServerRenderThread(int tid) { 8398 setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND); 8399 } 8400 8401 @Override isVrModePackageEnabled(ComponentName packageName)8402 public boolean isVrModePackageEnabled(ComponentName packageName) { 8403 mActivityTaskManager.enforceSystemHasVrFeature(); 8404 8405 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); 8406 8407 return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) == 8408 VrManagerInternal.NO_ERROR; 8409 } 8410 isTopActivityImmersive()8411 public boolean isTopActivityImmersive() { 8412 return mActivityTaskManager.isTopActivityImmersive(); 8413 } 8414 8415 @Override isTopOfTask(IBinder token)8416 public boolean isTopOfTask(IBinder token) { 8417 return ActivityClient.getInstance().isTopOfTask(token); 8418 } 8419 8420 @Override setHasTopUi(boolean hasTopUi)8421 public void setHasTopUi(boolean hasTopUi) throws RemoteException { 8422 if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) { 8423 String msg = "Permission Denial: setHasTopUi() from pid=" 8424 + Binder.getCallingPid() 8425 + ", uid=" + Binder.getCallingUid() 8426 + " requires " + permission.INTERNAL_SYSTEM_WINDOW; 8427 Slog.w(TAG, msg); 8428 throw new SecurityException(msg); 8429 } 8430 final int pid = Binder.getCallingPid(); 8431 final long origId = Binder.clearCallingIdentity(); 8432 try { 8433 synchronized (this) { 8434 boolean changed = false; 8435 ProcessRecord pr; 8436 synchronized (mPidsSelfLocked) { 8437 pr = mPidsSelfLocked.get(pid); 8438 if (pr == null) { 8439 Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid); 8440 return; 8441 } 8442 if (pr.mState.hasTopUi() != hasTopUi) { 8443 if (DEBUG_OOM_ADJ) { 8444 Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid); 8445 } 8446 pr.mState.setHasTopUi(hasTopUi); 8447 changed = true; 8448 } 8449 } 8450 if (changed) { 8451 updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY); 8452 } 8453 } 8454 } finally { 8455 Binder.restoreCallingIdentity(origId); 8456 } 8457 } 8458 enterSafeMode()8459 public final void enterSafeMode() { 8460 synchronized(this) { 8461 // It only makes sense to do this before the system is ready 8462 // and started launching other packages. 8463 if (!mSystemReady) { 8464 try { 8465 AppGlobals.getPackageManager().enterSafeMode(); 8466 } catch (RemoteException e) { 8467 } 8468 } 8469 8470 mSafeMode = true; 8471 } 8472 } 8473 showSafeModeOverlay()8474 public final void showSafeModeOverlay() { 8475 View v = LayoutInflater.from(mContext).inflate( 8476 com.android.internal.R.layout.safe_mode, null); 8477 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 8478 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 8479 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 8480 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 8481 lp.gravity = Gravity.BOTTOM | Gravity.START; 8482 lp.format = v.getBackground().getOpacity(); 8483 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 8484 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 8485 lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS; 8486 ((WindowManager)mContext.getSystemService( 8487 Context.WINDOW_SERVICE)).addView(v, lp); 8488 } 8489 8490 @Override noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)8491 public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, 8492 String sourcePkg, String tag) { 8493 if (workSource != null && workSource.isEmpty()) { 8494 workSource = null; 8495 } 8496 8497 if (sourceUid <= 0 && workSource == null) { 8498 // Try and derive a UID to attribute things to based on the caller. 8499 if (sender != null) { 8500 if (!(sender instanceof PendingIntentRecord)) { 8501 return; 8502 } 8503 8504 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8505 final int callerUid = Binder.getCallingUid(); 8506 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8507 } else { 8508 // TODO(narayan): Should we throw an exception in this case ? It means that we 8509 // haven't been able to derive a UID to attribute things to. 8510 return; 8511 } 8512 } 8513 8514 int standbyBucket = 0; 8515 8516 mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag); 8517 if (workSource != null) { 8518 String workSourcePackage = workSource.getPackageName(0); 8519 int workSourceUid = workSource.getAttributionUid(); 8520 if (workSourcePackage == null) { 8521 workSourcePackage = sourcePkg; 8522 workSourceUid = sourceUid; 8523 } 8524 8525 if (mUsageStatsService != null) { 8526 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage, 8527 UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime()); 8528 } 8529 8530 FrameworkStatsLog.write(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag, 8531 sourcePkg, standbyBucket); 8532 if (DEBUG_POWER) { 8533 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 8534 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 8535 + standbyBucket + " wsName=" + workSourcePackage + ")]"); 8536 } 8537 } else { 8538 if (mUsageStatsService != null) { 8539 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg, 8540 UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime()); 8541 } 8542 FrameworkStatsLog.write_non_chained(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, sourceUid, 8543 null, tag, sourcePkg, standbyBucket); 8544 if (DEBUG_POWER) { 8545 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 8546 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 8547 + standbyBucket + "]"); 8548 } 8549 } 8550 8551 } 8552 8553 @Override noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8554 public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, 8555 String tag) { 8556 if (workSource != null && workSource.isEmpty()) { 8557 workSource = null; 8558 } 8559 8560 if (sourceUid <= 0 && workSource == null) { 8561 // Try and derive a UID to attribute things to based on the caller. 8562 if (sender != null) { 8563 if (!(sender instanceof PendingIntentRecord)) { 8564 return; 8565 } 8566 8567 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8568 final int callerUid = Binder.getCallingUid(); 8569 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8570 } else { 8571 // TODO(narayan): Should we throw an exception in this case ? It means that we 8572 // haven't been able to derive a UID to attribute things to. 8573 return; 8574 } 8575 } 8576 8577 if (DEBUG_POWER) { 8578 Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource + 8579 ", tag=" + tag + "]"); 8580 } 8581 8582 mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid); 8583 } 8584 8585 @Override noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8586 public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, 8587 String tag) { 8588 if (workSource != null && workSource.isEmpty()) { 8589 workSource = null; 8590 } 8591 8592 if (sourceUid <= 0 && workSource == null) { 8593 // Try and derive a UID to attribute things to based on the caller. 8594 if (sender != null) { 8595 if (!(sender instanceof PendingIntentRecord)) { 8596 return; 8597 } 8598 8599 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8600 final int callerUid = Binder.getCallingUid(); 8601 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8602 } else { 8603 // TODO(narayan): Should we throw an exception in this case ? It means that we 8604 // haven't been able to derive a UID to attribute things to. 8605 return; 8606 } 8607 } 8608 8609 if (DEBUG_POWER) { 8610 Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource + 8611 ", tag=" + tag + "]"); 8612 } 8613 8614 mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid); 8615 } 8616 killPids(int[] pids, String pReason, boolean secure)8617 public boolean killPids(int[] pids, String pReason, boolean secure) { 8618 if (Binder.getCallingUid() != SYSTEM_UID) { 8619 throw new SecurityException("killPids only available to the system"); 8620 } 8621 final String reason = (pReason == null) ? "Unknown" : pReason; 8622 // XXX Note: don't acquire main activity lock here, because the window 8623 // manager calls in with its locks held. 8624 8625 boolean killed = false; 8626 final ArrayList<ProcessRecord> killCandidates = new ArrayList<>(); 8627 synchronized (mPidsSelfLocked) { 8628 int worstType = 0; 8629 for (int i = 0; i < pids.length; i++) { 8630 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 8631 if (proc != null) { 8632 int type = proc.mState.getSetAdj(); 8633 if (type > worstType) { 8634 worstType = type; 8635 } 8636 } 8637 } 8638 8639 // If the worst oom_adj is somewhere in the cached proc LRU range, 8640 // then constrain it so we will kill all cached procs. 8641 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 8642 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 8643 worstType = ProcessList.CACHED_APP_MIN_ADJ; 8644 } 8645 8646 // If this is not a secure call, don't let it kill processes that 8647 // are important. 8648 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 8649 worstType = ProcessList.SERVICE_ADJ; 8650 } 8651 8652 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 8653 for (int i = 0; i < pids.length; i++) { 8654 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 8655 if (proc == null) { 8656 continue; 8657 } 8658 int adj = proc.mState.getSetAdj(); 8659 if (adj >= worstType && !proc.isKilledByAm()) { 8660 killCandidates.add(proc); 8661 killed = true; 8662 } 8663 } 8664 } 8665 if (!killCandidates.isEmpty()) { 8666 mHandler.post(() -> { 8667 synchronized (ActivityManagerService.this) { 8668 for (int i = 0, size = killCandidates.size(); i < size; i++) { 8669 killCandidates.get(i).killLocked(reason, 8670 ApplicationExitInfo.REASON_OTHER, 8671 ApplicationExitInfo.SUBREASON_KILL_PID, true); 8672 } 8673 } 8674 }); 8675 } 8676 return killed; 8677 } 8678 killUid(int appId, int userId, int reason, int subReason, String reasonAsString)8679 private void killUid(int appId, int userId, int reason, int subReason, 8680 String reasonAsString) { 8681 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 8682 synchronized (this) { 8683 final long identity = Binder.clearCallingIdentity(); 8684 try { 8685 synchronized (mProcLock) { 8686 mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId, 8687 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 8688 true /* callerWillRestart */, true /* doit */, 8689 true /* evenPersistent */, false /* setRemoved */, 8690 false /* uninstalling */, 8691 reason, 8692 subReason, 8693 reasonAsString != null ? reasonAsString : "kill uid"); 8694 } 8695 } finally { 8696 Binder.restoreCallingIdentity(identity); 8697 } 8698 } 8699 } 8700 8701 @Override killUid(int appId, int userId, String reason)8702 public void killUid(int appId, int userId, String reason) { 8703 killUid(appId, userId, ApplicationExitInfo.REASON_OTHER, 8704 ApplicationExitInfo.SUBREASON_KILL_UID, reason); 8705 } 8706 8707 @Override killUidForPermissionChange(int appId, int userId, String reason)8708 public void killUidForPermissionChange(int appId, int userId, String reason) { 8709 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 8710 synchronized (this) { 8711 final long identity = Binder.clearCallingIdentity(); 8712 try { 8713 synchronized (mProcLock) { 8714 mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId, 8715 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 8716 true /* callerWillRestart */, true /* doit */, 8717 true /* evenPersistent */, false /* setRemoved */, 8718 false /* uninstalling */, 8719 ApplicationExitInfo.REASON_PERMISSION_CHANGE, 8720 ApplicationExitInfo.SUBREASON_UNKNOWN, 8721 reason != null ? reason : "kill uid"); 8722 } 8723 } finally { 8724 Binder.restoreCallingIdentity(identity); 8725 } 8726 } 8727 } 8728 8729 @Override killProcessesBelowForeground(String reason)8730 public boolean killProcessesBelowForeground(String reason) { 8731 if (Binder.getCallingUid() != SYSTEM_UID) { 8732 throw new SecurityException("killProcessesBelowForeground() only available to system"); 8733 } 8734 8735 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 8736 } 8737 killProcessesBelowAdj(int belowAdj, String reason)8738 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 8739 if (Binder.getCallingUid() != SYSTEM_UID) { 8740 throw new SecurityException("killProcessesBelowAdj() only available to system"); 8741 } 8742 8743 boolean killed = false; 8744 synchronized (this) { 8745 synchronized (mProcLock) { 8746 synchronized (mPidsSelfLocked) { 8747 final int size = mPidsSelfLocked.size(); 8748 for (int i = 0; i < size; i++) { 8749 final int pid = mPidsSelfLocked.keyAt(i); 8750 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 8751 if (proc == null) continue; 8752 8753 final int adj = proc.mState.getSetAdj(); 8754 if (adj > belowAdj && !proc.isKilledByAm()) { 8755 proc.killLocked(reason, ApplicationExitInfo.REASON_PERMISSION_CHANGE, 8756 true); 8757 killed = true; 8758 } 8759 } 8760 } 8761 } 8762 } 8763 return killed; 8764 } 8765 8766 /** 8767 * Similar to {@link #killPids} but killing will be delayed until the device is idle 8768 * and the given process is imperceptible. 8769 */ 8770 @Override killProcessesWhenImperceptible(int[] pids, String reason)8771 public void killProcessesWhenImperceptible(int[] pids, String reason) { 8772 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 8773 != PackageManager.PERMISSION_GRANTED) { 8774 throw new SecurityException("Requires permission " 8775 + android.Manifest.permission.FORCE_STOP_PACKAGES); 8776 } 8777 int callerUid = Binder.getCallingUid(); 8778 final long iden = Binder.clearCallingIdentity(); 8779 try { 8780 mProcessList.killProcessesWhenImperceptible(pids, reason, callerUid); 8781 } finally { 8782 Binder.restoreCallingIdentity(iden); 8783 } 8784 } 8785 8786 @Override hang(final IBinder who, boolean allowRestart)8787 public void hang(final IBinder who, boolean allowRestart) { 8788 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8789 != PackageManager.PERMISSION_GRANTED) { 8790 throw new SecurityException("Requires permission " 8791 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8792 } 8793 8794 final IBinder.DeathRecipient death = new DeathRecipient() { 8795 @Override 8796 public void binderDied() { 8797 synchronized (this) { 8798 notifyAll(); 8799 } 8800 } 8801 }; 8802 8803 try { 8804 who.linkToDeath(death, 0); 8805 } catch (RemoteException e) { 8806 Slog.w(TAG, "hang: given caller IBinder is already dead."); 8807 return; 8808 } 8809 8810 synchronized (this) { 8811 Watchdog.getInstance().setAllowRestart(allowRestart); 8812 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 8813 synchronized (death) { 8814 while (who.isBinderAlive()) { 8815 try { 8816 death.wait(); 8817 } catch (InterruptedException e) { 8818 } 8819 } 8820 } 8821 Watchdog.getInstance().setAllowRestart(true); 8822 } 8823 } 8824 8825 @Override restart()8826 public void restart() { 8827 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8828 != PackageManager.PERMISSION_GRANTED) { 8829 throw new SecurityException("Requires permission " 8830 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8831 } 8832 8833 Log.i(TAG, "Sending shutdown broadcast..."); 8834 8835 BroadcastReceiver br = new BroadcastReceiver() { 8836 @Override public void onReceive(Context context, Intent intent) { 8837 // Now the broadcast is done, finish up the low-level shutdown. 8838 Log.i(TAG, "Shutting down activity manager..."); 8839 shutdown(10000); 8840 Log.i(TAG, "Shutdown complete, restarting!"); 8841 killProcess(myPid()); 8842 System.exit(10); 8843 } 8844 }; 8845 8846 // First send the high-level shut down broadcast. 8847 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 8848 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8849 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 8850 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 8851 mContext.sendOrderedBroadcastAsUser(intent, 8852 UserHandle.ALL, null, br, mHandler, 0, null, null); 8853 */ 8854 br.onReceive(mContext, intent); 8855 } 8856 8857 @Override performIdleMaintenance()8858 public void performIdleMaintenance() { 8859 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8860 != PackageManager.PERMISSION_GRANTED) { 8861 throw new SecurityException("Requires permission " 8862 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8863 } 8864 8865 synchronized (mProcLock) { 8866 final long now = SystemClock.uptimeMillis(); 8867 final long timeSinceLastIdle = now - mLastIdleTime; 8868 8869 if (!disableSystemCompaction()) { 8870 // Compact all non-zygote processes to freshen up the page cache. 8871 mOomAdjuster.mCachedAppOptimizer.compactAllSystem(); 8872 } 8873 8874 final long lowRamSinceLastIdle = mAppProfiler.getLowRamTimeSinceIdleLPr(now); 8875 mLastIdleTime = now; 8876 mAppProfiler.updateLowRamTimestampLPr(now); 8877 8878 StringBuilder sb = new StringBuilder(128); 8879 sb.append("Idle maintenance over "); 8880 TimeUtils.formatDuration(timeSinceLastIdle, sb); 8881 sb.append(" low RAM for "); 8882 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 8883 Slog.i(TAG, sb.toString()); 8884 8885 // If at least 1/3 of our time since the last idle period has been spent 8886 // with RAM low, then we want to kill processes. 8887 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 8888 // If the processes' memory has increased by more than 1% of the total memory, 8889 // or 10 MB, whichever is greater, then the processes' are eligible to be killed. 8890 final long totalMemoryInKb = getTotalMemory() / 1000; 8891 8892 // This threshold should be applicable to both PSS and RSS because the value is absolute 8893 // and represents an increase in process memory relative to its own previous state. 8894 // 8895 // TODO(b/296454553): Tune this value during the flag rollout process if more processes 8896 // seem to be getting killed than before. 8897 final long memoryGrowthThreshold = 8898 Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD); 8899 mProcessList.forEachLruProcessesLOSP(false, proc -> { 8900 if (proc.getThread() == null) { 8901 return; 8902 } 8903 final ProcessProfileRecord pr = proc.mProfile; 8904 final ProcessStateRecord state = proc.mState; 8905 final int setProcState = state.getSetProcState(); 8906 if (state.isNotCachedSinceIdle()) { 8907 if (setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE 8908 && setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 8909 final long initialIdlePssOrRss, lastPssOrRss, lastSwapPss; 8910 synchronized (mAppProfiler.mProfilerLock) { 8911 initialIdlePssOrRss = pr.getInitialIdlePssOrRss(); 8912 lastPssOrRss = mAppProfiler.isProfilingPss() 8913 ? pr.getLastPss() : pr.getLastRss(); 8914 lastSwapPss = pr.getLastSwapPss(); 8915 } 8916 if (doKilling && initialIdlePssOrRss != 0 8917 && lastPssOrRss > (initialIdlePssOrRss * 3 / 2) 8918 && lastPssOrRss > (initialIdlePssOrRss + memoryGrowthThreshold)) { 8919 final StringBuilder sb2 = new StringBuilder(128); 8920 sb2.append("Kill"); 8921 sb2.append(proc.processName); 8922 if (mAppProfiler.isProfilingPss()) { 8923 sb2.append(" in idle maint: pss="); 8924 } else { 8925 sb2.append(" in idle maint: rss="); 8926 } 8927 sb2.append(lastPssOrRss); 8928 8929 if (mAppProfiler.isProfilingPss()) { 8930 sb2.append(", swapPss="); 8931 sb2.append(lastSwapPss); 8932 sb2.append(", initialPss="); 8933 } else { 8934 sb2.append(", initialRss="); 8935 } 8936 sb2.append(initialIdlePssOrRss); 8937 sb2.append(", period="); 8938 TimeUtils.formatDuration(timeSinceLastIdle, sb2); 8939 sb2.append(", lowRamPeriod="); 8940 TimeUtils.formatDuration(lowRamSinceLastIdle, sb2); 8941 Slog.wtfQuiet(TAG, sb2.toString()); 8942 mHandler.post(() -> { 8943 synchronized (ActivityManagerService.this) { 8944 proc.killLocked(mAppProfiler.isProfilingPss() 8945 ? "idle maint (pss " : "idle maint (rss " + lastPssOrRss 8946 + " from " + initialIdlePssOrRss + ")", 8947 ApplicationExitInfo.REASON_OTHER, 8948 ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE, 8949 true); 8950 } 8951 }); 8952 } 8953 } 8954 } else if (setProcState < ActivityManager.PROCESS_STATE_HOME 8955 && setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) { 8956 state.setNotCachedSinceIdle(true); 8957 synchronized (mAppProfiler.mProfilerLock) { 8958 pr.setInitialIdlePssOrRss(0); 8959 mAppProfiler.updateNextPssTimeLPf( 8960 state.getSetProcState(), proc.mProfile, now, true); 8961 } 8962 } 8963 }); 8964 } 8965 } 8966 8967 @Override sendIdleJobTrigger()8968 public void sendIdleJobTrigger() { 8969 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8970 != PackageManager.PERMISSION_GRANTED) { 8971 throw new SecurityException("Requires permission " 8972 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8973 } 8974 8975 final long ident = Binder.clearCallingIdentity(); 8976 try { 8977 Intent intent = new Intent(ACTION_TRIGGER_IDLE) 8978 .setPackage("android") 8979 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 8980 broadcastIntent(null, intent, null, null, 0, null, null, null, 8981 OP_NONE, null, false, false, UserHandle.USER_ALL); 8982 } finally { 8983 Binder.restoreCallingIdentity(ident); 8984 } 8985 } 8986 retrieveSettings()8987 private void retrieveSettings() { 8988 final ContentResolver resolver = mContext.getContentResolver(); 8989 mActivityTaskManager.retrieveSettings(resolver); 8990 8991 final String debugApp = Settings.Global.getString(resolver, DEBUG_APP); 8992 final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0; 8993 final boolean alwaysFinishActivities = 8994 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0; 8995 mHiddenApiBlacklist.registerObserver(); 8996 mPlatformCompat.registerContentObserver(); 8997 8998 mAppProfiler.retrieveSettings(); 8999 9000 final Resources res; 9001 synchronized (this) { 9002 mDebugApp = mOrigDebugApp = debugApp; 9003 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 9004 mAlwaysFinishActivities = alwaysFinishActivities; 9005 // Load resources only after the current configuration has been set. 9006 res = mContext.getResources(); 9007 final boolean userSwitchUiEnabled = !res.getBoolean( 9008 com.android.internal.R.bool.config_customUserSwitchUi); 9009 final int maxRunningUsers = res.getInteger( 9010 com.android.internal.R.integer.config_multiuserMaxRunningUsers); 9011 final boolean delayUserDataLocking = res.getBoolean( 9012 com.android.internal.R.bool.config_multiuserDelayUserDataLocking); 9013 final int backgroundUserScheduledStopTimeSecs = res.getInteger( 9014 com.android.internal.R.integer.config_backgroundUserScheduledStopTimeSecs); 9015 mUserController.setInitialConfig(userSwitchUiEnabled, maxRunningUsers, 9016 delayUserDataLocking, backgroundUserScheduledStopTimeSecs); 9017 } 9018 mAppErrors.loadAppsNotReportingCrashesFromConfig(res.getString( 9019 com.android.internal.R.string.config_appsNotReportingCrashes)); 9020 } 9021 9022 /** 9023 * Ready. Set. Go! 9024 */ systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t)9025 public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) { 9026 t.traceBegin("PhaseActivityManagerReady"); 9027 mSystemServiceManager.preSystemReady(); 9028 synchronized(this) { 9029 if (mSystemReady) { 9030 // If we're done calling all the receivers, run the next "boot phase" passed in 9031 // by the SystemServer 9032 if (goingCallback != null) { 9033 goingCallback.run(); 9034 } 9035 t.traceEnd(); // PhaseActivityManagerReady 9036 return; 9037 } 9038 9039 t.traceBegin("controllersReady"); 9040 mLocalDeviceIdleController = 9041 LocalServices.getService(DeviceIdleInternal.class); 9042 mActivityTaskManager.onSystemReady(); 9043 // Make sure we have the current profile info, since it is needed for security checks. 9044 mUserController.onSystemReady(); 9045 mAppOpsService.systemReady(); 9046 mProcessList.onSystemReady(); 9047 mAppRestrictionController.onSystemReady(); 9048 mSystemReady = true; 9049 t.traceEnd(); 9050 } 9051 9052 try { 9053 sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface( 9054 ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE)) 9055 .getSerial(); 9056 } catch (RemoteException e) {} 9057 9058 t.traceBegin("killProcesses"); 9059 ArrayList<ProcessRecord> procsToKill = null; 9060 synchronized(mPidsSelfLocked) { 9061 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 9062 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 9063 if (!isAllowedWhileBooting(proc.info)) { 9064 if (procsToKill == null) { 9065 procsToKill = new ArrayList<ProcessRecord>(); 9066 } 9067 procsToKill.add(proc); 9068 } 9069 } 9070 } 9071 9072 synchronized(this) { 9073 if (procsToKill != null) { 9074 for (int i = procsToKill.size() - 1; i >= 0; i--) { 9075 ProcessRecord proc = procsToKill.get(i); 9076 Slog.i(TAG, "Removing system update proc: " + proc); 9077 mProcessList.removeProcessLocked(proc, true, false, 9078 ApplicationExitInfo.REASON_OTHER, 9079 ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE, 9080 "system update done"); 9081 } 9082 } 9083 9084 // Now that we have cleaned up any update processes, we 9085 // are ready to start launching real processes and know that 9086 // we won't trample on them any more. 9087 mProcessesReady = true; 9088 } 9089 t.traceEnd(); // KillProcesses 9090 9091 Slog.i(TAG, "System now ready"); 9092 9093 EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis()); 9094 9095 t.traceBegin("updateTopComponentForFactoryTest"); 9096 mAtmInternal.updateTopComponentForFactoryTest(); 9097 t.traceEnd(); 9098 9099 t.traceBegin("registerActivityLaunchObserver"); 9100 mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver); 9101 t.traceEnd(); 9102 9103 t.traceBegin("watchDeviceProvisioning"); 9104 watchDeviceProvisioning(mContext); 9105 t.traceEnd(); 9106 9107 t.traceBegin("retrieveSettings"); 9108 retrieveSettings(); 9109 t.traceEnd(); 9110 9111 t.traceBegin("Ugm.onSystemReady"); 9112 mUgmInternal.onSystemReady(); 9113 t.traceEnd(); 9114 9115 t.traceBegin("updateForceBackgroundCheck"); 9116 final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class); 9117 if (pmi != null) { 9118 pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK, 9119 state -> updateForceBackgroundCheck(state.batterySaverEnabled)); 9120 updateForceBackgroundCheck( 9121 pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled); 9122 } else { 9123 Slog.wtf(TAG, "PowerManagerInternal not found."); 9124 } 9125 t.traceEnd(); 9126 9127 if (goingCallback != null) goingCallback.run(); 9128 9129 t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks 9130 // Check the current user here as a user can be started inside goingCallback.run() from 9131 // other system services. 9132 final int currentUserId = mUserController.getCurrentUserId(); 9133 Slog.i(TAG, "Current user:" + currentUserId); 9134 if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) { 9135 // User other than system user has started. Make sure that system user is already 9136 // started before switching user. 9137 throw new RuntimeException("System user not started while current user is:" 9138 + currentUserId); 9139 } 9140 t.traceEnd(); 9141 9142 t.traceBegin("ActivityManagerStartApps"); 9143 mBatteryStatsService.onSystemReady(); 9144 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 9145 Integer.toString(currentUserId), currentUserId); 9146 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 9147 Integer.toString(currentUserId), currentUserId); 9148 9149 // On Automotive / Headless System User Mode, at this point the system user has already been 9150 // started and unlocked, and some of the tasks we do here have already been done. So skip 9151 // those in that case. The duplicate system user start is guarded in SystemServiceManager. 9152 // TODO(b/266158156): this workaround shouldn't be necessary once we move the headless-user 9153 // start logic to UserManager-land. 9154 mUserController.onSystemUserStarting(); 9155 9156 synchronized (this) { 9157 // Only start up encryption-aware persistent apps; once user is 9158 // unlocked we'll come back around and start unaware apps 9159 t.traceBegin("startPersistentApps"); 9160 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE); 9161 t.traceEnd(); 9162 9163 // Start up initial activity. 9164 mBooting = true; 9165 // Enable home activity for system user, so that the system can always boot. We don't 9166 // do this when the system user is not setup since the setup wizard should be the one 9167 // to handle home activity in this case. 9168 if (SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) { 9169 t.traceBegin("enableHomeActivity"); 9170 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class); 9171 try { 9172 AppGlobals.getPackageManager().setComponentEnabledSetting(cName, 9173 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0, 9174 UserHandle.USER_SYSTEM, "am"); 9175 } catch (RemoteException e) { 9176 throw e.rethrowAsRuntimeException(); 9177 } 9178 t.traceEnd(); 9179 } 9180 9181 boolean isBootingSystemUser = currentUserId == UserHandle.USER_SYSTEM; 9182 9183 // Some systems - like automotive - will explicitly unlock system user then switch 9184 // to a secondary user. 9185 // TODO(b/266158156): this workaround shouldn't be necessary once we move 9186 // the headless-user start logic to UserManager-land. 9187 if (isBootingSystemUser && !UserManager.isHeadlessSystemUserMode()) { 9188 t.traceBegin("startHomeOnAllDisplays"); 9189 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady"); 9190 t.traceEnd(); 9191 } 9192 9193 mHandler.post(mAtmInternal::showSystemReadyErrorDialogsIfNeeded); 9194 9195 if (isBootingSystemUser) { 9196 // Need to send the broadcasts for the system user here because 9197 // UserController#startUserInternal will not send them for the system user starting, 9198 // It checks if the user state already exists, which is always the case for the 9199 // system user. 9200 t.traceBegin("sendUserStartBroadcast"); 9201 final int callingUid = Binder.getCallingUid(); 9202 final int callingPid = Binder.getCallingPid(); 9203 final long ident = Binder.clearCallingIdentity(); 9204 try { 9205 mUserController.sendUserStartedBroadcast( 9206 currentUserId, callingUid, callingPid); 9207 mUserController.sendUserStartingBroadcast( 9208 currentUserId, callingUid, callingPid); 9209 } catch (Throwable e) { 9210 Slog.wtf(TAG, "Failed sending first user broadcasts", e); 9211 } finally { 9212 Binder.restoreCallingIdentity(ident); 9213 } 9214 t.traceEnd(); 9215 } else { 9216 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user " 9217 + currentUserId); 9218 } 9219 9220 t.traceBegin("resumeTopActivities"); 9221 mAtmInternal.resumeTopActivities(false /* scheduleIdle */); 9222 t.traceEnd(); 9223 9224 if (isBootingSystemUser) { 9225 t.traceBegin("sendUserSwitchBroadcasts"); 9226 mUserController.sendUserSwitchBroadcasts(-1, currentUserId); 9227 t.traceEnd(); 9228 } 9229 9230 t.traceBegin("setBinderProxies"); 9231 BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK, 9232 BINDER_PROXY_LOW_WATERMARK, BINDER_PROXY_WARNING_WATERMARK); 9233 BinderInternal.nSetBinderProxyCountEnabled(true); 9234 BinderInternal.setBinderProxyCountCallback(new MyBinderProxyCountEventListener(), 9235 mHandler); 9236 t.traceEnd(); // setBinderProxies 9237 9238 t.traceEnd(); // ActivityManagerStartApps 9239 9240 // Load the component aliases. 9241 t.traceBegin("componentAlias"); 9242 mComponentAliasResolver.onSystemReady(mConstants.mEnableComponentAlias, 9243 mConstants.mComponentAliasOverrides); 9244 t.traceEnd(); // componentAlias 9245 9246 t.traceEnd(); // PhaseActivityManagerReady 9247 } 9248 } 9249 9250 private class MyBinderProxyCountEventListener implements BinderProxyCountEventListener { 9251 @Override onLimitReached(int uid)9252 public void onLimitReached(int uid) { 9253 // Spawn a new thread for the dump as it'll take long time. 9254 new Thread(() -> handleLimitReached(uid), "BinderProxy Dump: " + uid).start(); 9255 } 9256 handleLimitReached(int uid)9257 private void handleLimitReached(int uid) { 9258 Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid " 9259 + Process.myUid()); 9260 BinderProxy.dumpProxyDebugInfo(); 9261 CriticalEventLog.getInstance().logExcessiveBinderCalls(uid); 9262 if (uid == Process.SYSTEM_UID) { 9263 Slog.i(TAG, "Skipping kill (uid is SYSTEM)"); 9264 } else { 9265 killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid), 9266 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 9267 ApplicationExitInfo.SUBREASON_EXCESSIVE_BINDER_OBJECTS, 9268 "Too many Binders sent to SYSTEM"); 9269 // We need to run a GC here, because killing the processes involved 9270 // actually isn't guaranteed to free up the proxies; in fact, if the 9271 // GC doesn't run for a long time, we may even exceed the global 9272 // proxy limit for a process (20000), resulting in system_server itself 9273 // being killed. 9274 // Note that the GC here might not actually clean up all the proxies, 9275 // because the binder reference decrements will come in asynchronously; 9276 // but if new processes belonging to the UID keep adding proxies, we 9277 // will get another callback here, and run the GC again - this time 9278 // cleaning up the old proxies. 9279 VMRuntime.getRuntime().requestConcurrentGC(); 9280 } 9281 } 9282 9283 @Override onWarningThresholdReached(int uid)9284 public void onWarningThresholdReached(int uid) { 9285 if (Flags.logExcessiveBinderProxies()) { 9286 Slog.w(TAG, "Uid " + uid + " sent too many (" 9287 + BINDER_PROXY_WARNING_WATERMARK + ") Binders to uid " + Process.myUid()); 9288 FrameworkStatsLog.write( 9289 FrameworkStatsLog.EXCESSIVE_BINDER_PROXY_COUNT_REPORTED, 9290 uid); 9291 } 9292 } 9293 } 9294 watchDeviceProvisioning(Context context)9295 private void watchDeviceProvisioning(Context context) { 9296 // setting system property based on whether device is provisioned 9297 9298 if (isDeviceProvisioned(context)) { 9299 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 9300 } else { 9301 // watch for device provisioning change 9302 context.getContentResolver().registerContentObserver( 9303 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false, 9304 new ContentObserver(new Handler(Looper.getMainLooper())) { 9305 @Override 9306 public void onChange(boolean selfChange) { 9307 if (isDeviceProvisioned(context)) { 9308 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 9309 context.getContentResolver().unregisterContentObserver(this); 9310 } 9311 } 9312 }); 9313 } 9314 } 9315 isDeviceProvisioned(Context context)9316 private boolean isDeviceProvisioned(Context context) { 9317 return Settings.Global.getInt(context.getContentResolver(), 9318 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 9319 } 9320 startBroadcastObservers()9321 private void startBroadcastObservers() { 9322 mBroadcastQueue.start(mContext.getContentResolver()); 9323 } 9324 updateForceBackgroundCheck(boolean enabled)9325 private void updateForceBackgroundCheck(boolean enabled) { 9326 synchronized (this) { 9327 synchronized (mProcLock) { 9328 if (mForceBackgroundCheck != enabled) { 9329 mForceBackgroundCheck = enabled; 9330 9331 if (DEBUG_BACKGROUND_CHECK) { 9332 Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled")); 9333 } 9334 9335 if (mForceBackgroundCheck) { 9336 // Stop background services for idle UIDs. 9337 mProcessList.doStopUidForIdleUidsLocked(); 9338 } 9339 } 9340 } 9341 } 9342 } 9343 killAppAtUsersRequest(ProcessRecord app)9344 void killAppAtUsersRequest(ProcessRecord app) { 9345 synchronized (this) { 9346 mAppErrors.killAppAtUserRequestLocked(app); 9347 } 9348 } 9349 9350 /** 9351 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 9352 * The application process will exit immediately after this call returns. 9353 * @param app object of the crashing app, null for the system server 9354 * @param crashInfo describing the exception 9355 */ handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)9356 public void handleApplicationCrash(IBinder app, 9357 ApplicationErrorReport.ParcelableCrashInfo crashInfo) { 9358 ProcessRecord r = findAppProcess(app, "Crash"); 9359 final String processName = app == null ? "system_server" 9360 : (r == null ? "unknown" : r.processName); 9361 9362 handleApplicationCrashInner("crash", r, processName, crashInfo); 9363 } 9364 9365 /* Native crash reporting uses this inner version because it needs to be somewhat 9366 * decoupled from the AM-managed cleanup lifecycle 9367 */ handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)9368 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 9369 ApplicationErrorReport.CrashInfo crashInfo) { 9370 float loadingProgress = 1; 9371 IncrementalMetrics incrementalMetrics = null; 9372 // Obtain Incremental information if available 9373 if (r != null && r.info != null && r.info.packageName != null) { 9374 IncrementalStatesInfo incrementalStatesInfo = 9375 mPackageManagerInt.getIncrementalStatesInfo(r.info.packageName, SYSTEM_UID, 9376 r.userId); 9377 if (incrementalStatesInfo != null) { 9378 loadingProgress = incrementalStatesInfo.getProgress(); 9379 } 9380 final String codePath = r.info.getCodePath(); 9381 if (codePath != null && !codePath.isEmpty() 9382 && IncrementalManager.isIncrementalPath(codePath)) { 9383 // Report in the main log about the incremental package 9384 Slog.e(TAG, "App crashed on incremental package " + r.info.packageName 9385 + " which is " + ((int) (loadingProgress * 100)) + "% loaded."); 9386 final IBinder incrementalService = ServiceManager.getService( 9387 Context.INCREMENTAL_SERVICE); 9388 if (incrementalService != null) { 9389 final IncrementalManager incrementalManager = new IncrementalManager( 9390 IIncrementalService.Stub.asInterface(incrementalService)); 9391 incrementalMetrics = incrementalManager.getMetrics(codePath); 9392 } 9393 } 9394 } 9395 9396 boolean recoverable = eventType.equals("native_recoverable_crash"); 9397 9398 EventLogTags.writeAmCrash(Binder.getCallingPid(), 9399 UserHandle.getUserId(Binder.getCallingUid()), processName, 9400 r == null ? -1 : r.info.flags, 9401 crashInfo.exceptionClassName, 9402 crashInfo.exceptionMessage, 9403 crashInfo.throwFileName, 9404 crashInfo.throwLineNumber, 9405 recoverable ? 1 : 0); 9406 9407 int processClassEnum = processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER 9408 : (r != null) ? r.getProcessClassEnum() 9409 : ServerProtoEnums.ERROR_SOURCE_UNKNOWN; 9410 int uid = (r != null) ? r.uid : -1; 9411 int pid = (r != null) ? r.getPid() : -1; 9412 FrameworkStatsLog.write(FrameworkStatsLog.APP_CRASH_OCCURRED, 9413 uid, 9414 eventType, 9415 processName, 9416 pid, 9417 (r != null && r.info != null) ? r.info.packageName : "", 9418 (r != null && r.info != null) ? (r.info.isInstantApp() 9419 ? FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE 9420 : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE) 9421 : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE, 9422 r != null ? (r.isInterestingToUserLocked() 9423 ? FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND 9424 : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND) 9425 : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN, 9426 processClassEnum, 9427 incrementalMetrics != null /* isIncremental */, loadingProgress, 9428 incrementalMetrics != null ? incrementalMetrics.getMillisSinceOldestPendingRead() 9429 : -1, 9430 incrementalMetrics != null ? incrementalMetrics.getStorageHealthStatusCode() 9431 : -1, 9432 incrementalMetrics != null ? incrementalMetrics.getDataLoaderStatusCode() 9433 : -1, 9434 incrementalMetrics != null && incrementalMetrics.getReadLogsEnabled(), 9435 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastDataLoaderBind() 9436 : -1, 9437 incrementalMetrics != null ? incrementalMetrics.getDataLoaderBindDelayMillis() 9438 : -1, 9439 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReads() 9440 : -1, 9441 incrementalMetrics != null ? incrementalMetrics.getTotalFailedReads() 9442 : -1, 9443 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorUid() 9444 : -1, 9445 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastReadError() 9446 : -1, 9447 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorNumber() 9448 : 0, 9449 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReadsDurationMillis() 9450 : -1 9451 ); 9452 9453 if (eventType.equals("native_crash")) { 9454 CriticalEventLog.getInstance().logNativeCrash(processClassEnum, processName, uid, pid); 9455 } else if (eventType.equals("crash")) { 9456 CriticalEventLog.getInstance().logJavaCrash(crashInfo.exceptionClassName, 9457 processClassEnum, processName, uid, pid); 9458 } 9459 9460 final int relaunchReason = r == null ? RELAUNCH_REASON_NONE 9461 : r.getWindowProcessController().computeRelaunchReason(); 9462 final String relaunchReasonString = relaunchReasonToString(relaunchReason); 9463 if (crashInfo.crashTag == null) { 9464 crashInfo.crashTag = relaunchReasonString; 9465 } else { 9466 crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString; 9467 } 9468 9469 addErrorToDropBox( 9470 eventType, r, processName, null, null, null, null, null, null, crashInfo, 9471 new Float(loadingProgress), incrementalMetrics, null, null); 9472 9473 // For GWP-ASan recoverable crashes, don't make the app crash (the whole point of 9474 // 'recoverable' is that the app doesn't crash). Normally, for nonrecoreable native crashes, 9475 // debuggerd will terminate the process, but there's a backup where ActivityManager will 9476 // also kill it. Avoid that. 9477 if (recoverable) { 9478 mAppErrors.sendRecoverableCrashToAppExitInfo(r, crashInfo); 9479 } else { 9480 mAppErrors.crashApplication(r, crashInfo); 9481 } 9482 } 9483 handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)9484 public void handleApplicationStrictModeViolation( 9485 IBinder app, 9486 int penaltyMask, 9487 StrictMode.ViolationInfo info) { 9488 // We're okay if the ProcessRecord is missing; it probably means that 9489 // we're reporting a violation from the system process itself. 9490 final ProcessRecord r = findAppProcess(app, "StrictMode"); 9491 9492 if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) { 9493 Integer stackFingerprint = info.hashCode(); 9494 boolean logIt = true; 9495 synchronized (mAlreadyLoggedViolatedStacks) { 9496 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 9497 logIt = false; 9498 // TODO: sub-sample into EventLog for these, with 9499 // the info.durationMillis? Then we'd get 9500 // the relative pain numbers, without logging all 9501 // the stack traces repeatedly. We'd want to do 9502 // likewise in the client code, which also does 9503 // dup suppression, before the Binder call. 9504 } else { 9505 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 9506 mAlreadyLoggedViolatedStacks.clear(); 9507 } 9508 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 9509 } 9510 } 9511 if (logIt) { 9512 logStrictModeViolationToDropBox(r, info); 9513 } 9514 } 9515 9516 if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) { 9517 AppErrorResult result = new AppErrorResult(); 9518 final long origId = Binder.clearCallingIdentity(); 9519 try { 9520 Message msg = Message.obtain(); 9521 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG; 9522 HashMap<String, Object> data = new HashMap<String, Object>(); 9523 data.put("result", result); 9524 data.put("app", r); 9525 data.put("info", info); 9526 msg.obj = data; 9527 mUiHandler.sendMessage(msg); 9528 } finally { 9529 Binder.restoreCallingIdentity(origId); 9530 } 9531 int res = result.get(); 9532 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 9533 } 9534 } 9535 9536 /** 9537 * Register a callback to raise strict mode violations. 9538 * @param callback The binder used to communicate the violations. 9539 */ 9540 @Override registerStrictModeCallback(IBinder callback)9541 public synchronized void registerStrictModeCallback(IBinder callback) { 9542 int callingPid = Binder.getCallingPid(); 9543 mStrictModeCallbacks.put(callingPid, 9544 IUnsafeIntentStrictModeCallback.Stub.asInterface(callback)); 9545 try { 9546 callback.linkToDeath(() -> { 9547 synchronized (ActivityManagerService.this) { 9548 mStrictModeCallbacks.remove(callingPid); 9549 } 9550 }, 0); 9551 } catch (RemoteException e) { 9552 mStrictModeCallbacks.remove(callingPid); 9553 } 9554 } 9555 9556 // Depending on the policy in effect, there could be a bunch of 9557 // these in quick succession so we try to batch these together to 9558 // minimize disk writes, number of dropbox entries, and maximize 9559 // compression, by having more fewer, larger records. logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)9560 private void logStrictModeViolationToDropBox( 9561 ProcessRecord process, 9562 StrictMode.ViolationInfo info) { 9563 if (info == null) { 9564 return; 9565 } 9566 final boolean isSystemApp = process == null || 9567 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 9568 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 9569 final String processName = process != null && process.getPid() == MY_PID 9570 ? "system_server" 9571 : (process == null ? "unknown" : process.processName); 9572 final DropBoxManager dbox = (DropBoxManager) 9573 mContext.getSystemService(Context.DROPBOX_SERVICE); 9574 9575 // Exit early if the dropbox isn't configured to accept this report type. 9576 final String dropboxTag = processClass(process) + "_strictmode"; 9577 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 9578 9579 final StringBuilder sb = new StringBuilder(1024); 9580 synchronized (sb) { 9581 appendDropBoxProcessHeaders(process, processName, null, sb); 9582 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 9583 sb.append("System-App: ").append(isSystemApp).append("\n"); 9584 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 9585 if (info.violationNumThisLoop != 0) { 9586 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 9587 } 9588 if (info.numAnimationsRunning != 0) { 9589 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 9590 } 9591 if (info.broadcastIntentAction != null) { 9592 sb.append("Broadcast-Intent-Action: ") 9593 .append(info.broadcastIntentAction) 9594 .append("\n"); 9595 } 9596 if (info.durationMillis != -1) { 9597 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 9598 } 9599 if (info.numInstances != -1) { 9600 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 9601 } 9602 if (info.tags != null) { 9603 for (String tag : info.tags) { 9604 sb.append("Span-Tag: ").append(tag).append("\n"); 9605 } 9606 } 9607 sb.append("\n"); 9608 sb.append(info.getStackTrace()); 9609 sb.append("\n"); 9610 if (info.getViolationDetails() != null) { 9611 sb.append(info.getViolationDetails()); 9612 sb.append("\n"); 9613 } 9614 } 9615 9616 final String res = sb.toString(); 9617 IoThread.getHandler().post(() -> { 9618 dbox.addText(dropboxTag, res); 9619 }); 9620 } 9621 9622 /** 9623 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 9624 * @param app object of the crashing app, null for the system server 9625 * @param tag reported by the caller 9626 * @param system whether this wtf is coming from the system 9627 * @param crashInfo describing the context of the error 9628 * @return true if the process should exit immediately (WTF is fatal) 9629 */ 9630 @Override handleApplicationWtf(@ullable final IBinder app, @Nullable final String tag, boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)9631 public boolean handleApplicationWtf(@Nullable final IBinder app, @Nullable final String tag, 9632 boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, 9633 int immediateCallerPid) { 9634 final int callingUid = Binder.getCallingUid(); 9635 final int callingPid = Binder.getCallingPid(); 9636 9637 // Internal callers in RuntimeInit should always generate a crashInfo. 9638 Preconditions.checkNotNull(crashInfo); 9639 9640 // If this is coming from the system, we could very well have low-level 9641 // system locks held, so we want to do this all asynchronously. And we 9642 // never want this to become fatal, so there is that too. 9643 // 9644 // Note: "callingPid == Process.myPid())" wouldn't be reliable because even if the caller 9645 // is within the system server, if it calls Log.wtf() without clearning the calling 9646 // identity, callingPid would still be of a remote caller. So we explicltly pass the 9647 // process PID from the caller. 9648 if (system || (immediateCallerPid == Process.myPid())) { 9649 mHandler.post(new Runnable() { 9650 @Override public void run() { 9651 handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo); 9652 } 9653 }); 9654 return false; 9655 } 9656 9657 final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag, 9658 crashInfo); 9659 9660 final boolean isFatal = Build.IS_ENG || Settings.Global 9661 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0; 9662 final boolean isSystem = (r == null) || r.isPersistent(); 9663 9664 if (isFatal && !isSystem) { 9665 mAppErrors.crashApplication(r, crashInfo); 9666 return true; 9667 } else { 9668 return false; 9669 } 9670 } 9671 handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo)9672 ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, 9673 @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo) { 9674 final ProcessRecord r = findAppProcess(app, "WTF"); 9675 final String processName = app == null ? "system_server" 9676 : (r == null ? "unknown" : r.processName); 9677 9678 EventLogTags.writeAmWtf(UserHandle.getUserId(callingUid), callingPid, 9679 processName, r == null ? -1 : r.info.flags, tag, 9680 crashInfo == null ? "unknown" : crashInfo.exceptionMessage); 9681 9682 FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, callingUid, tag, processName, 9683 callingPid, (r != null) ? r.getProcessClassEnum() : 0); 9684 9685 addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo, 9686 null, null, null, null); 9687 9688 return r; 9689 } 9690 9691 /** 9692 * Schedule to handle any pending system_server WTFs. 9693 */ schedulePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)9694 public void schedulePendingSystemServerWtfs( 9695 final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) { 9696 mHandler.post(() -> handlePendingSystemServerWtfs(list)); 9697 } 9698 9699 /** 9700 * Handle any pending system_server WTFs, add into the dropbox 9701 */ handlePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)9702 private void handlePendingSystemServerWtfs( 9703 final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) { 9704 ProcessRecord proc; 9705 synchronized (mPidsSelfLocked) { 9706 proc = mPidsSelfLocked.get(MY_PID); 9707 } 9708 for (Pair<String, ApplicationErrorReport.CrashInfo> p = list.poll(); 9709 p != null; p = list.poll()) { 9710 addErrorToDropBox("wtf", proc, "system_server", null, null, null, p.first, null, null, 9711 p.second, null, null, null, null); 9712 } 9713 } 9714 9715 /** 9716 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 9717 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 9718 */ findAppProcess(IBinder app, String reason)9719 private ProcessRecord findAppProcess(IBinder app, String reason) { 9720 if (app == null) { 9721 return null; 9722 } 9723 9724 synchronized (mProcLock) { 9725 return mProcessList.findAppProcessLOSP(app, reason); 9726 } 9727 } 9728 9729 /** 9730 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 9731 * to append various headers to the dropbox log text. 9732 */ appendDropBoxProcessHeaders(ProcessRecord process, String processName, final VolatileDropboxEntryStates volatileStates, final StringBuilder sb)9733 void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 9734 final VolatileDropboxEntryStates volatileStates, final StringBuilder sb) { 9735 sb.append("SystemUptimeMs: ").append(SystemClock.uptimeMillis()).append("\n"); 9736 9737 // Watchdog thread ends up invoking this function (with 9738 // a null ProcessRecord) to add the stack file to dropbox. 9739 // Do not acquire a lock on this (am) in such cases, as it 9740 // could cause a potential deadlock, if and when watchdog 9741 // is invoked due to unavailability of lock on am and it 9742 // would prevent watchdog from killing system_server. 9743 if (process == null) { 9744 sb.append("Process: ").append(processName).append("\n"); 9745 return; 9746 } 9747 // Note: ProcessRecord 'process' is guarded by the service 9748 // instance. (notably process.pkgList, which could otherwise change 9749 // concurrently during execution of this method) 9750 synchronized (mProcLock) { 9751 sb.append("Process: ").append(processName).append("\n"); 9752 sb.append("PID: ").append(process.getPid()).append("\n"); 9753 sb.append("UID: ").append(process.uid).append("\n"); 9754 if (process.mOptRecord != null) { 9755 // Use 'isProcessFrozen' from 'volatileStates' if it'snon-null (present), 9756 // otherwise use 'isFrozen' from 'mOptRecord'. 9757 sb.append("Frozen: ").append( 9758 (volatileStates != null && volatileStates.isProcessFrozen() != null) 9759 ? volatileStates.isProcessFrozen() : process.mOptRecord.isFrozen() 9760 ).append("\n"); 9761 } 9762 if (volatileStates != null && volatileStates.getTimestamp() != null) { 9763 String formattedTime = DROPBOX_TIME_FORMATTER.format( 9764 volatileStates.getTimestamp()); 9765 sb.append("Timestamp: ").append(formattedTime).append("\n"); 9766 } 9767 int flags = process.info.flags; 9768 final IPackageManager pm = AppGlobals.getPackageManager(); 9769 sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n"); 9770 final int callingUserId = UserHandle.getCallingUserId(); 9771 process.getPkgList().forEachPackage(pkg -> { 9772 sb.append("Package: ").append(pkg); 9773 try { 9774 final PackageInfo pi = pm.getPackageInfo(pkg, 0, callingUserId); 9775 if (pi != null) { 9776 sb.append(" v").append(pi.getLongVersionCode()); 9777 if (pi.versionName != null) { 9778 sb.append(" (").append(pi.versionName).append(")"); 9779 } 9780 } 9781 } catch (RemoteException e) { 9782 Slog.e(TAG, "Error getting package info: " + pkg, e); 9783 } 9784 sb.append("\n"); 9785 }); 9786 if (process.info.isInstantApp()) { 9787 sb.append("Instant-App: true\n"); 9788 } 9789 9790 if (process.isSdkSandbox) { 9791 final String clientPackage = process.sdkSandboxClientAppPackage; 9792 try { 9793 final PackageInfo pi = pm.getPackageInfo(clientPackage, 9794 PackageManager.GET_SHARED_LIBRARY_FILES, callingUserId); 9795 if (pi != null) { 9796 appendSdkSandboxClientPackageHeader(sb, pi); 9797 appendSdkSandboxLibraryHeaders(sb, pi); 9798 } else { 9799 Slog.e(TAG, 9800 "PackageInfo is null for SDK sandbox client: " + clientPackage); 9801 } 9802 } catch (RemoteException e) { 9803 Slog.e(TAG, 9804 "Error getting package info for SDK sandbox client: " + clientPackage, 9805 e); 9806 } 9807 sb.append("SdkSandbox: true\n"); 9808 } 9809 } 9810 } 9811 appendSdkSandboxClientPackageHeader(StringBuilder sb, PackageInfo clientPackageInfo)9812 private void appendSdkSandboxClientPackageHeader(StringBuilder sb, 9813 PackageInfo clientPackageInfo) { 9814 sb.append("SdkSandbox-Client-Package: ").append(clientPackageInfo.packageName); 9815 sb.append(" v").append(clientPackageInfo.getLongVersionCode()); 9816 if (clientPackageInfo.versionName != null) { 9817 sb.append(" (").append(clientPackageInfo.versionName).append(")"); 9818 } 9819 sb.append("\n"); 9820 } 9821 appendSdkSandboxLibraryHeaders(StringBuilder sb, PackageInfo clientPackageInfo)9822 private void appendSdkSandboxLibraryHeaders(StringBuilder sb, 9823 PackageInfo clientPackageInfo) { 9824 final ApplicationInfo info = clientPackageInfo.applicationInfo; 9825 final List<SharedLibraryInfo> sharedLibraries = info.getSharedLibraryInfos(); 9826 for (int j = 0, size = sharedLibraries.size(); j < size; j++) { 9827 final SharedLibraryInfo sharedLibrary = sharedLibraries.get(j); 9828 if (!sharedLibrary.isSdk()) { 9829 continue; 9830 } 9831 9832 sb.append("SdkSandbox-Library: ").append(sharedLibrary.getPackageName()); 9833 final VersionedPackage versionedPackage = sharedLibrary.getDeclaringPackage(); 9834 sb.append(" v").append(versionedPackage.getLongVersionCode()); 9835 sb.append("\n"); 9836 } 9837 } 9838 processClass(ProcessRecord process)9839 private static String processClass(ProcessRecord process) { 9840 if (process == null || process.getPid() == MY_PID) { 9841 return "system_server"; 9842 } else if (process.info.isSystemApp() || process.info.isSystemExt()) { 9843 return "system_app"; 9844 } else { 9845 return "data_app"; 9846 } 9847 } 9848 9849 private final DropboxRateLimiter mDropboxRateLimiter = new DropboxRateLimiter(); 9850 9851 /** Initializes the Dropbox Rate Limiter parameters from flags. */ initDropboxRateLimiter()9852 public void initDropboxRateLimiter() { 9853 mDropboxRateLimiter.init(); 9854 } 9855 9856 /** 9857 * Write a description of an error (crash, WTF, ANR) to the drop box. 9858 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 9859 * @param process which caused the error, null means the system server 9860 * @param activityShortComponentName which triggered the error, null if unknown 9861 * @param parentShortComponentName activity related to the error, null if unknown 9862 * @param parentProcess parent process 9863 * @param subject line related to the error, null if absent 9864 * @param report in long form describing the error, null if absent 9865 * @param dataFile text file to include in the report, null if none 9866 * @param crashInfo giving an application stack trace, null if absent 9867 * @param loadingProgress the loading progress of an installed package, range in [0, 1]. 9868 * @param incrementalMetrics metrics for apps installed on Incremental. 9869 * @param errorId a unique id to append to the dropbox headers. 9870 */ 9871 @SuppressWarnings("DoNotCall") // Ignore warning for synchronous to call to worker.run() 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, @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics, @Nullable UUID errorId, @Nullable VolatileDropboxEntryStates volatileStates)9872 public void addErrorToDropBox(String eventType, 9873 ProcessRecord process, String processName, String activityShortComponentName, 9874 String parentShortComponentName, ProcessRecord parentProcess, 9875 String subject, final String report, final File dataFile, 9876 final ApplicationErrorReport.CrashInfo crashInfo, 9877 @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics, 9878 @Nullable UUID errorId, @Nullable VolatileDropboxEntryStates volatileStates) { 9879 // NOTE -- this must never acquire the ActivityManagerService lock, 9880 // otherwise the watchdog may be prevented from resetting the system. 9881 9882 // Bail early if not published yet 9883 final DropBoxManager dbox; 9884 try { 9885 dbox = mContext.getSystemService(DropBoxManager.class); 9886 } catch (Exception e) { 9887 return; 9888 } 9889 9890 // Exit early if the dropbox isn't configured to accept this report type. 9891 final String dropboxTag = processClass(process) + "_" + eventType; 9892 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 9893 9894 // Check if we should rate limit and abort early if needed. 9895 final DropboxRateLimiter.RateLimitResult rateLimitResult = 9896 mDropboxRateLimiter.shouldRateLimit(eventType, processName); 9897 if (rateLimitResult.shouldRateLimit()) return; 9898 9899 final StringBuilder sb = new StringBuilder(1024); 9900 appendDropBoxProcessHeaders(process, processName, volatileStates, sb); 9901 if (process != null) { 9902 sb.append("Foreground: ") 9903 .append(process.isInterestingToUserLocked() ? "Yes" : "No") 9904 .append("\n"); 9905 if (process.getStartUptime() > 0) { 9906 long runtimeMillis = SystemClock.uptimeMillis() - process.getStartUptime(); 9907 sb.append("Process-Runtime: ").append(runtimeMillis).append("\n"); 9908 } 9909 } 9910 if (eventType.equals("crash")) { 9911 String formattedTime = DROPBOX_TIME_FORMATTER.format( 9912 Instant.now().atZone(ZoneId.systemDefault())); 9913 sb.append("Timestamp: ").append(formattedTime).append("\n"); 9914 } 9915 if (activityShortComponentName != null) { 9916 sb.append("Activity: ").append(activityShortComponentName).append("\n"); 9917 } 9918 if (parentShortComponentName != null) { 9919 if (parentProcess != null && parentProcess.getPid() != process.getPid()) { 9920 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n"); 9921 } 9922 if (!parentShortComponentName.equals(activityShortComponentName)) { 9923 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n"); 9924 } 9925 } 9926 if (subject != null) { 9927 sb.append("Subject: ").append(subject).append("\n"); 9928 } 9929 if (errorId != null) { 9930 sb.append("ErrorId: ").append(errorId.toString()).append("\n"); 9931 } 9932 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 9933 9934 // If device is not using 4KB pages, add the PageSize 9935 long pageSize = Os.sysconf(OsConstants._SC_PAGESIZE); 9936 if (pageSize != 4096) { 9937 sb.append("PageSize: ").append(pageSize).append("\n"); 9938 } 9939 9940 if (Debug.isDebuggerConnected()) { 9941 sb.append("Debugger: Connected\n"); 9942 } 9943 if (crashInfo != null && crashInfo.exceptionHandlerClassName != null 9944 && !crashInfo.exceptionHandlerClassName.isEmpty()) { 9945 sb.append("Crash-Handler: ").append(crashInfo.exceptionHandlerClassName).append("\n"); 9946 } 9947 if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) { 9948 sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n"); 9949 } 9950 if (loadingProgress != null) { 9951 sb.append("Loading-Progress: ").append(loadingProgress.floatValue()).append("\n"); 9952 } 9953 if (incrementalMetrics != null) { 9954 sb.append("Incremental: Yes").append("\n"); 9955 final long millisSinceOldestPendingRead = 9956 incrementalMetrics.getMillisSinceOldestPendingRead(); 9957 if (millisSinceOldestPendingRead > 0) { 9958 sb.append("Millis-Since-Oldest-Pending-Read: ").append( 9959 millisSinceOldestPendingRead).append("\n"); 9960 } 9961 } 9962 sb.append(rateLimitResult.createHeader()); 9963 sb.append("\n"); 9964 9965 // Do the rest in a worker thread to avoid blocking the caller on I/O 9966 // (After this point, we shouldn't access AMS internal data structures.) 9967 // 9968 // If process is null, we are being called from some internal code 9969 // and may be about to die -- run this synchronously. 9970 final boolean runSynchronously = process == null; 9971 Thread worker = new Thread("Error dump: " + dropboxTag) { 9972 @Override 9973 public void run() { 9974 if (report != null) { 9975 sb.append(report); 9976 } 9977 9978 String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 9979 String kerLogSetting = Settings.Global.ERROR_KERNEL_LOG_PREFIX + dropboxTag; 9980 String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag; 9981 int logcatLines = Build.IS_USER 9982 ? 0 9983 : Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0); 9984 int kernelLogLines = Build.IS_USER 9985 ? 0 9986 : Settings.Global.getInt(mContext.getContentResolver(), kerLogSetting, 0); 9987 int dropboxMaxSize = Settings.Global.getInt( 9988 mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE); 9989 9990 if (dataFile != null) { 9991 // Attach the stack traces file to the report so collectors can load them 9992 // by file if they have access. 9993 sb.append(DATA_FILE_PATH_HEADER) 9994 .append(dataFile.getAbsolutePath()).append('\n'); 9995 9996 int maxDataFileSize = dropboxMaxSize 9997 - sb.length() 9998 - logcatLines * RESERVED_BYTES_PER_LOGCAT_LINE 9999 - kernelLogLines * RESERVED_BYTES_PER_LOGCAT_LINE 10000 - DATA_FILE_PATH_FOOTER.length(); 10001 10002 if (maxDataFileSize > 0) { 10003 // Inline dataFile contents if there is room. 10004 try { 10005 sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize, 10006 "\n\n[[TRUNCATED]]\n")); 10007 } catch (IOException e) { 10008 Slog.e(TAG, "Error reading " + dataFile, e); 10009 } 10010 } 10011 // Always append the footer, even there wasn't enough space to inline the 10012 // dataFile contents. 10013 sb.append(DATA_FILE_PATH_FOOTER); 10014 } 10015 10016 if (crashInfo != null && crashInfo.stackTrace != null) { 10017 sb.append(crashInfo.stackTrace); 10018 } 10019 boolean shouldAddLogs = logcatLines > 0 || kernelLogLines > 0; 10020 if (!runSynchronously && shouldAddLogs) { 10021 sb.append("\n"); 10022 if (logcatLines > 0) { 10023 fetchLogcatBuffers(sb, logcatLines, LOGCAT_TIMEOUT_SEC, 10024 List.of("events", "system", "main", "crash")); 10025 } 10026 if (kernelLogLines > 0) { 10027 fetchLogcatBuffers(sb, kernelLogLines, LOGCAT_TIMEOUT_SEC / 2, 10028 List.of("kernel")); 10029 } 10030 } 10031 10032 dbox.addText(dropboxTag, sb.toString()); 10033 } 10034 }; 10035 10036 if (runSynchronously) { 10037 final int oldMask = StrictMode.allowThreadDiskWritesMask(); 10038 try { 10039 worker.run(); 10040 } finally { 10041 StrictMode.setThreadPolicyMask(oldMask); 10042 } 10043 } else { 10044 worker.start(); 10045 if (process != null && process.mPid == MY_PID && "crash".equals(eventType)) { 10046 // We're actually crashing, let's wait for up to 2 seconds before killing ourselves, 10047 // so the data could be persisted into the dropbox. 10048 try { 10049 worker.join(2000); 10050 } catch (InterruptedException ignored) { 10051 } 10052 } 10053 } 10054 } 10055 10056 @Override getProcessesInErrorState()10057 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 10058 enforceNotIsolatedCaller("getProcessesInErrorState"); 10059 // assume our apps are happy - lazy create the list 10060 final List<ActivityManager.ProcessErrorStateInfo>[] errList = new List[1]; 10061 10062 final int callingUid = Binder.getCallingUid(); 10063 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 10064 callingUid) == PackageManager.PERMISSION_GRANTED; 10065 int userId = UserHandle.getUserId(callingUid); 10066 10067 final boolean hasDumpPermission = ActivityManager.checkUidPermission( 10068 android.Manifest.permission.DUMP, callingUid) == PackageManager.PERMISSION_GRANTED; 10069 10070 synchronized (mProcLock) { 10071 // iterate across all processes 10072 mProcessList.forEachLruProcessesLOSP(false, app -> { 10073 if (!allUsers && app.userId != userId) { 10074 return; 10075 } 10076 if (!hasDumpPermission && app.info.uid != callingUid) { 10077 return; 10078 } 10079 final ProcessErrorStateRecord errState = app.mErrorState; 10080 final boolean crashing = errState.isCrashing(); 10081 final boolean notResponding = errState.isNotResponding(); 10082 if ((app.getThread() != null) && (crashing || notResponding)) { 10083 // This one's in trouble, so we'll generate a report for it 10084 // crashes are higher priority (in case there's a crash *and* an anr) 10085 ActivityManager.ProcessErrorStateInfo report = null; 10086 if (crashing) { 10087 report = errState.getCrashingReport(); 10088 } else if (notResponding) { 10089 report = errState.getNotRespondingReport(); 10090 } 10091 10092 if (report != null) { 10093 if (errList[0] == null) { 10094 errList[0] = new ArrayList<>(1); 10095 } 10096 errList[0].add(report); 10097 } else { 10098 Slog.w(TAG, "Missing app error report, app = " + app.processName + 10099 " crashing = " + crashing + 10100 " notResponding = " + notResponding); 10101 } 10102 } 10103 }); 10104 } 10105 10106 return errList[0]; 10107 } 10108 10109 @Override getRunningAppProcesses()10110 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 10111 enforceNotIsolatedCaller("getRunningAppProcesses"); 10112 10113 final int callingUid = Binder.getCallingUid(); 10114 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 10115 10116 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 10117 callingUid) == PackageManager.PERMISSION_GRANTED; 10118 final int userId = UserHandle.getUserId(callingUid); 10119 final boolean allUids = mAtmInternal.isGetTasksAllowed( 10120 "getRunningAppProcesses", Binder.getCallingPid(), callingUid); 10121 10122 synchronized (mProcLock) { 10123 // Iterate across all processes 10124 return mProcessList.getRunningAppProcessesLOSP(allUsers, userId, allUids, 10125 callingUid, clientTargetSdk); 10126 } 10127 } 10128 10129 @Override getRunningExternalApplications()10130 public List<ApplicationInfo> getRunningExternalApplications() { 10131 enforceNotIsolatedCaller("getRunningExternalApplications"); 10132 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 10133 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 10134 if (runningApps != null && runningApps.size() > 0) { 10135 Set<String> extList = new HashSet<String>(); 10136 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 10137 if (app.pkgList != null) { 10138 for (String pkg : app.pkgList) { 10139 extList.add(pkg); 10140 } 10141 } 10142 } 10143 IPackageManager pm = AppGlobals.getPackageManager(); 10144 for (String pkg : extList) { 10145 try { 10146 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 10147 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 10148 retList.add(info); 10149 } 10150 } catch (RemoteException e) { 10151 } 10152 } 10153 } 10154 return retList; 10155 } 10156 10157 @Override getHistoricalProcessStartReasons( String packageName, int maxNum, int userId)10158 public ParceledListSlice<ApplicationStartInfo> getHistoricalProcessStartReasons( 10159 String packageName, int maxNum, int userId) { 10160 enforceNotIsolatedCaller("getHistoricalProcessStartReasons"); 10161 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10162 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10163 throw new IllegalArgumentException("Unsupported userId"); 10164 } 10165 10166 final int callingPid = Binder.getCallingPid(); 10167 final int callingUid = Binder.getCallingUid(); 10168 mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL, 10169 "getHistoricalProcessStartReasons", null); 10170 10171 final ArrayList<ApplicationStartInfo> results = new ArrayList<ApplicationStartInfo>(); 10172 if (!TextUtils.isEmpty(packageName)) { 10173 final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid, 10174 "getHistoricalProcessStartReasons"); 10175 if (uid != INVALID_UID) { 10176 mProcessList.getAppStartInfoTracker().getStartInfo( 10177 packageName, uid, callingPid, maxNum, results); 10178 } 10179 } else { 10180 // If no package name is given, use the caller's uid as the filter uid. 10181 mProcessList.getAppStartInfoTracker().getStartInfo( 10182 packageName, callingUid, callingPid, maxNum, results); 10183 } 10184 return new ParceledListSlice<ApplicationStartInfo>(results); 10185 } 10186 10187 10188 @Override addApplicationStartInfoCompleteListener( IApplicationStartInfoCompleteListener listener, int userId)10189 public void addApplicationStartInfoCompleteListener( 10190 IApplicationStartInfoCompleteListener listener, int userId) { 10191 enforceNotIsolatedCaller("setApplicationStartInfoCompleteListener"); 10192 10193 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10194 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10195 throw new IllegalArgumentException("Unsupported userId"); 10196 } 10197 10198 final int callingUid = Binder.getCallingUid(); 10199 mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, true, 10200 ALLOW_NON_FULL, "addApplicationStartInfoCompleteListener", null); 10201 10202 mProcessList.getAppStartInfoTracker().addStartInfoCompleteListener(listener, 10203 UserHandle.getUid(userId, UserHandle.getAppId(callingUid))); 10204 } 10205 10206 10207 @Override removeApplicationStartInfoCompleteListener( IApplicationStartInfoCompleteListener listener, int userId)10208 public void removeApplicationStartInfoCompleteListener( 10209 IApplicationStartInfoCompleteListener listener, int userId) { 10210 enforceNotIsolatedCaller("clearApplicationStartInfoCompleteListener"); 10211 10212 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10213 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10214 throw new IllegalArgumentException("Unsupported userId"); 10215 } 10216 10217 final int callingUid = Binder.getCallingUid(); 10218 mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, true, 10219 ALLOW_NON_FULL, "removeApplicationStartInfoCompleteListener", null); 10220 10221 mProcessList.getAppStartInfoTracker().removeStartInfoCompleteListener(listener, 10222 UserHandle.getUid(userId, UserHandle.getAppId(callingUid)), true); 10223 } 10224 10225 @Override addStartInfoTimestamp(int key, long timestampNs, int userId)10226 public void addStartInfoTimestamp(int key, long timestampNs, int userId) { 10227 enforceNotIsolatedCaller("addStartInfoTimestamp"); 10228 10229 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10230 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10231 throw new IllegalArgumentException("Unsupported userId"); 10232 } 10233 10234 final int callingUid = Binder.getCallingUid(); 10235 mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, true, 10236 ALLOW_NON_FULL, "addStartInfoTimestamp", null); 10237 10238 addStartInfoTimestampInternal(key, timestampNs, userId, callingUid); 10239 } 10240 10241 @Override reportStartInfoViewTimestamps(long renderThreadDrawStartTimeNs, long framePresentedTimeNs)10242 public void reportStartInfoViewTimestamps(long renderThreadDrawStartTimeNs, 10243 long framePresentedTimeNs) { 10244 int callingUid = Binder.getCallingUid(); 10245 int userId = UserHandle.getUserId(callingUid); 10246 addStartInfoTimestampInternal( 10247 ApplicationStartInfo.START_TIMESTAMP_INITIAL_RENDERTHREAD_FRAME, 10248 renderThreadDrawStartTimeNs, userId, callingUid); 10249 addStartInfoTimestampInternal( 10250 ApplicationStartInfo.START_TIMESTAMP_SURFACEFLINGER_COMPOSITION_COMPLETE, 10251 framePresentedTimeNs, userId, callingUid); 10252 } 10253 addStartInfoTimestampInternal(int key, long timestampNs, int userId, int uid)10254 private void addStartInfoTimestampInternal(int key, long timestampNs, int userId, int uid) { 10255 mProcessList.getAppStartInfoTracker().addTimestampToStart( 10256 Settings.getPackageNameForUid(mContext, uid), 10257 UserHandle.getUid(userId, UserHandle.getAppId(uid)), 10258 timestampNs, 10259 key); 10260 } 10261 10262 @Override getHistoricalProcessExitReasons( String packageName, int pid, int maxNum, int userId)10263 public ParceledListSlice<ApplicationExitInfo> getHistoricalProcessExitReasons( 10264 String packageName, int pid, int maxNum, int userId) { 10265 enforceNotIsolatedCaller("getHistoricalProcessExitReasons"); 10266 10267 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10268 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10269 throw new IllegalArgumentException("Unsupported userId"); 10270 } 10271 10272 final int callingPid = Binder.getCallingPid(); 10273 final int callingUid = Binder.getCallingUid(); 10274 final int callingUserId = UserHandle.getCallingUserId(); 10275 mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL, 10276 "getHistoricalProcessExitReasons", null); 10277 10278 NativeTombstoneManager tombstoneService = LocalServices.getService( 10279 NativeTombstoneManager.class); 10280 10281 final ArrayList<ApplicationExitInfo> results = new ArrayList<ApplicationExitInfo>(); 10282 if (!TextUtils.isEmpty(packageName)) { 10283 final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid, 10284 "getHistoricalProcessExitReasons"); 10285 if (uid != INVALID_UID) { 10286 mProcessList.mAppExitInfoTracker.getExitInfo( 10287 packageName, uid, pid, maxNum, results); 10288 tombstoneService.collectTombstones(results, uid, pid, maxNum); 10289 } 10290 } else { 10291 // If no package name is given, use the caller's uid as the filter uid. 10292 mProcessList.mAppExitInfoTracker.getExitInfo( 10293 packageName, callingUid, pid, maxNum, results); 10294 tombstoneService.collectTombstones(results, callingUid, pid, maxNum); 10295 } 10296 10297 return new ParceledListSlice<ApplicationExitInfo>(results); 10298 } 10299 10300 @Override setProcessStateSummary(@ullable byte[] state)10301 public void setProcessStateSummary(@Nullable byte[] state) { 10302 if (state != null && state.length > MAX_STATE_DATA_SIZE) { 10303 throw new IllegalArgumentException("Data size is too large"); 10304 } 10305 mProcessList.mAppExitInfoTracker.setProcessStateSummary(Binder.getCallingUid(), 10306 Binder.getCallingPid(), state); 10307 } 10308 10309 /** 10310 * Retrieves logs from specified logcat buffers and appends them to a StringBuilder 10311 * in the supplied order. The method executes a logcat command to fetch specific 10312 * log entries from the supplied buffers. 10313 * 10314 * @param sb the StringBuilder to append the logcat output to. 10315 * @param lines the number of lines to retrieve. 10316 * @param timeout the maximum allowed time in seconds for logcat to run before being terminated. 10317 * @param buffers the list of log buffers from which to retrieve logs. 10318 */ fetchLogcatBuffers(StringBuilder sb, int lines, int timeout, List<String> buffers)10319 private static void fetchLogcatBuffers(StringBuilder sb, int lines, 10320 int timeout, List<String> buffers) { 10321 10322 if (buffers.size() == 0 || lines <= 0 || timeout <= 0) { 10323 return; 10324 } 10325 10326 List<String> command = new ArrayList<>(10 + (2 * buffers.size())); 10327 // Time out after 10s of inactivity, but kill logcat with SEGV 10328 // so we can investigate why it didn't finish. 10329 command.add("/system/bin/timeout"); 10330 command.add("-i"); 10331 command.add("-s"); 10332 command.add("SEGV"); 10333 command.add(timeout + "s"); 10334 10335 // Merge several logcat streams, and take the last N lines. 10336 command.add("/system/bin/logcat"); 10337 command.add("-v"); 10338 // This adds a timestamp and thread info to each log line. 10339 // Also change the timestamps to use UTC time. 10340 command.add("threadtime,UTC"); 10341 for (String buffer : buffers) { 10342 command.add("-b"); 10343 command.add(buffer); 10344 } 10345 // Limit the output to the last N lines. 10346 command.add("-t"); 10347 command.add(String.valueOf(lines)); 10348 10349 try { 10350 java.lang.Process proc = 10351 new ProcessBuilder(command).redirectErrorStream(true).start(); 10352 10353 // Close the output stream immediately as we do not send input to the process. 10354 try { 10355 proc.getOutputStream().close(); 10356 } catch (IOException e) { 10357 } 10358 10359 try (InputStreamReader reader = new InputStreamReader(proc.getInputStream())) { 10360 char[] buffer = new char[8192]; 10361 int numRead; 10362 while ((numRead = reader.read(buffer, 0, buffer.length)) > 0) { 10363 sb.append(buffer, 0, numRead); 10364 } 10365 } 10366 } catch (IOException e) { 10367 Slog.e(TAG, "Error running logcat", e); 10368 } 10369 } 10370 10371 /** 10372 * Check if the calling process has the permission to dump given package, 10373 * throw SecurityException if it doesn't have the permission. 10374 * 10375 * @return The real UID of process that can be dumped, or {@link android.os.Process#INVALID_UID} 10376 * if the package is not found. 10377 */ enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, String function)10378 int enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, 10379 String function) { 10380 // Allow SDK sandbox process to dump for its own process (under SDK sandbox package) 10381 try { 10382 if (Process.isSdkSandboxUid(callingUid) 10383 && getPackageManager().getSdkSandboxPackageName().equals(packageName)) { 10384 return callingUid; 10385 } 10386 } catch (RemoteException e) { 10387 Log.e(TAG, "Could not get SDK sandbox package name"); 10388 } 10389 final long identity = Binder.clearCallingIdentity(); 10390 int uid = INVALID_UID; 10391 try { 10392 uid = mPackageManagerInt.getPackageUid(packageName, 10393 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId); 10394 } finally { 10395 Binder.restoreCallingIdentity(identity); 10396 } 10397 // If the uid is Process.INVALID_UID, the below 'if' check will be always true 10398 if (UserHandle.getAppId(uid) != UserHandle.getAppId(callingUid)) { 10399 // Requires the DUMP permission if the target package doesn't belong 10400 // to the caller or it doesn't exist. 10401 enforceCallingPermission(android.Manifest.permission.DUMP, function); 10402 } 10403 return uid; 10404 } 10405 10406 @Override getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)10407 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) { 10408 if (outState == null) { 10409 throw new IllegalArgumentException("outState is null"); 10410 } 10411 enforceNotIsolatedCaller("getMyMemoryState"); 10412 10413 final int callingUid = Binder.getCallingUid(); 10414 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 10415 10416 synchronized (mProcLock) { 10417 ProcessRecord proc; 10418 synchronized (mPidsSelfLocked) { 10419 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 10420 } 10421 if (proc != null) { 10422 mProcessList.fillInProcMemInfoLOSP(proc, outState, clientTargetSdk); 10423 } 10424 } 10425 } 10426 10427 @Override getMemoryTrimLevel()10428 public @MemFactor int getMemoryTrimLevel() { 10429 enforceNotIsolatedCaller("getMyMemoryState"); 10430 synchronized (this) { 10431 return mAppProfiler.getLastMemoryLevelLocked(); 10432 } 10433 } 10434 setMemFactorOverride(@emFactor int level)10435 void setMemFactorOverride(@MemFactor int level) { 10436 synchronized (this) { 10437 if (level == mAppProfiler.getLastMemoryLevelLocked()) { 10438 return; 10439 } 10440 10441 mAppProfiler.setMemFactorOverrideLocked(level); 10442 // Kick off an oom adj update since we forced a mem factor update. 10443 updateOomAdjLocked(OOM_ADJ_REASON_SHELL); 10444 } 10445 } 10446 10447 /** 10448 * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}. 10449 */ setServiceRestartBackoffEnabled(@onNull String packageName, boolean enable, @NonNull String reason)10450 void setServiceRestartBackoffEnabled(@NonNull String packageName, boolean enable, 10451 @NonNull String reason) { 10452 synchronized (this) { 10453 mServices.setServiceRestartBackoffEnabledLocked(packageName, enable, reason); 10454 } 10455 } 10456 10457 /** 10458 * @return {@code false} if the given package has been disable from enforcing the service 10459 * restart backoff policy, used by {@link ActivityManagerShellCommand}. 10460 */ isServiceRestartBackoffEnabled(@onNull String packageName)10461 boolean isServiceRestartBackoffEnabled(@NonNull String packageName) { 10462 synchronized (this) { 10463 return mServices.isServiceRestartBackoffEnabledLocked(packageName); 10464 } 10465 } 10466 10467 @Override onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)10468 public void onShellCommand(FileDescriptor in, FileDescriptor out, 10469 FileDescriptor err, String[] args, ShellCallback callback, 10470 ResultReceiver resultReceiver) { 10471 (new ActivityManagerShellCommand(this, false)).exec( 10472 this, in, out, err, args, callback, resultReceiver); 10473 } 10474 10475 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)10476 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 10477 PriorityDump.dump(mPriorityDumper, fd, pw, args); 10478 } 10479 10480 private static final String TICK = 10481 "---------------------------------------" 10482 + "----------------------------------------"; 10483 dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, int displayIdFilter, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies)10484 private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, 10485 boolean dumpAll, String dumpPackage, int displayIdFilter, boolean dumpClient, 10486 boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies) { 10487 10488 ActiveServices.ServiceDumper sdumper; 10489 10490 synchronized(this) { 10491 mConstants.dump(pw); 10492 synchronized (mProcLock) { 10493 mOomAdjuster.dumpCachedAppOptimizerSettings(pw); 10494 } 10495 mOomAdjuster.dumpCacheOomRankerSettings(pw); 10496 pw.println(); 10497 if (dumpAll) { 10498 pw.println( 10499 "-------------------------------------------------------------------------------"); 10500 } 10501 dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10502 pw.println(); 10503 if (dumpAll) { 10504 pw.println( 10505 "-------------------------------------------------------------------------------"); 10506 } 10507 mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage); 10508 pw.println(); 10509 if (dumpAll) { 10510 pw.println( 10511 "-------------------------------------------------------------------------------"); 10512 } 10513 dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10514 pw.println(); 10515 if (dumpAll) { 10516 pw.println( 10517 "-------------------------------------------------------------------------------"); 10518 } 10519 if (dumpAll || dumpPackage != null) { 10520 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10521 pw.println(); 10522 if (dumpAll) { 10523 pw.println( 10524 "-------------------------------------------------------------------------------"); 10525 } 10526 } 10527 mCpHelper.dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10528 pw.println(); 10529 if (dumpAll) { 10530 pw.println( 10531 "-------------------------------------------------------------------------------"); 10532 } 10533 dumpPermissions(fd, pw, args, opti, dumpAll, dumpPackage); 10534 pw.println(); 10535 sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10536 if (!dumpClient) { 10537 if (dumpAll) { 10538 pw.println( 10539 "-------------------------------------------------------------------------------"); 10540 } 10541 sdumper.dumpLocked(); 10542 } 10543 } 10544 10545 // No need to hold the lock. 10546 pw.println(TICK); 10547 AnrTimer.dump(pw, false); 10548 10549 // We drop the lock here because we can't call dumpWithClient() with the lock held; 10550 // if the caller wants a consistent state for the !dumpClient case, it can call this 10551 // method with the lock held. 10552 if (dumpClient) { 10553 if (dumpAll) { 10554 pw.println( 10555 "-------------------------------------------------------------------------------"); 10556 } 10557 sdumper.dumpWithClient(); 10558 } 10559 if (dumpPackage == null && dumpProxies) { 10560 // Intentionally dropping the lock for this, because dumpBinderProxies() will make many 10561 // outgoing binder calls to retrieve interface descriptors; while that is system code, 10562 // there is nothing preventing an app from overriding this implementation by talking to 10563 // the binder driver directly, and hang up system_server in the process. So, dump 10564 // without locks held, and even then only when there is an unreasonably large number of 10565 // proxies in the first place. 10566 pw.println(); 10567 if (dumpAll) { 10568 pw.println( 10569 "-------------------------------------------------------------------------------"); 10570 } 10571 dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */); 10572 } 10573 synchronized(this) { 10574 pw.println(); 10575 if (dumpAll) { 10576 pw.println( 10577 "-------------------------------------------------------------------------------"); 10578 } 10579 mAtmInternal.dump(DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10580 dumpPackage, displayIdFilter); 10581 pw.println(); 10582 if (dumpAll) { 10583 pw.println( 10584 "-------------------------------------------------------------------------------"); 10585 } 10586 mAtmInternal.dump(DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10587 dumpPackage, displayIdFilter); 10588 pw.println(); 10589 if (dumpAll) { 10590 pw.println( 10591 "-------------------------------------------------------------------------------"); 10592 } 10593 mAtmInternal.dump(DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10594 dumpPackage, displayIdFilter); 10595 if (dumpPackage == null) { 10596 pw.println(); 10597 if (dumpAll) { 10598 pw.println( 10599 "-------------------------------------------------------------------------------"); 10600 } 10601 mAtmInternal.dump(DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10602 dumpPackage, displayIdFilter); 10603 } 10604 // Activities section is dumped as part of the Critical priority dump. Exclude the 10605 // section if priority is Normal. 10606 if (!dumpNormalPriority) { 10607 pw.println(); 10608 if (dumpAll) { 10609 pw.println( 10610 "-------------------------------------------------------------------------------"); 10611 } 10612 mAtmInternal.dump(DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10613 dumpPackage, displayIdFilter); 10614 } 10615 if (mAssociations.size() > 0) { 10616 pw.println(); 10617 if (dumpAll) { 10618 pw.println( 10619 "-------------------------------------------------------------------------------"); 10620 } 10621 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 10622 } 10623 pw.println(); 10624 if (dumpAll) { 10625 pw.println( 10626 "-------------------------------------------------------------------------------"); 10627 mProcessList.getAppStartInfoTracker().dumpHistoryProcessStartInfo(pw, dumpPackage); 10628 pw.println( 10629 "-------------------------------------------------------------------------------"); 10630 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage); 10631 } 10632 if (dumpPackage == null) { 10633 pw.println(); 10634 if (dumpAll) { 10635 pw.println( 10636 "-------------------------------------------------------------------------------"); 10637 } 10638 dumpLmkLocked(pw); 10639 } 10640 pw.println(); 10641 if (dumpAll) { 10642 pw.println( 10643 "-------------------------------------------------------------------------------"); 10644 } 10645 synchronized (mProcLock) { 10646 mProcessList.dumpProcessesLSP(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId); 10647 } 10648 pw.println(); 10649 if (dumpAll) { 10650 pw.println( 10651 "-------------------------------------------------------------------------------"); 10652 } 10653 dumpUsers(pw); 10654 10655 pw.println(); 10656 if (dumpAll) { 10657 pw.println( 10658 "-------------------------------------------------------------------------------"); 10659 } 10660 mComponentAliasResolver.dump(pw); 10661 } 10662 } 10663 10664 /** 10665 * Dump the app restriction controller, it's required not to hold the global lock here. 10666 */ dumpAppRestrictionController(PrintWriter pw)10667 private void dumpAppRestrictionController(PrintWriter pw) { 10668 pw.println( 10669 "-------------------------------------------------------------------------------"); 10670 mAppRestrictionController.dump(pw, ""); 10671 } 10672 dumpAppRestrictionController(ProtoOutputStream proto, int uid)10673 void dumpAppRestrictionController(ProtoOutputStream proto, int uid) { 10674 mAppRestrictionController.dumpAsProto(proto, uid); 10675 } 10676 10677 /** 10678 * Wrapper function to print out debug data filtered by specified arguments. 10679 */ 10680 @NeverCompile // Avoid size overhead of debugging code. doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)10681 private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) { 10682 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 10683 10684 boolean dumpAll = false; 10685 boolean dumpClient = false; 10686 boolean dumpCheckin = false; 10687 boolean dumpCheckinFormat = false; 10688 boolean dumpNormalPriority = false; 10689 boolean dumpVisibleStacksOnly = false; 10690 boolean dumpFocusedStackOnly = false; 10691 int dumpDisplayId = INVALID_DISPLAY; 10692 String dumpPackage = null; 10693 int dumpUserId = UserHandle.USER_ALL; 10694 10695 int opti = 0; 10696 while (opti < args.length) { 10697 String opt = args[opti]; 10698 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 10699 break; 10700 } 10701 opti++; 10702 if ("-a".equals(opt)) { 10703 dumpAll = true; 10704 } else if ("-c".equals(opt)) { 10705 dumpClient = true; 10706 } else if ("-v".equals(opt)) { 10707 dumpVisibleStacksOnly = true; 10708 } else if ("-f".equals(opt)) { 10709 dumpFocusedStackOnly = true; 10710 } else if ("-p".equals(opt)) { 10711 if (opti < args.length) { 10712 dumpPackage = args[opti]; 10713 opti++; 10714 } else { 10715 pw.println("Error: -p option requires package argument"); 10716 return; 10717 } 10718 dumpClient = true; 10719 } else if ("--checkin".equals(opt)) { 10720 dumpCheckin = dumpCheckinFormat = true; 10721 } else if ("-C".equals(opt)) { 10722 dumpCheckinFormat = true; 10723 } else if ("--normal-priority".equals(opt)) { 10724 dumpNormalPriority = true; 10725 } else if ("--user".equals(opt)) { 10726 if (opti < args.length) { 10727 dumpUserId = UserHandle.parseUserArg(args[opti]); 10728 if (dumpUserId == UserHandle.USER_CURRENT) { 10729 dumpUserId = mUserController.getCurrentUserId(); 10730 } 10731 opti++; 10732 } else { 10733 pw.println("Error: --user option requires user id argument"); 10734 return; 10735 } 10736 } else if ("-d".equals(opt)) { 10737 if (opti < args.length) { 10738 dumpDisplayId = Integer.parseInt(args[opti]); 10739 if (dumpDisplayId == INVALID_DISPLAY) { 10740 pw.println("Error: -d cannot be used with INVALID_DISPLAY"); 10741 return; 10742 } 10743 opti++; 10744 } else { 10745 pw.println("Error: -d option requires display argument"); 10746 return; 10747 } 10748 dumpClient = true; 10749 } else if ("-h".equals(opt)) { 10750 ActivityManagerShellCommand.dumpHelp(pw, true); 10751 return; 10752 } else { 10753 pw.println("Unknown argument: " + opt + "; use -h for help"); 10754 return; 10755 } 10756 } 10757 10758 final long origId = Binder.clearCallingIdentity(); 10759 10760 if (useProto) { 10761 final ProtoOutputStream proto = new ProtoOutputStream(fd); 10762 String cmd = opti < args.length ? args[opti] : ""; 10763 opti++; 10764 10765 if ("activities".equals(cmd) || "a".equals(cmd)) { 10766 // output proto is ActivityManagerServiceDumpActivitiesProto 10767 mAtmInternal.writeActivitiesToProto(proto); 10768 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 10769 // output proto is ActivityManagerServiceDumpBroadcastsProto 10770 synchronized (this) { 10771 writeBroadcastsToProtoLocked(proto); 10772 } 10773 } else if ("provider".equals(cmd)) { 10774 String[] newArgs; 10775 String name; 10776 if (opti >= args.length) { 10777 name = null; 10778 newArgs = EMPTY_STRING_ARRAY; 10779 } else { 10780 name = args[opti]; 10781 opti++; 10782 newArgs = new String[args.length - opti]; 10783 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10784 args.length - opti); 10785 } 10786 if (!mCpHelper.dumpProviderProto(fd, pw, name, newArgs)) { 10787 pw.println("No providers match: " + name); 10788 pw.println("Use -h for help."); 10789 } 10790 } else if ("service".equals(cmd)) { 10791 // output proto is ActivityManagerServiceDumpServicesProto 10792 mServices.dumpDebug(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 10793 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 10794 if (opti < args.length) { 10795 dumpPackage = args[opti]; 10796 opti++; 10797 } 10798 // output proto is ProcessProto 10799 synchronized (this) { 10800 synchronized (mProcLock) { 10801 mProcessList.writeProcessesToProtoLSP(proto, dumpPackage); 10802 } 10803 } 10804 } else if ("app-restrictions".equals(cmd)) { 10805 int uid = Process.INVALID_UID; 10806 boolean error = false; 10807 for (int i = 0; i < args.length; i++) { 10808 if ("--uid".equals(args[i])) { 10809 if (i + 1 < args.length) { 10810 try { 10811 uid = Integer.parseInt(args[i + 1]); 10812 } catch (NumberFormatException e) { 10813 error = true; 10814 } 10815 } else { 10816 error = true; 10817 } 10818 break; 10819 } 10820 } 10821 if (error) { 10822 pw.println("Invalid --uid argument"); 10823 pw.println("Use -h for help."); 10824 } else { 10825 dumpAppRestrictionController(proto, uid); 10826 } 10827 } else { 10828 // default option, dump everything, output is ActivityManagerServiceProto 10829 synchronized (this) { 10830 long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES); 10831 mAtmInternal.writeActivitiesToProto(proto); 10832 proto.end(activityToken); 10833 10834 long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS); 10835 writeBroadcastsToProtoLocked(proto); 10836 proto.end(broadcastToken); 10837 10838 long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES); 10839 mServices.dumpDebug(proto, 10840 ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 10841 proto.end(serviceToken); 10842 10843 long processToken = proto.start(ActivityManagerServiceProto.PROCESSES); 10844 synchronized (mProcLock) { 10845 mProcessList.writeProcessesToProtoLSP(proto, dumpPackage); 10846 } 10847 proto.end(processToken); 10848 } 10849 } 10850 proto.flush(); 10851 Binder.restoreCallingIdentity(origId); 10852 return; 10853 } 10854 10855 int dumpAppId = getAppId(dumpPackage); 10856 boolean more = false; 10857 // Is the caller requesting to dump a particular piece of data? 10858 if (opti < args.length) { 10859 String cmd = args[opti]; 10860 opti++; 10861 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd) 10862 || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd) 10863 || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd) 10864 || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd) 10865 || DUMP_TOP_RESUMED_ACTIVITY.equals(cmd) 10866 || DUMP_VISIBLE_ACTIVITIES.equals(cmd)) { 10867 mAtmInternal.dump(cmd, fd, pw, args, opti, /* dumpAll= */ true , dumpClient, 10868 dumpPackage, dumpDisplayId); 10869 } else if ("binder-proxies".equals(cmd)) { 10870 if (opti >= args.length) { 10871 dumpBinderProxies(pw, 0 /* minToDump */); 10872 } else { 10873 String uid = args[opti]; 10874 opti++; 10875 // Ensure Binder Proxy Count is as up to date as possible 10876 System.gc(); 10877 System.runFinalization(); 10878 System.gc(); 10879 pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid))); 10880 } 10881 } else if ("allowed-associations".equals(cmd)) { 10882 if (opti < args.length) { 10883 dumpPackage = args[opti]; 10884 opti++; 10885 } 10886 synchronized (this) { 10887 dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage); 10888 } 10889 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 10890 if (opti < args.length) { 10891 dumpPackage = args[opti]; 10892 opti++; 10893 } 10894 synchronized (this) { 10895 dumpBroadcastsLocked(fd, pw, args, opti, /* dumpAll= */ true, dumpPackage); 10896 } 10897 } else if ("broadcast-stats".equals(cmd)) { 10898 if (opti < args.length) { 10899 dumpPackage = args[opti]; 10900 opti++; 10901 } 10902 synchronized (this) { 10903 if (dumpCheckinFormat) { 10904 dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, 10905 dumpPackage); 10906 } else { 10907 dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage); 10908 } 10909 } 10910 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 10911 if (opti < args.length) { 10912 dumpPackage = args[opti]; 10913 opti++; 10914 } 10915 mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage); 10916 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 10917 if (opti < args.length) { 10918 dumpPackage = args[opti]; 10919 opti++; 10920 } 10921 synchronized (this) { 10922 synchronized (mProcLock) { 10923 mProcessList.dumpProcessesLSP( 10924 fd, pw, args, opti, true, dumpPackage, dumpAppId); 10925 } 10926 } 10927 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 10928 synchronized (this) { 10929 mProcessList.dumpOomLocked(fd, pw, false, args, opti, true, dumpPackage, true); 10930 } 10931 } else if ("lmk".equals(cmd)) { 10932 synchronized (this) { 10933 dumpLmkLocked(pw); 10934 } 10935 } else if ("lru".equals(cmd)) { 10936 synchronized (this) { 10937 mProcessList.dumpLruLocked(pw, dumpPackage, null); 10938 } 10939 } else if ("permissions".equals(cmd) || "perm".equals(cmd)) { 10940 dumpPermissions(fd, pw, args, opti, true, dumpPackage); 10941 } else if ("provider".equals(cmd)) { 10942 String[] newArgs; 10943 String name; 10944 if (opti >= args.length) { 10945 name = null; 10946 newArgs = EMPTY_STRING_ARRAY; 10947 } else { 10948 name = args[opti]; 10949 opti++; 10950 newArgs = new String[args.length - opti]; 10951 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti); 10952 } 10953 if (!mCpHelper.dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 10954 pw.println("No providers match: " + name); 10955 pw.println("Use -h for help."); 10956 } 10957 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 10958 synchronized (this) { 10959 mCpHelper.dumpProvidersLocked(fd, pw, args, opti, true, dumpPackage); 10960 } 10961 } else if ("service".equals(cmd)) { 10962 String[] newArgs; 10963 String name; 10964 if (opti >= args.length) { 10965 name = null; 10966 newArgs = EMPTY_STRING_ARRAY; 10967 } else { 10968 name = args[opti]; 10969 opti++; 10970 newArgs = new String[args.length - opti]; 10971 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10972 args.length - opti); 10973 } 10974 int[] users = dumpUserId == UserHandle.USER_ALL ? null : new int[] { dumpUserId }; 10975 if (!mServices.dumpService(fd, pw, name, users, newArgs, 0, dumpAll)) { 10976 pw.println("No services match: " + name); 10977 pw.println("Use -h for help."); 10978 } 10979 } else if ("package".equals(cmd)) { 10980 String[] newArgs; 10981 if (opti >= args.length) { 10982 pw.println("package: no package name specified"); 10983 pw.println("Use -h for help."); 10984 } else { 10985 dumpPackage = args[opti]; 10986 opti++; 10987 newArgs = new String[args.length - opti]; 10988 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10989 args.length - opti); 10990 args = newArgs; 10991 opti = 0; 10992 more = true; 10993 } 10994 } else if ("associations".equals(cmd) || "as".equals(cmd)) { 10995 synchronized (this) { 10996 dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage); 10997 } 10998 } else if ("settings".equals(cmd)) { 10999 synchronized (this) { 11000 mConstants.dump(pw); 11001 } 11002 synchronized (mProcLock) { 11003 mOomAdjuster.dumpCachedAppOptimizerSettings(pw); 11004 mOomAdjuster.dumpCacheOomRankerSettings(pw); 11005 } 11006 } else if ("timers".equals(cmd)) { 11007 AnrTimer.dump(pw, true); 11008 } else if ("services".equals(cmd) || "s".equals(cmd)) { 11009 if (dumpClient) { 11010 ActiveServices.ServiceDumper dumper; 11011 synchronized (this) { 11012 dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true, 11013 dumpPackage); 11014 } 11015 dumper.dumpWithClient(); 11016 } else { 11017 synchronized (this) { 11018 mServices.newServiceDumperLocked(fd, pw, args, opti, true, 11019 dumpPackage).dumpLocked(); 11020 } 11021 } 11022 } else if ("locks".equals(cmd)) { 11023 LockGuard.dump(fd, pw, args); 11024 } else if ("users".equals(cmd)) { 11025 dumpUsers(pw); 11026 } else if ("start-info".equals(cmd)) { 11027 if (opti < args.length) { 11028 dumpPackage = args[opti]; 11029 opti++; 11030 } 11031 mProcessList.getAppStartInfoTracker().dumpHistoryProcessStartInfo(pw, dumpPackage); 11032 } else if ("exit-info".equals(cmd)) { 11033 if (opti < args.length) { 11034 dumpPackage = args[opti]; 11035 opti++; 11036 } 11037 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage); 11038 } else if ("component-alias".equals(cmd)) { 11039 mComponentAliasResolver.dump(pw); 11040 } else { 11041 // Dumping a single activity? 11042 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll, 11043 dumpVisibleStacksOnly, dumpFocusedStackOnly, dumpDisplayId, dumpUserId)) { 11044 ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true); 11045 int res = shell.exec(this, null, fd, null, args, null, 11046 new ResultReceiver(null)); 11047 if (res < 0) { 11048 pw.println("Bad activity command, or no activities match: " + cmd); 11049 pw.println("Use -h for help."); 11050 } 11051 } 11052 } 11053 if (!more) { 11054 Binder.restoreCallingIdentity(origId); 11055 return; 11056 } 11057 } 11058 11059 // No piece of data specified, dump everything. 11060 if (dumpCheckinFormat) { 11061 dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage); 11062 } else { 11063 if (dumpClient) { 11064 // dumpEverything() will take the lock when needed, and momentarily drop 11065 // it for dumping client state. 11066 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpDisplayId, 11067 dumpClient, dumpNormalPriority, dumpAppId, /* dumpProxies= */ true); 11068 } else { 11069 // Take the lock here, so we get a consistent state for the entire dump; 11070 // dumpEverything() will take the lock as well, which is fine for everything 11071 // except dumping proxies, which can take a long time; exclude them. 11072 synchronized(this) { 11073 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpDisplayId, 11074 dumpClient, dumpNormalPriority, dumpAppId, /* dumpProxies= */ false); 11075 } 11076 } 11077 if (dumpAll) { 11078 dumpAppRestrictionController(pw); 11079 } 11080 } 11081 Binder.restoreCallingIdentity(origId); 11082 } 11083 dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)11084 void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11085 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 11086 pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)"); 11087 11088 int dumpUid = 0; 11089 if (dumpPackage != null) { 11090 IPackageManager pm = AppGlobals.getPackageManager(); 11091 try { 11092 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0); 11093 } catch (RemoteException e) { 11094 } 11095 } 11096 11097 boolean printedAnything = false; 11098 11099 final long now = SystemClock.uptimeMillis(); 11100 11101 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 11102 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 11103 = mAssociations.valueAt(i1); 11104 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 11105 SparseArray<ArrayMap<String, Association>> sourceUids 11106 = targetComponents.valueAt(i2); 11107 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) { 11108 ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3); 11109 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 11110 Association ass = sourceProcesses.valueAt(i4); 11111 if (dumpPackage != null) { 11112 if (!ass.mTargetComponent.getPackageName().equals(dumpPackage) 11113 && UserHandle.getAppId(ass.mSourceUid) != dumpUid) { 11114 continue; 11115 } 11116 } 11117 printedAnything = true; 11118 pw.print(" "); 11119 pw.print(ass.mTargetProcess); 11120 pw.print("/"); 11121 UserHandle.formatUid(pw, ass.mTargetUid); 11122 pw.print(" <- "); 11123 pw.print(ass.mSourceProcess); 11124 pw.print("/"); 11125 UserHandle.formatUid(pw, ass.mSourceUid); 11126 pw.println(); 11127 pw.print(" via "); 11128 pw.print(ass.mTargetComponent.flattenToShortString()); 11129 pw.println(); 11130 pw.print(" "); 11131 long dur = ass.mTime; 11132 if (ass.mNesting > 0) { 11133 dur += now - ass.mStartTime; 11134 } 11135 TimeUtils.formatDuration(dur, pw); 11136 pw.print(" ("); 11137 pw.print(ass.mCount); 11138 pw.print(" times)"); 11139 pw.print(" "); 11140 for (int i=0; i<ass.mStateTimes.length; i++) { 11141 long amt = ass.mStateTimes[i]; 11142 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 11143 amt += now - ass.mLastStateUptime; 11144 } 11145 if (amt != 0) { 11146 pw.print(" "); 11147 pw.print(ProcessList.makeProcStateString( 11148 i + ActivityManager.MIN_PROCESS_STATE)); 11149 pw.print("="); 11150 TimeUtils.formatDuration(amt, pw); 11151 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 11152 pw.print("*"); 11153 } 11154 } 11155 } 11156 pw.println(); 11157 if (ass.mNesting > 0) { 11158 pw.print(" Currently active: "); 11159 TimeUtils.formatDuration(now - ass.mStartTime, pw); 11160 pw.println(); 11161 } 11162 } 11163 } 11164 } 11165 11166 } 11167 11168 if (!printedAnything) { 11169 pw.println(" (nothing)"); 11170 } 11171 } 11172 getAppId(String dumpPackage)11173 int getAppId(String dumpPackage) { 11174 if (dumpPackage != null) { 11175 try { 11176 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 11177 dumpPackage, 0); 11178 return UserHandle.getAppId(info.uid); 11179 } catch (NameNotFoundException e) { 11180 e.printStackTrace(); 11181 } 11182 } 11183 return -1; 11184 } 11185 dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)11186 void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) { 11187 final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50); 11188 11189 pw.println(header); 11190 for (int i = 0; i < proxyCounts.length; i++) { 11191 pw.println(" #" + (i + 1) + ": " + proxyCounts[i]); 11192 } 11193 } 11194 dumpBinderProxiesCounts(PrintWriter pw, String header)11195 boolean dumpBinderProxiesCounts(PrintWriter pw, String header) { 11196 SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts(); 11197 if(counts != null) { 11198 pw.println(header); 11199 for (int i = 0; i < counts.size(); i++) { 11200 final int uid = counts.keyAt(i); 11201 final int binderCount = counts.valueAt(i); 11202 pw.print(" UID "); 11203 pw.print(uid); 11204 pw.print(", binder count = "); 11205 pw.print(binderCount); 11206 pw.print(", package(s)= "); 11207 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid); 11208 if (pkgNames != null) { 11209 for (int j = 0; j < pkgNames.length; j++) { 11210 pw.print(pkgNames[j]); 11211 pw.print("; "); 11212 } 11213 } else { 11214 pw.print("NO PACKAGE NAME FOUND"); 11215 } 11216 pw.println(); 11217 } 11218 return true; 11219 } 11220 return false; 11221 } 11222 dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)11223 void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) { 11224 pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)"); 11225 final int proxyCount = BinderProxy.getProxyCount(); 11226 if (proxyCount >= minCountToDumpInterfaces) { 11227 dumpBinderProxyInterfaceCounts(pw, 11228 "Top proxy interface names held by SYSTEM"); 11229 } else { 11230 pw.print("Not dumping proxy interface counts because size (" 11231 + Integer.toString(proxyCount) + ") looks reasonable"); 11232 pw.println(); 11233 } 11234 dumpBinderProxiesCounts(pw, 11235 " Counts of Binder Proxies held by SYSTEM"); 11236 } 11237 11238 @GuardedBy("this") dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep)11239 boolean dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep) { 11240 final int size = mActiveInstrumentation.size(); 11241 if (size > 0) { 11242 boolean printed = false; 11243 for (int i = 0; i < size; i++) { 11244 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 11245 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 11246 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 11247 continue; 11248 } 11249 if (!printed) { 11250 if (needSep) { 11251 pw.println(); 11252 } 11253 pw.println(" Active instrumentation:"); 11254 printed = true; 11255 needSep = true; 11256 } 11257 pw.print(" Instrumentation #"); pw.print(i); pw.print(": "); 11258 pw.println(ai); 11259 ai.dump(pw, " "); 11260 } 11261 } 11262 return needSep; 11263 } 11264 11265 @NeverCompile // Avoid size overhead of debugging code. 11266 @GuardedBy({"this", "mProcLock"}) dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep)11267 void dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, 11268 boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep) { 11269 if (dumpAll || dumpPackage != null) { 11270 final SparseArray<ProcessRecord> pidToProcess = new SparseArray<>(); 11271 synchronized (mPidsSelfLocked) { 11272 boolean printed = false; 11273 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 11274 ProcessRecord r = mPidsSelfLocked.valueAt(i); 11275 pidToProcess.put(r.getPid(), r); 11276 if (dumpPackage != null && !r.getPkgList().containsKey(dumpPackage)) { 11277 continue; 11278 } 11279 if (!printed) { 11280 if (needSep) pw.println(); 11281 needSep = true; 11282 pw.println(" PID mappings:"); 11283 printed = true; 11284 } 11285 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 11286 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 11287 } 11288 } 11289 11290 synchronized (sActiveProcessInfoSelfLocked) { 11291 boolean printed = false; 11292 for (int i = 0, size = sActiveProcessInfoSelfLocked.size(); i < size; i++) { 11293 ProcessInfo info = sActiveProcessInfoSelfLocked.valueAt(i); 11294 ProcessRecord r = pidToProcess.get(sActiveProcessInfoSelfLocked.keyAt(i)); 11295 if (r != null && dumpPackage != null 11296 && !r.getPkgList().containsKey(dumpPackage)) { 11297 continue; 11298 } 11299 if (!printed) { 11300 if (needSep) pw.println(); 11301 needSep = true; 11302 pw.println(" Active process infos:"); 11303 printed = true; 11304 } 11305 pw.print(" Pinfo PID #"); pw.print(sActiveProcessInfoSelfLocked.keyAt(i)); 11306 pw.println(":"); 11307 pw.print(" name="); pw.println(info.name); 11308 if (info.deniedPermissions != null) { 11309 for (int j = 0; j < info.deniedPermissions.size(); j++) { 11310 pw.print(" deny: "); 11311 pw.println(info.deniedPermissions.valueAt(j)); 11312 } 11313 } 11314 } 11315 } 11316 } 11317 11318 if (dumpAll) { 11319 mPhantomProcessList.dump(pw, " "); 11320 } 11321 11322 if (mImportantProcesses.size() > 0) { 11323 synchronized (mPidsSelfLocked) { 11324 boolean printed = false; 11325 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) { 11326 ProcessRecord r = mPidsSelfLocked.get(mImportantProcesses.valueAt(i).pid); 11327 if (dumpPackage != null && (r == null 11328 || !r.getPkgList().containsKey(dumpPackage))) { 11329 continue; 11330 } 11331 if (!printed) { 11332 if (needSep) pw.println(); 11333 needSep = true; 11334 pw.println(" Foreground Processes:"); 11335 printed = true; 11336 } 11337 pw.print(" PID #"); pw.print(mImportantProcesses.keyAt(i)); 11338 pw.print(": "); pw.println(mImportantProcesses.valueAt(i)); 11339 } 11340 } 11341 } 11342 11343 if (mPersistentStartingProcesses.size() > 0) { 11344 if (needSep) pw.println(); 11345 needSep = true; 11346 pw.println(" Persisent processes that are starting:"); 11347 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 11348 "Starting Norm", "Restarting PERS", dumpPackage); 11349 } 11350 11351 if (mProcessList.mRemovedProcesses.size() > 0) { 11352 if (needSep) pw.println(); 11353 needSep = true; 11354 pw.println(" Processes that are being removed:"); 11355 dumpProcessList(pw, this, mProcessList.mRemovedProcesses, " ", 11356 "Removed Norm", "Removed PERS", dumpPackage); 11357 } 11358 11359 if (mProcessesOnHold.size() > 0) { 11360 if (needSep) pw.println(); 11361 needSep = true; 11362 pw.println(" Processes that are on old until the system is ready:"); 11363 dumpProcessList(pw, this, mProcessesOnHold, " ", 11364 "OnHold Norm", "OnHold PERS", dumpPackage); 11365 } 11366 11367 needSep = mAppErrors.dumpLPr(fd, pw, needSep, dumpPackage); 11368 11369 needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep, 11370 mAppProfiler.getTestPssMode(), mWakefulness.get()); 11371 11372 if (dumpAll && mProcessList.mPendingStarts.size() > 0) { 11373 if (needSep) pw.println(); 11374 needSep = true; 11375 pw.println(" mPendingStarts: "); 11376 for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) { 11377 pw.println(" " + mProcessList.mPendingStarts.keyAt(i) + ": " 11378 + mProcessList.mPendingStarts.valueAt(i)); 11379 } 11380 } 11381 if (dumpAll) { 11382 mUidObserverController.dump(pw, dumpPackage); 11383 11384 pw.println(" mDeviceIdleAllowlist=" + Arrays.toString(mDeviceIdleAllowlist)); 11385 pw.println(" mDeviceIdleExceptIdleAllowlist=" 11386 + Arrays.toString(mDeviceIdleExceptIdleAllowlist)); 11387 pw.println(" mDeviceIdleTempAllowlist=" + Arrays.toString(mDeviceIdleTempAllowlist)); 11388 if (mPendingTempAllowlist.size() > 0) { 11389 pw.println(" mPendingTempAllowlist:"); 11390 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) { 11391 PendingTempAllowlist ptw = mPendingTempAllowlist.valueAt(i); 11392 pw.print(" "); 11393 UserHandle.formatUid(pw, ptw.targetUid); 11394 pw.print(": "); 11395 TimeUtils.formatDuration(ptw.duration, pw); 11396 pw.print(" "); 11397 pw.println(ptw.tag); 11398 pw.print(" "); 11399 pw.print(ptw.type); 11400 pw.print(" "); 11401 pw.print(ptw.reasonCode); 11402 pw.print(" "); 11403 pw.print(ptw.callingUid); 11404 } 11405 } 11406 pw.println(" mFgsStartTempAllowList:"); 11407 final long currentTimeNow = System.currentTimeMillis(); 11408 final long elapsedRealtimeNow = SystemClock.elapsedRealtime(); 11409 mFgsStartTempAllowList.forEach((uid, entry) -> { 11410 pw.print(" " + UserHandle.formatUid(uid) + ": "); 11411 entry.second.dump(pw); 11412 pw.print(" expiration="); 11413 // Convert entry.mExpirationTime, which is an elapsed time since boot, 11414 // to a time since epoch (i.e. System.currentTimeMillis()-based time.) 11415 final long expirationInCurrentTime = 11416 currentTimeNow - elapsedRealtimeNow + entry.first; 11417 TimeUtils.dumpTimeWithDelta(pw, expirationInCurrentTime, currentTimeNow); 11418 pw.println(); 11419 }); 11420 11421 if (!mProcessList.mAppsInBackgroundRestricted.isEmpty()) { 11422 pw.println(" Processes that are in background restricted:"); 11423 for (int i = 0, size = mProcessList.mAppsInBackgroundRestricted.size(); 11424 i < size; i++) { 11425 pw.println(String.format("%s #%2d: %s", " ", i, 11426 mProcessList.mAppsInBackgroundRestricted.valueAt(i).toString())); 11427 } 11428 } 11429 } 11430 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 11431 || mOrigWaitForDebugger) { 11432 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 11433 || dumpPackage.equals(mOrigDebugApp)) { 11434 if (needSep) { 11435 pw.println(); 11436 needSep = false; 11437 } 11438 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 11439 + " mDebugTransient=" + mDebugTransient 11440 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 11441 } 11442 } 11443 synchronized (mAppProfiler.mProfilerLock) { 11444 needSep = mAppProfiler.dumpMemWatchProcessesLPf(pw, needSep); 11445 } 11446 if (mTrackAllocationApp != null) { 11447 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 11448 if (needSep) { 11449 pw.println(); 11450 needSep = false; 11451 } 11452 pw.println(" mTrackAllocationApp=" + mTrackAllocationApp); 11453 } 11454 } 11455 needSep = mAppProfiler.dumpProfileDataLocked(pw, dumpPackage, needSep); 11456 if (mNativeDebuggingApp != null) { 11457 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 11458 if (needSep) { 11459 pw.println(); 11460 needSep = false; 11461 } 11462 pw.println(" mNativeDebuggingApp=" + mNativeDebuggingApp); 11463 } 11464 } 11465 if (dumpPackage == null) { 11466 if (mAlwaysFinishActivities) { 11467 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities); 11468 } 11469 if (mAllowSpecifiedFifoScheduling) { 11470 pw.println(" mAllowSpecifiedFifoScheduling=true"); 11471 } 11472 if (dumpAll) { 11473 pw.println(" Total persistent processes: " + numPers); 11474 pw.println(" mProcessesReady=" + mProcessesReady 11475 + " mSystemReady=" + mSystemReady 11476 + " mBooted=" + mBooted 11477 + " mFactoryTest=" + mFactoryTest); 11478 pw.println(" mBooting=" + mBooting 11479 + " mCallFinishBooting=" + mCallFinishBooting 11480 + " mBootAnimationComplete=" + mBootAnimationComplete); 11481 pw.print(" mLastPowerCheckUptime="); 11482 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 11483 pw.println(""); 11484 mOomAdjuster.dumpSequenceNumbersLocked(pw); 11485 mOomAdjuster.dumpProcCountsLocked(pw); 11486 mAppProfiler.dumpMemoryLevelsLocked(pw); 11487 long now = SystemClock.uptimeMillis(); 11488 pw.print(" mLastIdleTime="); 11489 TimeUtils.formatDuration(now, mLastIdleTime, pw); 11490 pw.print(" mLowRamSinceLastIdle="); 11491 TimeUtils.formatDuration( 11492 mAppProfiler.getLowRamTimeSinceIdleLPr(now), pw); 11493 pw.println(); 11494 11495 pw.println(); 11496 pw.println(" ServiceManager statistics:"); 11497 ServiceManager.sStatLogger.dump(pw, " "); 11498 pw.println(); 11499 } 11500 } 11501 pw.println(" mForceBackgroundCheck=" + mForceBackgroundCheck); 11502 } 11503 dumpUsers(PrintWriter pw)11504 private void dumpUsers(PrintWriter pw) { 11505 pw.println("ACTIVITY MANAGER USERS (dumpsys activity users)"); 11506 mUserController.dump(pw); 11507 } 11508 11509 @GuardedBy({"this", "mProcLock"}) writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, int dumpAppId, int numPers)11510 void writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, 11511 int dumpAppId, int numPers) { 11512 for (int i = 0, size = mActiveInstrumentation.size(); i < size; i++) { 11513 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 11514 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 11515 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 11516 continue; 11517 } 11518 ai.dumpDebug(proto, 11519 ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS); 11520 } 11521 11522 mUidObserverController.dumpValidateUidsProto(proto, dumpPackage, dumpAppId, 11523 ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS); 11524 11525 if (dumpPackage != null) { 11526 synchronized (mPidsSelfLocked) { 11527 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 11528 ProcessRecord r = mPidsSelfLocked.valueAt(i); 11529 if (!r.getPkgList().containsKey(dumpPackage)) { 11530 continue; 11531 } 11532 r.dumpDebug(proto, 11533 ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED); 11534 } 11535 } 11536 } 11537 11538 if (mImportantProcesses.size() > 0) { 11539 synchronized (mPidsSelfLocked) { 11540 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) { 11541 ImportanceToken it = mImportantProcesses.valueAt(i); 11542 ProcessRecord r = mPidsSelfLocked.get(it.pid); 11543 if (dumpPackage != null && (r == null 11544 || !r.getPkgList().containsKey(dumpPackage))) { 11545 continue; 11546 } 11547 it.dumpDebug(proto, 11548 ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS); 11549 } 11550 } 11551 } 11552 11553 for (int i = 0, size = mPersistentStartingProcesses.size(); i < size; i++) { 11554 ProcessRecord r = mPersistentStartingProcesses.get(i); 11555 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11556 continue; 11557 } 11558 r.dumpDebug(proto, 11559 ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS); 11560 } 11561 11562 for (int i = 0, size = mProcessList.mRemovedProcesses.size(); i < size; i++) { 11563 ProcessRecord r = mProcessList.mRemovedProcesses.get(i); 11564 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11565 continue; 11566 } 11567 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS); 11568 } 11569 11570 for (int i = 0, size = mProcessesOnHold.size(); i < size; i++) { 11571 ProcessRecord r = mProcessesOnHold.get(i); 11572 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11573 continue; 11574 } 11575 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS); 11576 } 11577 11578 synchronized (mAppProfiler.mProfilerLock) { 11579 mAppProfiler.writeProcessesToGcToProto(proto, 11580 ActivityManagerServiceDumpProcessesProto.GC_PROCS, 11581 dumpPackage); 11582 } 11583 mAppErrors.dumpDebugLPr(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS, 11584 dumpPackage); 11585 mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness.get(), 11586 mAppProfiler.getTestPssMode()); 11587 11588 if (dumpPackage == null) { 11589 mUserController.dumpDebug(proto, 11590 ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER); 11591 } 11592 11593 mUidObserverController.dumpDebug(proto, dumpPackage); 11594 11595 for (int v : mDeviceIdleAllowlist) { 11596 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v); 11597 } 11598 11599 for (int v : mDeviceIdleTempAllowlist) { 11600 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v); 11601 } 11602 11603 if (mPendingTempAllowlist.size() > 0) { 11604 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) { 11605 mPendingTempAllowlist.valueAt(i).dumpDebug(proto, 11606 ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST); 11607 } 11608 } 11609 11610 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 11611 || mOrigWaitForDebugger) { 11612 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 11613 || dumpPackage.equals(mOrigDebugApp)) { 11614 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG); 11615 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp); 11616 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp); 11617 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient); 11618 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger); 11619 proto.end(debugAppToken); 11620 } 11621 } 11622 11623 synchronized (mAppProfiler.mProfilerLock) { 11624 mAppProfiler.writeMemWatchProcessToProtoLPf(proto); 11625 } 11626 11627 if (mTrackAllocationApp != null) { 11628 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 11629 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP, 11630 mTrackAllocationApp); 11631 } 11632 } 11633 11634 mAppProfiler.writeProfileDataToProtoLocked(proto, dumpPackage); 11635 11636 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 11637 proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp); 11638 } 11639 11640 if (dumpPackage == null) { 11641 proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities); 11642 proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers); 11643 proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady); 11644 proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady); 11645 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted); 11646 proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest); 11647 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting); 11648 proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting); 11649 proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete); 11650 proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime); 11651 mOomAdjuster.dumpProcessListVariablesLocked(proto); 11652 mAppProfiler.writeMemoryLevelsToProtoLocked(proto); 11653 long now = SystemClock.uptimeMillis(); 11654 ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now); 11655 proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS, 11656 mAppProfiler.getLowRamTimeSinceIdleLPr(now)); 11657 } 11658 } 11659 reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)11660 private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) { 11661 Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj); 11662 if (cnt != null) { 11663 pw.println(" kills at or below oom_adj " + oom_adj + ": " + cnt); 11664 return true; 11665 } 11666 return false; 11667 } 11668 dumpLmkLocked(PrintWriter pw)11669 boolean dumpLmkLocked(PrintWriter pw) { 11670 pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)"); 11671 Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ, 11672 ProcessList.UNKNOWN_ADJ); 11673 if (cnt == null) { 11674 return false; 11675 } 11676 pw.println(" Total number of kills: " + cnt); 11677 11678 return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) && 11679 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) && 11680 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) && 11681 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) && 11682 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) && 11683 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) && 11684 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) && 11685 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) && 11686 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) && 11687 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) && 11688 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) && 11689 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ); 11690 } 11691 11692 public static class ItemMatcher { 11693 ArrayList<ComponentName> components; 11694 ArrayList<String> strings; 11695 ArrayList<Integer> objects; 11696 boolean all; 11697 ItemMatcher()11698 public ItemMatcher() { 11699 all = true; 11700 } 11701 build(String name)11702 public void build(String name) { 11703 ComponentName componentName = ComponentName.unflattenFromString(name); 11704 if (componentName != null) { 11705 if (components == null) { 11706 components = new ArrayList<ComponentName>(); 11707 } 11708 components.add(componentName); 11709 all = false; 11710 } else { 11711 int objectId = 0; 11712 // Not a '/' separated full component name; maybe an object ID? 11713 try { 11714 objectId = Integer.parseInt(name, 16); 11715 if (objects == null) { 11716 objects = new ArrayList<Integer>(); 11717 } 11718 objects.add(objectId); 11719 all = false; 11720 } catch (RuntimeException e) { 11721 // Not an integer; just do string match. 11722 if (strings == null) { 11723 strings = new ArrayList<String>(); 11724 } 11725 strings.add(name); 11726 all = false; 11727 } 11728 } 11729 } 11730 build(String[] args, int opti)11731 public int build(String[] args, int opti) { 11732 for (; opti<args.length; opti++) { 11733 String name = args[opti]; 11734 if ("--".equals(name)) { 11735 return opti+1; 11736 } 11737 build(name); 11738 } 11739 return opti; 11740 } 11741 match(Object object, ComponentName comp)11742 public boolean match(Object object, ComponentName comp) { 11743 if (all) { 11744 return true; 11745 } 11746 if (components != null) { 11747 for (int i=0; i<components.size(); i++) { 11748 if (components.get(i).equals(comp)) { 11749 return true; 11750 } 11751 } 11752 } 11753 if (objects != null) { 11754 for (int i=0; i<objects.size(); i++) { 11755 if (System.identityHashCode(object) == objects.get(i)) { 11756 return true; 11757 } 11758 } 11759 } 11760 if (strings != null) { 11761 String flat = comp.flattenToString(); 11762 for (int i=0; i<strings.size(); i++) { 11763 if (flat.contains(strings.get(i))) { 11764 return true; 11765 } 11766 } 11767 } 11768 return false; 11769 } 11770 } 11771 writeBroadcastsToProtoLocked(ProtoOutputStream proto)11772 void writeBroadcastsToProtoLocked(ProtoOutputStream proto) { 11773 if (mRegisteredReceivers.size() > 0) { 11774 Iterator it = mRegisteredReceivers.values().iterator(); 11775 while (it.hasNext()) { 11776 ReceiverList r = (ReceiverList)it.next(); 11777 r.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST); 11778 } 11779 } 11780 mReceiverResolver.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER); 11781 mBroadcastQueue.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE); 11782 synchronized (mStickyBroadcasts) { 11783 for (int user = 0; user < mStickyBroadcasts.size(); user++) { 11784 long token = proto.start( 11785 ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS); 11786 proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user)); 11787 for (Map.Entry<String, ArrayList<StickyBroadcast>> ent 11788 : mStickyBroadcasts.valueAt(user).entrySet()) { 11789 long actionToken = proto.start(StickyBroadcastProto.ACTIONS); 11790 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey()); 11791 for (StickyBroadcast broadcast : ent.getValue()) { 11792 broadcast.intent.dumpDebug(proto, StickyBroadcastProto.StickyAction.INTENTS, 11793 false, true, true, false); 11794 } 11795 proto.end(actionToken); 11796 } 11797 proto.end(token); 11798 } 11799 } 11800 11801 long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER); 11802 proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString()); 11803 mHandler.getLooper().dumpDebug(proto, 11804 ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER); 11805 proto.end(handlerToken); 11806 } 11807 dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11808 void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11809 int opti, boolean dumpAll, String dumpPackage) { 11810 pw.println( 11811 "ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity" 11812 + " allowed-associations)"); 11813 boolean printed = false; 11814 if (mAllowedAssociations != null) { 11815 for (int i = 0; i < mAllowedAssociations.size(); i++) { 11816 final String pkg = mAllowedAssociations.keyAt(i); 11817 final ArraySet<String> asc = 11818 mAllowedAssociations.valueAt(i).getAllowedPackageAssociations(); 11819 if (!printed) { 11820 pw.println(" Allowed associations (by restricted package):"); 11821 printed = true; 11822 } 11823 pw.print(" * "); 11824 pw.print(pkg); 11825 pw.println(":"); 11826 for (int j = 0; j < asc.size(); j++) { 11827 if (dumpPackage == null || pkg.equals(dumpPackage) 11828 || asc.valueAt(j).equals(dumpPackage)) { 11829 pw.print(" Allow: "); 11830 pw.println(asc.valueAt(j)); 11831 } 11832 } 11833 if (mAllowedAssociations.valueAt(i).isDebuggable()) { 11834 pw.println(" (debuggable)"); 11835 } 11836 } 11837 } 11838 if (!printed) { 11839 pw.println(" (No association restrictions)"); 11840 } 11841 } 11842 11843 @NeverCompile dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11844 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11845 int opti, boolean dumpAll, String dumpPackage) { 11846 boolean dumpConstants = true; 11847 boolean dumpHistory = true; 11848 boolean needSep = false; 11849 boolean onlyHistory = false; 11850 boolean printedAnything = false; 11851 boolean onlyReceivers = false; 11852 int filteredUid = Process.INVALID_UID; 11853 11854 if ("history".equals(dumpPackage)) { 11855 if (opti < args.length && "-s".equals(args[opti])) { 11856 dumpAll = false; 11857 } 11858 onlyHistory = true; 11859 dumpPackage = null; 11860 } 11861 if ("receivers".equals(dumpPackage)) { 11862 onlyReceivers = true; 11863 dumpPackage = null; 11864 if (opti + 2 <= args.length) { 11865 for (int i = opti; i < args.length; i++) { 11866 String arg = args[i]; 11867 switch (arg) { 11868 case "--uid": 11869 filteredUid = getIntArg(pw, args, ++i, Process.INVALID_UID); 11870 if (filteredUid == Process.INVALID_UID) { 11871 return; 11872 } 11873 break; 11874 default: 11875 pw.printf("Invalid argument at index %d: %s\n", i, arg); 11876 return; 11877 } 11878 } 11879 } 11880 } 11881 if (DEBUG_BROADCAST) { 11882 Slogf.d(TAG_BROADCAST, "dumpBroadcastsLocked(): dumpPackage=%s, onlyHistory=%b, " 11883 + "onlyReceivers=%b, filteredUid=%d", dumpPackage, onlyHistory, onlyReceivers, 11884 filteredUid); 11885 } 11886 11887 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 11888 if (!onlyHistory && dumpAll) { 11889 if (mRegisteredReceivers.size() > 0) { 11890 boolean printed = false; 11891 Iterator it = mRegisteredReceivers.values().iterator(); 11892 while (it.hasNext()) { 11893 ReceiverList r = (ReceiverList)it.next(); 11894 if (dumpPackage != null && (r.app == null || 11895 !dumpPackage.equals(r.app.info.packageName))) { 11896 continue; 11897 } 11898 if (filteredUid != Process.INVALID_UID && filteredUid != r.app.uid) { 11899 if (DEBUG_BROADCAST) { 11900 Slogf.v(TAG_BROADCAST, "dumpBroadcastsLocked(): skipping receiver whose" 11901 + " uid (%d) is not %d: %s", r.app.uid, filteredUid, r.app); 11902 } 11903 continue; 11904 } 11905 if (!printed) { 11906 pw.println(" Registered Receivers:"); 11907 needSep = true; 11908 printed = true; 11909 printedAnything = true; 11910 } 11911 pw.print(" * "); pw.println(r); 11912 r.dump(pw, " "); 11913 } 11914 } else { 11915 if (onlyReceivers) { 11916 pw.println(" (no registered receivers)"); 11917 } 11918 } 11919 11920 if (!onlyReceivers) { 11921 if (mReceiverResolver.dump(pw, needSep 11922 ? "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 11923 " ", dumpPackage, false, false)) { 11924 needSep = true; 11925 printedAnything = true; 11926 } 11927 } 11928 } 11929 11930 if (!onlyReceivers) { 11931 needSep = mBroadcastQueue.dumpLocked(fd, pw, args, opti, 11932 dumpConstants, dumpHistory, dumpAll, dumpPackage, needSep); 11933 printedAnything |= needSep; 11934 } 11935 11936 needSep = true; 11937 11938 synchronized (mStickyBroadcasts) { 11939 if (!onlyHistory && !onlyReceivers && mStickyBroadcasts != null 11940 && dumpPackage == null) { 11941 for (int user = 0; user < mStickyBroadcasts.size(); user++) { 11942 if (needSep) { 11943 pw.println(); 11944 } 11945 needSep = true; 11946 printedAnything = true; 11947 pw.print(" Sticky broadcasts for user "); 11948 pw.print(mStickyBroadcasts.keyAt(user)); 11949 pw.println(":"); 11950 StringBuilder sb = new StringBuilder(128); 11951 for (Map.Entry<String, ArrayList<StickyBroadcast>> ent 11952 : mStickyBroadcasts.valueAt(user).entrySet()) { 11953 pw.print(" * Sticky action "); 11954 pw.print(ent.getKey()); 11955 if (dumpAll) { 11956 pw.println(":"); 11957 ArrayList<StickyBroadcast> broadcasts = ent.getValue(); 11958 final int N = broadcasts.size(); 11959 for (int i = 0; i < N; i++) { 11960 final Intent intent = broadcasts.get(i).intent; 11961 final boolean deferUntilActive = broadcasts.get(i).deferUntilActive; 11962 sb.setLength(0); 11963 sb.append(" Intent: "); 11964 intent.toShortString(sb, false, true, false, false); 11965 pw.print(sb); 11966 if (deferUntilActive) { 11967 pw.print(" [D]"); 11968 } 11969 pw.println(); 11970 pw.print(" originalCallingUid: "); 11971 pw.println(broadcasts.get(i).originalCallingUid); 11972 pw.println(); 11973 Bundle bundle = intent.getExtras(); 11974 if (bundle != null) { 11975 pw.print(" extras: "); 11976 pw.println(bundle); 11977 } 11978 } 11979 } else { 11980 pw.println(""); 11981 } 11982 } 11983 } 11984 } 11985 } 11986 11987 if (!onlyHistory && !onlyReceivers && dumpAll) { 11988 pw.println(); 11989 pw.println(" Queue " + mBroadcastQueue.toString() + ": " 11990 + mBroadcastQueue.describeStateLocked()); 11991 pw.println(" mHandler:"); 11992 mHandler.dump(new PrintWriterPrinter(pw), " "); 11993 needSep = true; 11994 printedAnything = true; 11995 } 11996 11997 if (!printedAnything) { 11998 pw.println(" (nothing)"); 11999 } 12000 } 12001 12002 @NeverCompile dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)12003 void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12004 int opti, boolean dumpAll, String dumpPackage) { 12005 if (mCurBroadcastStats == null) { 12006 return; 12007 } 12008 12009 pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)"); 12010 final long now = SystemClock.elapsedRealtime(); 12011 if (mLastBroadcastStats != null) { 12012 pw.print(" Last stats (from "); 12013 TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw); 12014 pw.print(" to "); 12015 TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw); 12016 pw.print(", "); 12017 TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime 12018 - mLastBroadcastStats.mStartUptime, pw); 12019 pw.println(" uptime):"); 12020 if (!mLastBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 12021 pw.println(" (nothing)"); 12022 } 12023 pw.println(); 12024 } 12025 pw.print(" Current stats (from "); 12026 TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw); 12027 pw.print(" to now, "); 12028 TimeUtils.formatDuration(SystemClock.uptimeMillis() 12029 - mCurBroadcastStats.mStartUptime, pw); 12030 pw.println(" uptime):"); 12031 if (!mCurBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 12032 pw.println(" (nothing)"); 12033 } 12034 } 12035 12036 @NeverCompile dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)12037 void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12038 int opti, boolean fullCheckin, String dumpPackage) { 12039 if (mCurBroadcastStats == null) { 12040 return; 12041 } 12042 12043 if (mLastBroadcastStats != null) { 12044 mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage); 12045 if (fullCheckin) { 12046 mLastBroadcastStats = null; 12047 return; 12048 } 12049 } 12050 mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage); 12051 if (fullCheckin) { 12052 mCurBroadcastStats = null; 12053 } 12054 } 12055 dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)12056 void dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, 12057 int opti, boolean dumpAll, String dumpPackage) { 12058 12059 pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)"); 12060 12061 mUgmInternal.dump(pw, dumpAll, dumpPackage); 12062 } 12063 dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)12064 private static int dumpProcessList(PrintWriter pw, 12065 ActivityManagerService service, List list, 12066 String prefix, String normalLabel, String persistentLabel, 12067 String dumpPackage) { 12068 int numPers = 0; 12069 for (int i = list.size() - 1; i >= 0; i--) { 12070 ProcessRecord r = (ProcessRecord) list.get(i); 12071 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 12072 continue; 12073 } 12074 pw.println(String.format("%s%s #%2d: %s", 12075 prefix, (r.isPersistent() ? persistentLabel : normalLabel), 12076 i, r.toString())); 12077 if (r.isPersistent()) { 12078 numPers++; 12079 } 12080 } 12081 return numPers; 12082 } 12083 collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)12084 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs, 12085 String[] args) { 12086 synchronized (mProcLock) { 12087 return mProcessList.collectProcessesLOSP(start, allPkgs, args); 12088 } 12089 } 12090 dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)12091 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 12092 PrintWriter pw, String[] args) { 12093 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 12094 if (procs == null) { 12095 pw.println("No process found for: " + args[0]); 12096 return; 12097 } 12098 12099 long uptime = SystemClock.uptimeMillis(); 12100 long realtime = SystemClock.elapsedRealtime(); 12101 pw.println("Applications Graphics Acceleration Info:"); 12102 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 12103 12104 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 12105 ProcessRecord r = procs.get(i); 12106 final int pid = r.getPid(); 12107 final IApplicationThread thread = r.getThread(); 12108 if (thread != null) { 12109 pw.println("\n** Graphics info for pid " + pid + " [" + r.processName + "] **"); 12110 pw.flush(); 12111 try { 12112 TransferPipe tp = new TransferPipe(); 12113 try { 12114 thread.dumpGfxInfo(tp.getWriteFd(), args); 12115 tp.go(fd); 12116 } finally { 12117 tp.kill(); 12118 } 12119 } catch (IOException e) { 12120 pw.println("Failure while dumping the app: " + r); 12121 pw.flush(); 12122 } catch (RemoteException e) { 12123 pw.println("Got a RemoteException while dumping the app " + r); 12124 pw.flush(); 12125 } 12126 } 12127 } 12128 } 12129 dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args)12130 final void dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args) { 12131 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 12132 if (procs == null) { 12133 pw.println("No process found for: " + args[0]); 12134 return; 12135 } 12136 12137 pw.println("Per-process Binder Cache Contents"); 12138 12139 for (int i = procs.size() - 1; i >= 0; i--) { 12140 ProcessRecord r = procs.get(i); 12141 final int pid = r.getPid(); 12142 final IApplicationThread thread = r.getThread(); 12143 if (thread != null) { 12144 pw.println("\n\n** Cache info for pid " + pid + " [" + r.processName + "] **"); 12145 pw.flush(); 12146 try { 12147 if (pid == Process.myPid()) { 12148 // Directly dump to target fd for local dump to avoid hang. 12149 try (ParcelFileDescriptor pfd = ParcelFileDescriptor.fromFd(fd.getInt$())) { 12150 thread.dumpCacheInfo(pfd, args); 12151 } 12152 continue; 12153 } 12154 TransferPipe tp = new TransferPipe(); 12155 try { 12156 thread.dumpCacheInfo(tp.getWriteFd(), args); 12157 tp.go(fd); 12158 } finally { 12159 tp.kill(); 12160 } 12161 } catch (IOException e) { 12162 pw.println("Failure while dumping the app " + r); 12163 pw.flush(); 12164 } catch (RemoteException e) { 12165 pw.println("Got a RemoteException while dumping the app " + r); 12166 pw.flush(); 12167 } 12168 } 12169 } 12170 } 12171 dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)12172 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 12173 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 12174 if (procs == null) { 12175 pw.println("No process found for: " + args[0]); 12176 return; 12177 } 12178 12179 pw.println("Applications Database Info:"); 12180 12181 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 12182 ProcessRecord r = procs.get(i); 12183 final int pid = r.getPid(); 12184 final IApplicationThread thread = r.getThread(); 12185 if (thread != null) { 12186 pw.println("\n** Database info for pid " + pid + " [" + r.processName + "] **"); 12187 pw.flush(); 12188 try { 12189 TransferPipe tp = new TransferPipe(); 12190 try { 12191 thread.dumpDbInfo(tp.getWriteFd(), args); 12192 tp.go(fd); 12193 } finally { 12194 tp.kill(); 12195 } 12196 } catch (IOException e) { 12197 pw.println("Failure while dumping the app: " + r); 12198 pw.flush(); 12199 } catch (RemoteException e) { 12200 pw.println("Got a RemoteException while dumping the app " + r); 12201 pw.flush(); 12202 } 12203 } 12204 } 12205 } 12206 12207 final static class MemItem { 12208 final boolean isProc; 12209 final String label; 12210 final String shortLabel; 12211 final long pss; 12212 final long swapPss; 12213 final long mRss; 12214 final long mPrivateDirty; 12215 final int id; // pid 12216 final int userId; 12217 final boolean hasActivities; 12218 ArrayList<MemItem> subitems; 12219 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, long privateDirty, int id, @UserIdInt int userId, boolean hasActivities)12220 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, 12221 long privateDirty, int id, @UserIdInt int userId, 12222 boolean hasActivities) { 12223 this.isProc = true; 12224 this.label = label; 12225 this.shortLabel = shortLabel; 12226 this.pss = pss; 12227 this.swapPss = swapPss; 12228 this.mRss = rss; 12229 this.mPrivateDirty = privateDirty; 12230 this.id = id; 12231 this.userId = userId; 12232 this.hasActivities = hasActivities; 12233 } 12234 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, long privateDirty, int id)12235 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, 12236 long privateDirty, int id) { 12237 this.isProc = false; 12238 this.label = label; 12239 this.shortLabel = shortLabel; 12240 this.pss = pss; 12241 this.swapPss = swapPss; 12242 this.mRss = rss; 12243 this.mPrivateDirty = privateDirty; 12244 this.id = id; 12245 this.userId = UserHandle.USER_SYSTEM; 12246 this.hasActivities = false; 12247 } 12248 } 12249 sortMemItems(List<MemItem> items, final boolean pss)12250 private static void sortMemItems(List<MemItem> items, final boolean pss) { 12251 Collections.sort(items, new Comparator<MemItem>() { 12252 @Override 12253 public int compare(MemItem lhs, MemItem rhs) { 12254 long lss = pss ? lhs.pss : lhs.mRss; 12255 long rss = pss ? rhs.pss : rhs.mRss; 12256 if (lss < rss) { 12257 return 1; 12258 } else if (lss > rss) { 12259 return -1; 12260 } 12261 return 0; 12262 } 12263 }); 12264 } 12265 dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, boolean dumpSwapPss, boolean dumpPrivateDirty)12266 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 12267 ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, 12268 boolean dumpSwapPss, boolean dumpPrivateDirty) { 12269 if (sort && !isCompact) { 12270 sortMemItems(items, dumpPss); 12271 } 12272 12273 for (int i=0; i<items.size(); i++) { 12274 MemItem mi = items.get(i); 12275 if (!isCompact) { 12276 String printFormat = "%s%s: %s%s\n"; 12277 if ((dumpPss && dumpSwapPss) || dumpPrivateDirty) { 12278 StringBuilder format = new StringBuilder(); 12279 format.append("%s%s: %-60s%s"); 12280 if (dumpSwapPss) { 12281 format.append(String.format("(%s in swap%s", stringifyKBSize(mi.swapPss), 12282 dumpPrivateDirty ? ", " : ")")); 12283 } 12284 if (dumpPrivateDirty) { 12285 format.append(String.format("%s%s private dirty)", dumpSwapPss ? "" : "(", 12286 stringifyKBSize(mi.mPrivateDirty))); 12287 } 12288 printFormat = format.append("\n").toString(); 12289 } 12290 pw.printf(printFormat, prefix, stringifyKBSize(dumpPss ? mi.pss : mi.mRss), 12291 mi.label, 12292 mi.userId != UserHandle.USER_SYSTEM ? " (user " + mi.userId + ")" : ""); 12293 } else if (mi.isProc) { 12294 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 12295 pw.print(","); pw.print(mi.id); pw.print(","); 12296 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(","); 12297 pw.print(dumpSwapPss ? mi.swapPss : "N/A"); 12298 pw.println(mi.hasActivities ? ",a" : ",e"); 12299 } else { 12300 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 12301 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(","); 12302 pw.println(dumpSwapPss ? mi.swapPss : "N/A"); 12303 } 12304 if (mi.subitems != null) { 12305 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 12306 true, isCompact, dumpPss, dumpSwapPss, dumpPrivateDirty); 12307 } 12308 } 12309 } 12310 dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss)12311 static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, 12312 ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss) { 12313 if (sort) { 12314 sortMemItems(items, dumpPss); 12315 } 12316 12317 for (int i=0; i<items.size(); i++) { 12318 MemItem mi = items.get(i); 12319 final long token = proto.start(fieldId); 12320 12321 proto.write(MemInfoDumpProto.MemItem.TAG, tag); 12322 proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel); 12323 proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc); 12324 proto.write(MemInfoDumpProto.MemItem.ID, mi.id); 12325 proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities); 12326 proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss); 12327 proto.write(MemInfoDumpProto.MemItem.RSS_KB, mi.mRss); 12328 if (dumpSwapPss) { 12329 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss); 12330 } 12331 if (mi.subitems != null) { 12332 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems, 12333 true, dumpPss, dumpSwapPss); 12334 } 12335 proto.end(token); 12336 } 12337 } 12338 12339 // These are in KB. 12340 static final long[] DUMP_MEM_BUCKETS = new long[] { 12341 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 12342 120*1024, 160*1024, 200*1024, 12343 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 12344 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 12345 }; 12346 appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)12347 static final void appendMemBucket(StringBuilder out, long memKB, String label, 12348 boolean stackLike) { 12349 int start = label.lastIndexOf('.'); 12350 if (start >= 0) start++; 12351 else start = 0; 12352 int end = label.length(); 12353 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 12354 if (DUMP_MEM_BUCKETS[i] >= memKB) { 12355 long bucket = DUMP_MEM_BUCKETS[i]/1024; 12356 out.append(bucket); 12357 out.append(stackLike ? "MB." : "MB "); 12358 out.append(label, start, end); 12359 return; 12360 } 12361 } 12362 out.append(memKB/1024); 12363 out.append(stackLike ? "MB." : "MB "); 12364 out.append(label, start, end); 12365 } 12366 12367 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 12368 ProcessList.NATIVE_ADJ, 12369 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, 12370 ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ, 12371 ProcessList.VISIBLE_APP_ADJ, 12372 ProcessList.PERCEPTIBLE_APP_ADJ, 12373 ProcessList.PERCEPTIBLE_MEDIUM_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ, 12374 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 12375 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 12376 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ 12377 }; 12378 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 12379 "Native", 12380 "System", "Persistent", "Persistent Service", "Foreground", 12381 "Visible", "Perceptible", "Perceptible Medium", "Perceptible Low", 12382 "Backup", "Heavy Weight", 12383 "A Services", "Home", 12384 "Previous", "B Services", "Cached" 12385 }; 12386 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 12387 "native", 12388 "sys", "pers", "persvc", "fore", 12389 "vis", "percept", "perceptm", "perceptl", 12390 "backup", "heavy", 12391 "servicea", "home", 12392 "prev", "serviceb", "cached" 12393 }; 12394 dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)12395 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 12396 long realtime, boolean isCheckinRequest, boolean isCompact) { 12397 if (isCompact) { 12398 pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION); 12399 } 12400 if (isCheckinRequest || isCompact) { 12401 // short checkin version 12402 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 12403 } else { 12404 pw.println("Applications Memory Usage (in Kilobytes):"); 12405 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 12406 } 12407 } 12408 12409 static final int KSM_SHARED = 0; 12410 static final int KSM_SHARING = 1; 12411 static final int KSM_UNSHARED = 2; 12412 static final int KSM_VOLATILE = 3; 12413 getKsmInfo()12414 static final long[] getKsmInfo() { 12415 long[] longOut = new long[4]; 12416 final int[] SINGLE_LONG_FORMAT = new int[] { 12417 PROC_SPACE_TERM| PROC_OUT_LONG 12418 }; 12419 long[] longTmp = new long[1]; 12420 readProcFile("/sys/kernel/mm/ksm/pages_shared", 12421 SINGLE_LONG_FORMAT, null, longTmp, null); 12422 longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12423 longTmp[0] = 0; 12424 readProcFile("/sys/kernel/mm/ksm/pages_sharing", 12425 SINGLE_LONG_FORMAT, null, longTmp, null); 12426 longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12427 longTmp[0] = 0; 12428 readProcFile("/sys/kernel/mm/ksm/pages_unshared", 12429 SINGLE_LONG_FORMAT, null, longTmp, null); 12430 longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12431 longTmp[0] = 0; 12432 readProcFile("/sys/kernel/mm/ksm/pages_volatile", 12433 SINGLE_LONG_FORMAT, null, longTmp, null); 12434 longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12435 return longOut; 12436 } 12437 stringifySize(long size, int order)12438 static String stringifySize(long size, int order) { 12439 Locale locale = Locale.US; 12440 switch (order) { 12441 case 1: 12442 return String.format(locale, "%,13d", size); 12443 case 1024: 12444 return String.format(locale, "%,9dK", size / 1024); 12445 case 1024 * 1024: 12446 return String.format(locale, "%,5dM", size / 1024 / 1024); 12447 case 1024 * 1024 * 1024: 12448 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024); 12449 default: 12450 throw new IllegalArgumentException("Invalid size order"); 12451 } 12452 } 12453 stringifyKBSize(long size)12454 static String stringifyKBSize(long size) { 12455 return stringifySize(size * 1024, 1024); 12456 } 12457 12458 // Update this version number if you change the 'compact' format. 12459 private static final int MEMINFO_COMPACT_VERSION = 1; 12460 12461 private static class MemoryUsageDumpOptions { 12462 boolean dumpDetails; 12463 boolean dumpFullDetails; 12464 boolean dumpDalvik; 12465 boolean dumpSummaryOnly; 12466 boolean dumpUnreachable; 12467 boolean oomOnly; 12468 boolean isCompact; 12469 boolean localOnly; 12470 boolean packages; 12471 boolean isCheckinRequest; 12472 boolean dumpSwapPss; 12473 boolean dumpProto; 12474 boolean mDumpPrivateDirty; 12475 boolean mDumpAllocatorStats; 12476 } 12477 12478 @NeverCompile // Avoid size overhead of debugging code. dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)12479 final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 12480 String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) { 12481 MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions(); 12482 opts.dumpDetails = false; 12483 opts.dumpFullDetails = false; 12484 opts.dumpDalvik = false; 12485 opts.dumpSummaryOnly = false; 12486 opts.dumpUnreachable = false; 12487 opts.oomOnly = false; 12488 opts.isCompact = false; 12489 opts.localOnly = false; 12490 opts.packages = false; 12491 opts.isCheckinRequest = false; 12492 opts.dumpSwapPss = false; 12493 opts.dumpProto = asProto; 12494 opts.mDumpPrivateDirty = false; 12495 opts.mDumpAllocatorStats = false; 12496 12497 int opti = 0; 12498 while (opti < args.length) { 12499 String opt = args[opti]; 12500 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12501 break; 12502 } 12503 opti++; 12504 if ("-a".equals(opt)) { 12505 opts.dumpDetails = true; 12506 opts.dumpFullDetails = true; 12507 opts.dumpDalvik = true; 12508 opts.dumpSwapPss = true; 12509 } else if ("-d".equals(opt)) { 12510 opts.dumpDalvik = true; 12511 } else if ("-c".equals(opt)) { 12512 opts.isCompact = true; 12513 } else if ("-s".equals(opt)) { 12514 opts.dumpDetails = true; 12515 opts.dumpSummaryOnly = true; 12516 } else if ("-S".equals(opt)) { 12517 opts.dumpSwapPss = true; 12518 } else if ("-p".equals(opt)) { 12519 opts.mDumpPrivateDirty = true; 12520 } else if ("--unreachable".equals(opt)) { 12521 opts.dumpUnreachable = true; 12522 } else if ("--oom".equals(opt)) { 12523 opts.oomOnly = true; 12524 } else if ("--local".equals(opt)) { 12525 opts.localOnly = true; 12526 } else if ("--package".equals(opt)) { 12527 opts.packages = true; 12528 } else if ("--checkin".equals(opt)) { 12529 opts.isCheckinRequest = true; 12530 } else if ("--proto".equals(opt)) { 12531 opts.dumpProto = true; 12532 } else if ("--logstats".equals(opt)) { 12533 opts.mDumpAllocatorStats = true; 12534 } else if ("-h".equals(opt)) { 12535 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]"); 12536 pw.println(" -a: include all available information for each process."); 12537 pw.println(" -d: include dalvik details."); 12538 pw.println(" -c: dump in a compact machine-parseable representation."); 12539 pw.println(" -s: dump only summary of application memory usage."); 12540 pw.println(" -S: dump also SwapPss."); 12541 pw.println(" -p: dump also private dirty memory usage."); 12542 pw.println(" --oom: only show processes organized by oom adj."); 12543 pw.println(" --local: only collect details locally, don't call process."); 12544 pw.println(" --package: interpret process arg as package, dumping all"); 12545 pw.println(" processes that have loaded that package."); 12546 pw.println(" --checkin: dump data for a checkin"); 12547 pw.println(" --proto: dump data to proto"); 12548 pw.println("If [process] is specified it can be the name or "); 12549 pw.println("pid of a specific process to dump."); 12550 return; 12551 } else { 12552 pw.println("Unknown argument: " + opt + "; use -h for help"); 12553 } 12554 } 12555 12556 String[] innerArgs = new String[args.length-opti]; 12557 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 12558 12559 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args); 12560 if (opts.dumpProto) { 12561 dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs); 12562 } else { 12563 dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw); 12564 } 12565 } 12566 12567 @NeverCompile // Avoid size overhead of debugging code. dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs, PrintWriter categoryPw)12568 private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 12569 MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, 12570 ArrayList<ProcessRecord> procs, PrintWriter categoryPw) { 12571 long uptime = SystemClock.uptimeMillis(); 12572 long realtime = SystemClock.elapsedRealtime(); 12573 final long[] tmpLong = new long[3]; 12574 12575 if (procs == null) { 12576 // No Java processes. Maybe they want to print a native process. 12577 String proc = "N/A"; 12578 if (innerArgs.length > 0) { 12579 proc = innerArgs[0]; 12580 if (proc.charAt(0) != '-') { 12581 ArrayList<ProcessCpuTracker.Stats> nativeProcs 12582 = new ArrayList<ProcessCpuTracker.Stats>(); 12583 updateCpuStatsNow(); 12584 int findPid = -1; 12585 try { 12586 findPid = Integer.parseInt(innerArgs[0]); 12587 } catch (NumberFormatException e) { 12588 } 12589 final int fFindPid = findPid; 12590 mAppProfiler.forAllCpuStats((st) -> { 12591 if (st.pid == fFindPid || (st.baseName != null 12592 && st.baseName.equals(innerArgs[0]))) { 12593 nativeProcs.add(st); 12594 } 12595 }); 12596 if (nativeProcs.size() > 0) { 12597 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, 12598 opts.isCheckinRequest, opts.isCompact); 12599 Debug.MemoryInfo mi = null; 12600 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 12601 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 12602 final int pid = r.pid; 12603 if (mi == null) { 12604 mi = new Debug.MemoryInfo(); 12605 } 12606 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 12607 if (!Debug.getMemoryInfo(pid, mi)) { 12608 continue; 12609 } 12610 } else { 12611 long pss = Debug.getPss(pid, tmpLong, null); 12612 if (pss == 0) { 12613 continue; 12614 } 12615 mi.nativePss = (int) pss; 12616 mi.nativePrivateDirty = (int) tmpLong[0]; 12617 mi.nativeRss = (int) tmpLong[2]; 12618 } 12619 if (!opts.isCheckinRequest && opts.dumpDetails) { 12620 pw.println("\n** MEMINFO in pid " + pid + " [" 12621 + r.baseName + "] **"); 12622 } 12623 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, 12624 opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 12625 pid, r.baseName, 0, 0, 0, 0, 0, 0); 12626 if (opts.isCheckinRequest) { 12627 pw.println(); 12628 } 12629 } 12630 return; 12631 } 12632 } 12633 } 12634 pw.println("No process found for: " + proc); 12635 return; 12636 } 12637 12638 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 12639 opts.dumpDetails = true; 12640 } 12641 final int numProcs = procs.size(); 12642 final boolean collectNative = !opts.isCheckinRequest && numProcs > 1 && !opts.packages; 12643 if (collectNative) { 12644 // If we are showing aggregations, also look for native processes to 12645 // include so that our aggregations are more accurate. 12646 updateCpuStatsNow(); 12647 } 12648 12649 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact); 12650 12651 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 12652 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 12653 final long[] ss = new long[INDEX_LAST]; 12654 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12655 EmptyArray.LONG; 12656 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12657 EmptyArray.LONG; 12658 long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12659 EmptyArray.LONG; 12660 long[] dalvikSubitemPrivateDirty = opts.dumpDalvik 12661 ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : EmptyArray.LONG; 12662 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12663 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12664 long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12665 long[] miscPrivateDirty = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12666 long[] memtrackTmp = new long[4]; 12667 12668 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 12669 long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 12670 long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length]; 12671 long[] oomPrivateDirty = new long[DUMP_MEM_OOM_LABEL.length]; 12672 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 12673 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 12674 12675 long totalSwapPss = 0; 12676 long totalRss = 0; 12677 long cachedPss = 0; 12678 long cachedSwapPss = 0; 12679 boolean hasSwapPss = false; 12680 12681 Debug.MemoryInfo mi = null; 12682 for (int i = numProcs - 1; i >= 0; i--) { 12683 final ProcessRecord r = procs.get(i); 12684 final IApplicationThread thread; 12685 final int pid; 12686 final int oomAdj; 12687 final boolean hasActivities; 12688 synchronized (mProcLock) { 12689 thread = r.getThread(); 12690 pid = r.getPid(); 12691 oomAdj = r.mState.getSetAdjWithServices(); 12692 hasActivities = r.hasActivities(); 12693 } 12694 if (thread != null) { 12695 if (mi == null) { 12696 mi = new Debug.MemoryInfo(); 12697 } 12698 final int reportType; 12699 final long startTime; 12700 final long endTime; 12701 long memtrackGraphics = 0; 12702 long memtrackGl = 0; 12703 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 12704 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 12705 startTime = SystemClock.currentThreadTimeMillis(); 12706 if (!Debug.getMemoryInfo(pid, mi)) { 12707 continue; 12708 } 12709 endTime = SystemClock.currentThreadTimeMillis(); 12710 hasSwapPss = mi.hasSwappedOutPss; 12711 memtrackGraphics = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS); 12712 memtrackGl = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GL); 12713 } else { 12714 reportType = ProcessStats.ADD_PSS_EXTERNAL; 12715 startTime = SystemClock.currentThreadTimeMillis(); 12716 long pss = Debug.getPss(pid, tmpLong, memtrackTmp); 12717 if (pss == 0) { 12718 continue; 12719 } 12720 mi.dalvikPss = (int) pss; 12721 endTime = SystemClock.currentThreadTimeMillis(); 12722 mi.dalvikPrivateDirty = (int) tmpLong[0]; 12723 mi.dalvikRss = (int) tmpLong[2]; 12724 memtrackGraphics = memtrackTmp[1]; 12725 memtrackGl = memtrackTmp[2]; 12726 } 12727 if (!opts.isCheckinRequest && opts.dumpDetails) { 12728 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 12729 } 12730 if (opts.dumpDetails) { 12731 if (opts.localOnly) { 12732 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails, 12733 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0); 12734 if (opts.isCheckinRequest) { 12735 pw.println(); 12736 } 12737 } else { 12738 pw.flush(); 12739 try { 12740 TransferPipe tp = new TransferPipe(); 12741 try { 12742 thread.dumpMemInfo(tp.getWriteFd(), 12743 mi, opts.isCheckinRequest, opts.dumpFullDetails, 12744 opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, 12745 opts.mDumpAllocatorStats, innerArgs); 12746 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000); 12747 } finally { 12748 tp.kill(); 12749 } 12750 } catch (IOException e) { 12751 if (!opts.isCheckinRequest) { 12752 pw.println("Got IoException! " + e); 12753 pw.flush(); 12754 } 12755 } catch (RemoteException e) { 12756 if (!opts.isCheckinRequest) { 12757 pw.println("Got RemoteException! " + e); 12758 pw.flush(); 12759 } 12760 } 12761 } 12762 } 12763 12764 final long myTotalPss = mi.getTotalPss(); 12765 final long myTotalUss = mi.getTotalUss(); 12766 final long myTotalRss = mi.getTotalRss(); 12767 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 12768 final long myTotalPrivateDirty = mi.getTotalPrivateDirty(); 12769 12770 synchronized (mProcLock) { 12771 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) { 12772 // Record this for posterity if the process has been stable. 12773 r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true, 12774 reportType, endTime - startTime); 12775 } 12776 } 12777 12778 if (!opts.isCheckinRequest && mi != null) { 12779 ss[INDEX_TOTAL_PSS] += myTotalPss; 12780 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 12781 ss[INDEX_TOTAL_RSS] += myTotalRss; 12782 ss[INDEX_TOTAL_PRIVATE_DIRTY] += myTotalPrivateDirty; 12783 ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics; 12784 ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl; 12785 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 12786 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 12787 myTotalSwapPss, myTotalRss, myTotalPrivateDirty, 12788 pid, r.userId, hasActivities); 12789 procMems.add(pssItem); 12790 procMemsMap.put(pid, pssItem); 12791 12792 ss[INDEX_NATIVE_PSS] += mi.nativePss; 12793 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss; 12794 ss[INDEX_NATIVE_RSS] += mi.nativeRss; 12795 ss[INDEX_NATIVE_PRIVATE_DIRTY] += mi.nativePrivateDirty; 12796 ss[INDEX_DALVIK_PSS] += mi.dalvikPss; 12797 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss; 12798 ss[INDEX_DALVIK_RSS] += mi.dalvikRss; 12799 ss[INDEX_DALVIK_PRIVATE_DIRTY] += mi.dalvikPrivateDirty; 12800 for (int j=0; j<dalvikSubitemPss.length; j++) { 12801 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12802 dalvikSubitemSwapPss[j] += 12803 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12804 dalvikSubitemPrivateDirty[j] += 12805 mi.getOtherPrivateDirty(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12806 dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12807 } 12808 ss[INDEX_OTHER_PSS] += mi.otherPss; 12809 ss[INDEX_OTHER_RSS] += mi.otherRss; 12810 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss; 12811 ss[INDEX_OTHER_PRIVATE_DIRTY] += mi.otherPrivateDirty; 12812 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12813 long mem = mi.getOtherPss(j); 12814 miscPss[j] += mem; 12815 ss[INDEX_OTHER_PSS] -= mem; 12816 mem = mi.getOtherSwappedOutPss(j); 12817 miscSwapPss[j] += mem; 12818 ss[INDEX_OTHER_SWAP_PSS] -= mem; 12819 mem = mi.getOtherPrivateDirty(j); 12820 miscPrivateDirty[j] += mem; 12821 ss[INDEX_OTHER_PRIVATE_DIRTY] -= mem; 12822 mem = mi.getOtherRss(j); 12823 miscRss[j] += mem; 12824 ss[INDEX_OTHER_RSS] -= mem; 12825 } 12826 12827 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 12828 cachedPss += myTotalPss; 12829 cachedSwapPss += myTotalSwapPss; 12830 } 12831 12832 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 12833 if (oomIndex == (oomPss.length - 1) 12834 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 12835 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 12836 oomPss[oomIndex] += myTotalPss; 12837 oomSwapPss[oomIndex] += myTotalSwapPss; 12838 oomPrivateDirty[oomIndex] += myTotalPrivateDirty; 12839 if (oomProcs[oomIndex] == null) { 12840 oomProcs[oomIndex] = new ArrayList<MemItem>(); 12841 } 12842 oomProcs[oomIndex].add(pssItem); 12843 oomRss[oomIndex] += myTotalRss; 12844 break; 12845 } 12846 } 12847 } 12848 } 12849 } 12850 12851 long nativeProcTotalPss = 0; 12852 12853 if (collectNative) { 12854 mi = null; 12855 final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1]; 12856 mAppProfiler.forAllCpuStats((st) -> { 12857 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 12858 long memtrackGraphics = 0; 12859 long memtrackGl = 0; 12860 if (memInfos[0] == null) { 12861 memInfos[0] = new Debug.MemoryInfo(); 12862 } 12863 final Debug.MemoryInfo info = memInfos[0]; 12864 if (!brief && !opts.oomOnly) { 12865 if (!Debug.getMemoryInfo(st.pid, info)) { 12866 return; 12867 } 12868 memtrackGraphics = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS); 12869 memtrackGl = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GL); 12870 } else { 12871 long pss = Debug.getPss(st.pid, tmpLong, memtrackTmp); 12872 if (pss == 0) { 12873 return; 12874 } 12875 info.nativePss = (int) pss; 12876 info.nativePrivateDirty = (int) tmpLong[0]; 12877 info.nativeRss = (int) tmpLong[2]; 12878 memtrackGraphics = memtrackTmp[1]; 12879 memtrackGl = memtrackTmp[2]; 12880 } 12881 12882 final long myTotalPss = info.getTotalPss(); 12883 final long myTotalSwapPss = info.getTotalSwappedOutPss(); 12884 final long myTotalRss = info.getTotalRss(); 12885 final long myTotalPrivateDirty = info.getTotalPrivateDirty(); 12886 ss[INDEX_TOTAL_PSS] += myTotalPss; 12887 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 12888 ss[INDEX_TOTAL_RSS] += myTotalRss; 12889 ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss; 12890 ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics; 12891 ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl; 12892 12893 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 12894 st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss, 12895 myTotalPrivateDirty, st.pid, UserHandle.getUserId(st.uid), false); 12896 procMems.add(pssItem); 12897 12898 ss[INDEX_NATIVE_PSS] += info.nativePss; 12899 ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss; 12900 ss[INDEX_NATIVE_RSS] += info.nativeRss; 12901 ss[INDEX_NATIVE_PRIVATE_DIRTY] += info.nativePrivateDirty; 12902 ss[INDEX_DALVIK_PSS] += info.dalvikPss; 12903 ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss; 12904 ss[INDEX_DALVIK_RSS] += info.dalvikRss; 12905 ss[INDEX_DALVIK_PRIVATE_DIRTY] += info.dalvikPrivateDirty; 12906 for (int j = 0; j < dalvikSubitemPss.length; j++) { 12907 dalvikSubitemPss[j] += info.getOtherPss( 12908 Debug.MemoryInfo.NUM_OTHER_STATS + j); 12909 dalvikSubitemSwapPss[j] += 12910 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12911 dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS 12912 + j); 12913 dalvikSubitemPrivateDirty[j] += 12914 info.getOtherPrivateDirty(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12915 } 12916 ss[INDEX_OTHER_PSS] += info.otherPss; 12917 ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss; 12918 ss[INDEX_OTHER_RSS] += info.otherRss; 12919 ss[INDEX_OTHER_PRIVATE_DIRTY] += info.otherPrivateDirty; 12920 for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12921 long mem = info.getOtherPss(j); 12922 miscPss[j] += mem; 12923 ss[INDEX_OTHER_PSS] -= mem; 12924 mem = info.getOtherSwappedOutPss(j); 12925 miscSwapPss[j] += mem; 12926 ss[INDEX_OTHER_SWAP_PSS] -= mem; 12927 mem = info.getOtherRss(j); 12928 miscRss[j] += mem; 12929 ss[INDEX_OTHER_RSS] -= mem; 12930 mem = info.getOtherPrivateDirty(j); 12931 miscPrivateDirty[j] += mem; 12932 ss[INDEX_OTHER_PRIVATE_DIRTY] -= mem; 12933 } 12934 oomPss[0] += myTotalPss; 12935 oomSwapPss[0] += myTotalSwapPss; 12936 if (oomProcs[0] == null) { 12937 oomProcs[0] = new ArrayList<MemItem>(); 12938 } 12939 oomProcs[0].add(pssItem); 12940 oomRss[0] += myTotalRss; 12941 oomPrivateDirty[0] += myTotalPrivateDirty; 12942 } 12943 }); 12944 12945 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 12946 12947 catMems.add(new MemItem("Native", "Native", 12948 ss[INDEX_NATIVE_PSS], ss[INDEX_NATIVE_SWAP_PSS], 12949 ss[INDEX_NATIVE_RSS], ss[INDEX_NATIVE_PRIVATE_DIRTY], -1)); 12950 final int dalvikId = -2; 12951 catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS], 12952 ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], 12953 ss[INDEX_DALVIK_PRIVATE_DIRTY], dalvikId)); 12954 catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS], 12955 ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], 12956 ss[INDEX_OTHER_PRIVATE_DIRTY], -3)); 12957 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12958 String label = Debug.MemoryInfo.getOtherLabel(j); 12959 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], 12960 miscPrivateDirty[j], j)); 12961 } 12962 if (dalvikSubitemPss.length > 0) { 12963 // Add dalvik subitems. 12964 for (MemItem memItem : catMems) { 12965 int memItemStart = 0, memItemEnd = 0; 12966 if (memItem.id == dalvikId) { 12967 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 12968 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 12969 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 12970 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 12971 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 12972 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 12973 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 12974 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 12975 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 12976 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 12977 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 12978 } else { 12979 continue; // No subitems, continue. 12980 } 12981 memItem.subitems = new ArrayList<MemItem>(); 12982 for (int j=memItemStart; j<=memItemEnd; j++) { 12983 final String name = Debug.MemoryInfo.getOtherLabel( 12984 Debug.MemoryInfo.NUM_OTHER_STATS + j); 12985 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 12986 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], 12987 dalvikSubitemPrivateDirty[j], j)); 12988 } 12989 } 12990 } 12991 12992 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 12993 for (int j=0; j<oomPss.length; j++) { 12994 if (oomPss[j] != 0) { 12995 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 12996 : DUMP_MEM_OOM_LABEL[j]; 12997 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j], 12998 oomPrivateDirty[j], DUMP_MEM_OOM_ADJ[j]); 12999 item.subitems = oomProcs[j]; 13000 oomMems.add(item); 13001 } 13002 } 13003 if (!opts.isCompact) { 13004 pw.println(); 13005 } 13006 if (!brief && !opts.oomOnly && !opts.isCompact) { 13007 pw.println(); 13008 pw.println("Total RSS by process:"); 13009 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, false, false, false); 13010 pw.println(); 13011 } 13012 if (!opts.isCompact) { 13013 pw.println("Total RSS by OOM adjustment:"); 13014 } 13015 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, false, false, false); 13016 if (!brief && !opts.oomOnly) { 13017 PrintWriter out = categoryPw != null ? categoryPw : pw; 13018 if (!opts.isCompact) { 13019 out.println(); 13020 out.println("Total RSS by category:"); 13021 } 13022 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, false, false, false); 13023 } 13024 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0; 13025 if (!brief && !opts.oomOnly && !opts.isCompact) { 13026 pw.println(); 13027 pw.println("Total PSS by process:"); 13028 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, true, 13029 opts.dumpSwapPss, opts.mDumpPrivateDirty); 13030 pw.println(); 13031 } 13032 if (!opts.isCompact) { 13033 pw.println("Total PSS by OOM adjustment:"); 13034 } 13035 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, true, opts.dumpSwapPss, 13036 opts.mDumpPrivateDirty); 13037 if (!brief && !opts.oomOnly) { 13038 PrintWriter out = categoryPw != null ? categoryPw : pw; 13039 if (!opts.isCompact) { 13040 out.println(); 13041 out.println("Total PSS by category:"); 13042 } 13043 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, true, 13044 opts.dumpSwapPss, opts.mDumpPrivateDirty); 13045 } 13046 if (!opts.isCompact) { 13047 pw.println(); 13048 } 13049 MemInfoReader memInfo = new MemInfoReader(); 13050 memInfo.readMemInfo(); 13051 if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) { 13052 synchronized (mProcessStats.mLock) { 13053 final long cachedKb = memInfo.getCachedSizeKb(); 13054 final long freeKb = memInfo.getFreeSizeKb(); 13055 final long zramKb = memInfo.getZramTotalSizeKb(); 13056 final long kernelKb = memInfo.getKernelUsedSizeKb(); 13057 EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, 13058 kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024); 13059 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 13060 ss[INDEX_TOTAL_NATIVE_PSS]); 13061 } 13062 } 13063 if (!brief) { 13064 if (!opts.isCompact) { 13065 pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb())); 13066 pw.print(" (status "); 13067 mAppProfiler.dumpLastMemoryLevelLocked(pw); 13068 pw.print(" Free RAM: "); 13069 pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb() 13070 + memInfo.getFreeSizeKb())); 13071 pw.print(" ("); 13072 pw.print(stringifyKBSize(cachedPss)); 13073 pw.print(" cached pss + "); 13074 pw.print(stringifyKBSize(memInfo.getCachedSizeKb())); 13075 pw.print(" cached kernel + "); 13076 pw.print(stringifyKBSize(memInfo.getFreeSizeKb())); 13077 pw.println(" free)"); 13078 } else { 13079 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 13080 pw.print(cachedPss + memInfo.getCachedSizeKb() 13081 + memInfo.getFreeSizeKb()); pw.print(","); 13082 pw.println(ss[INDEX_TOTAL_PSS] - cachedPss); 13083 } 13084 } 13085 long kernelUsed = memInfo.getKernelUsedSizeKb(); 13086 final long ionHeap = Debug.getIonHeapsSizeKb(); 13087 final long ionPool = Debug.getIonPoolsSizeKb(); 13088 final long dmabufMapped = Debug.getDmabufMappedSizeKb(); 13089 if (ionHeap >= 0 && ionPool >= 0) { 13090 final long ionUnmapped = ionHeap - dmabufMapped; 13091 pw.print(" ION: "); 13092 pw.print(stringifyKBSize(ionHeap + ionPool)); 13093 pw.print(" ("); 13094 pw.print(stringifyKBSize(dmabufMapped)); 13095 pw.print(" mapped + "); 13096 pw.print(stringifyKBSize(ionUnmapped)); 13097 pw.print(" unmapped + "); 13098 pw.print(stringifyKBSize(ionPool)); 13099 pw.println(" pools)"); 13100 kernelUsed += ionUnmapped; 13101 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being 13102 // set on ION VMAs, however it might be included by the memtrack HAL. 13103 // Replace memtrack HAL reported Graphics category with mapped dmabufs 13104 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS]; 13105 ss[INDEX_TOTAL_PSS] += dmabufMapped; 13106 } else { 13107 final long totalExportedDmabuf = Debug.getDmabufTotalExportedKb(); 13108 if (totalExportedDmabuf >= 0) { 13109 final long dmabufUnmapped = totalExportedDmabuf - dmabufMapped; 13110 pw.print("DMA-BUF: "); 13111 pw.print(stringifyKBSize(totalExportedDmabuf)); 13112 pw.print(" ("); 13113 pw.print(stringifyKBSize(dmabufMapped)); 13114 pw.print(" mapped + "); 13115 pw.print(stringifyKBSize(dmabufUnmapped)); 13116 pw.println(" unmapped)"); 13117 // Account unmapped dmabufs as part of kernel memory allocations 13118 kernelUsed += dmabufUnmapped; 13119 // Replace memtrack HAL reported Graphics category with mapped dmabufs 13120 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS]; 13121 ss[INDEX_TOTAL_PSS] += dmabufMapped; 13122 } 13123 13124 // totalDmabufHeapExported is included in totalExportedDmabuf above and hence do not 13125 // need to be added to kernelUsed. 13126 final long totalDmabufHeapExported = Debug.getDmabufHeapTotalExportedKb(); 13127 if (totalDmabufHeapExported >= 0) { 13128 pw.print("DMA-BUF Heaps: "); 13129 pw.println(stringifyKBSize(totalDmabufHeapExported)); 13130 } 13131 13132 final long totalDmabufHeapPool = Debug.getDmabufHeapPoolsSizeKb(); 13133 if (totalDmabufHeapPool >= 0) { 13134 pw.print("DMA-BUF Heaps pool: "); 13135 pw.println(stringifyKBSize(totalDmabufHeapPool)); 13136 } 13137 } 13138 final long gpuUsage = Debug.getGpuTotalUsageKb(); 13139 if (gpuUsage >= 0) { 13140 final long gpuPrivateUsage = Debug.getGpuPrivateMemoryKb(); 13141 if (gpuPrivateUsage >= 0) { 13142 final long gpuDmaBufUsage = gpuUsage - gpuPrivateUsage; 13143 pw.print(" GPU: "); 13144 pw.print(stringifyKBSize(gpuUsage)); 13145 pw.print(" ("); 13146 pw.print(stringifyKBSize(gpuDmaBufUsage)); 13147 pw.print(" dmabuf + "); 13148 pw.print(stringifyKBSize(gpuPrivateUsage)); 13149 pw.println(" private)"); 13150 // Replace memtrack HAL reported GL category with private GPU allocations and 13151 // account it as part of kernel memory allocations 13152 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GL]; 13153 kernelUsed += gpuPrivateUsage; 13154 } else { 13155 pw.print(" GPU: "); pw.println(stringifyKBSize(gpuUsage)); 13156 } 13157 } 13158 13159 // Note: ION/DMA-BUF heap pools are reclaimable and hence, they are included as part of 13160 // memInfo.getCachedSizeKb(). 13161 final long lostRAM = memInfo.getTotalSizeKb() 13162 - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS]) 13163 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 13164 - kernelUsed - memInfo.getZramTotalSizeKb(); 13165 if (!opts.isCompact) { 13166 pw.print(" Used RAM: "); pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss 13167 + kernelUsed)); pw.print(" ("); 13168 pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss)); 13169 pw.print(" used pss + "); 13170 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n"); 13171 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM)); 13172 } else { 13173 pw.print("lostram,"); pw.println(lostRAM); 13174 } 13175 if (!brief) { 13176 if (memInfo.getZramTotalSizeKb() != 0) { 13177 if (!opts.isCompact) { 13178 pw.print(" ZRAM: "); 13179 pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb())); 13180 pw.print(" physical used for "); 13181 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb() 13182 - memInfo.getSwapFreeSizeKb())); 13183 pw.print(" in swap ("); 13184 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb())); 13185 pw.println(" total swap)"); 13186 } else { 13187 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 13188 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 13189 pw.println(memInfo.getSwapFreeSizeKb()); 13190 } 13191 } 13192 final long[] ksm = getKsmInfo(); 13193 if (!opts.isCompact) { 13194 if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 13195 || ksm[KSM_VOLATILE] != 0) { 13196 pw.print(" KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING])); 13197 pw.print(" saved from shared "); 13198 pw.print(stringifyKBSize(ksm[KSM_SHARED])); 13199 pw.print(" "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED])); 13200 pw.print(" unshared; "); 13201 pw.print(stringifyKBSize( 13202 ksm[KSM_VOLATILE])); pw.println(" volatile"); 13203 } 13204 pw.print(" Tuning: "); 13205 pw.print(ActivityManager.staticGetMemoryClass()); 13206 pw.print(" (large "); 13207 pw.print(ActivityManager.staticGetLargeMemoryClass()); 13208 pw.print("), oom "); 13209 pw.print(stringifySize( 13210 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024)); 13211 pw.print(", restore limit "); 13212 pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb())); 13213 if (ActivityManager.isLowRamDeviceStatic()) { 13214 pw.print(" (low-ram)"); 13215 } 13216 if (ActivityManager.isHighEndGfx()) { 13217 pw.print(" (high-end-gfx)"); 13218 } 13219 pw.println(); 13220 } else { 13221 pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(","); 13222 pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]); 13223 pw.print(","); pw.println(ksm[KSM_VOLATILE]); 13224 pw.print("tuning,"); 13225 pw.print(ActivityManager.staticGetMemoryClass()); 13226 pw.print(','); 13227 pw.print(ActivityManager.staticGetLargeMemoryClass()); 13228 pw.print(','); 13229 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 13230 if (ActivityManager.isLowRamDeviceStatic()) { 13231 pw.print(",low-ram"); 13232 } 13233 if (ActivityManager.isHighEndGfx()) { 13234 pw.print(",high-end-gfx"); 13235 } 13236 pw.println(); 13237 } 13238 } 13239 } 13240 } 13241 13242 @NeverCompile // Avoid size overhead of debugging code. dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)13243 private final void dumpApplicationMemoryUsage(FileDescriptor fd, 13244 MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, 13245 ArrayList<ProcessRecord> procs) { 13246 final long uptimeMs = SystemClock.uptimeMillis(); 13247 final long realtimeMs = SystemClock.elapsedRealtime(); 13248 final long[] tmpLong = new long[3]; 13249 13250 if (procs == null) { 13251 // No Java processes. Maybe they want to print a native process. 13252 String proc = "N/A"; 13253 if (innerArgs.length > 0) { 13254 proc = innerArgs[0]; 13255 if (proc.charAt(0) != '-') { 13256 final ArrayList<ProcessCpuTracker.Stats> nativeProcs 13257 = new ArrayList<ProcessCpuTracker.Stats>(); 13258 updateCpuStatsNow(); 13259 int findPid = -1; 13260 try { 13261 findPid = Integer.parseInt(innerArgs[0]); 13262 } catch (NumberFormatException e) { 13263 } 13264 final int fFindPid = findPid; 13265 mAppProfiler.forAllCpuStats((st) -> { 13266 if (st.pid == fFindPid || (st.baseName != null 13267 && st.baseName.equals(innerArgs[0]))) { 13268 nativeProcs.add(st); 13269 } 13270 }); 13271 if (nativeProcs.size() > 0) { 13272 ProtoOutputStream proto = new ProtoOutputStream(fd); 13273 13274 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 13275 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 13276 Debug.MemoryInfo mi = null; 13277 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 13278 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 13279 final int pid = r.pid; 13280 13281 if (mi == null) { 13282 mi = new Debug.MemoryInfo(); 13283 } 13284 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 13285 if (!Debug.getMemoryInfo(pid, mi)) { 13286 continue; 13287 } 13288 } else { 13289 long pss = Debug.getPss(pid, tmpLong, null); 13290 if (pss == 0) { 13291 continue; 13292 } 13293 mi.nativePss = (int) pss; 13294 mi.nativePrivateDirty = (int) tmpLong[0]; 13295 mi.nativeRss = (int) tmpLong[2]; 13296 } 13297 13298 final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES); 13299 13300 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 13301 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName); 13302 13303 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 13304 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 13305 13306 proto.end(nToken); 13307 } 13308 13309 proto.flush(); 13310 return; 13311 } 13312 } 13313 } 13314 Log.d(TAG, "No process found for: " + innerArgs[0]); 13315 return; 13316 } 13317 13318 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 13319 opts.dumpDetails = true; 13320 } 13321 final int numProcs = procs.size(); 13322 final boolean collectNative = numProcs > 1 && !opts.packages; 13323 if (collectNative) { 13324 // If we are showing aggregations, also look for native processes to 13325 // include so that our aggregations are more accurate. 13326 updateCpuStatsNow(); 13327 } 13328 13329 ProtoOutputStream proto = new ProtoOutputStream(fd); 13330 13331 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 13332 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 13333 13334 final ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 13335 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 13336 final long[] ss = new long[INDEX_LAST]; 13337 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 13338 EmptyArray.LONG; 13339 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 13340 EmptyArray.LONG; 13341 long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 13342 EmptyArray.LONG; 13343 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13344 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13345 long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13346 13347 final long[] oomPss = new long[DUMP_MEM_OOM_LABEL.length]; 13348 final long[] oomSwapPss = new long[DUMP_MEM_OOM_LABEL.length]; 13349 final long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length]; 13350 final ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 13351 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 13352 13353 long cachedPss = 0; 13354 long cachedSwapPss = 0; 13355 boolean hasSwapPss = false; 13356 13357 Debug.MemoryInfo mi = null; 13358 for (int i = numProcs - 1; i >= 0; i--) { 13359 final ProcessRecord r = procs.get(i); 13360 final IApplicationThread thread; 13361 final int pid; 13362 final int oomAdj; 13363 final boolean hasActivities; 13364 synchronized (mProcLock) { 13365 thread = r.getThread(); 13366 pid = r.getPid(); 13367 oomAdj = r.mState.getSetAdjWithServices(); 13368 hasActivities = r.hasActivities(); 13369 } 13370 if (thread == null) { 13371 continue; 13372 } 13373 if (mi == null) { 13374 mi = new Debug.MemoryInfo(); 13375 } 13376 final int reportType; 13377 final long startTime; 13378 final long endTime; 13379 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 13380 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 13381 startTime = SystemClock.currentThreadTimeMillis(); 13382 if (!Debug.getMemoryInfo(pid, mi)) { 13383 continue; 13384 } 13385 endTime = SystemClock.currentThreadTimeMillis(); 13386 hasSwapPss = mi.hasSwappedOutPss; 13387 } else { 13388 reportType = ProcessStats.ADD_PSS_EXTERNAL; 13389 startTime = SystemClock.currentThreadTimeMillis(); 13390 long pss = Debug.getPss(pid, tmpLong, null); 13391 if (pss == 0) { 13392 continue; 13393 } 13394 mi.dalvikPss = (int) pss; 13395 endTime = SystemClock.currentThreadTimeMillis(); 13396 mi.dalvikPrivateDirty = (int) tmpLong[0]; 13397 mi.dalvikRss = (int) tmpLong[2]; 13398 } 13399 if (opts.dumpDetails) { 13400 if (opts.localOnly) { 13401 final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES); 13402 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY); 13403 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 13404 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName); 13405 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 13406 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 13407 proto.end(mToken); 13408 proto.end(aToken); 13409 } else { 13410 try { 13411 ByteTransferPipe tp = new ByteTransferPipe(); 13412 try { 13413 thread.dumpMemInfoProto(tp.getWriteFd(), 13414 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 13415 opts.dumpUnreachable, innerArgs); 13416 proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get()); 13417 } finally { 13418 tp.kill(); 13419 } 13420 } catch (IOException e) { 13421 Log.e(TAG, "Got IOException!", e); 13422 } catch (RemoteException e) { 13423 Log.e(TAG, "Got RemoteException!", e); 13424 } 13425 } 13426 } 13427 13428 final long myTotalPss = mi.getTotalPss(); 13429 final long myTotalUss = mi.getTotalUss(); 13430 final long myTotalRss = mi.getTotalRss(); 13431 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 13432 13433 synchronized (mProcLock) { 13434 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) { 13435 // Record this for posterity if the process has been stable. 13436 r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true, 13437 reportType, endTime - startTime); 13438 } 13439 } 13440 13441 if (!opts.isCheckinRequest && mi != null) { 13442 ss[INDEX_TOTAL_PSS] += myTotalPss; 13443 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 13444 ss[INDEX_TOTAL_RSS] += myTotalRss; 13445 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 13446 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 13447 myTotalSwapPss, myTotalRss, 0, pid, r.userId, hasActivities); 13448 procMems.add(pssItem); 13449 procMemsMap.put(pid, pssItem); 13450 13451 ss[INDEX_NATIVE_PSS] += mi.nativePss; 13452 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss; 13453 ss[INDEX_NATIVE_RSS] += mi.nativeRss; 13454 ss[INDEX_DALVIK_PSS] += mi.dalvikPss; 13455 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss; 13456 ss[INDEX_DALVIK_RSS] += mi.dalvikRss; 13457 for (int j=0; j<dalvikSubitemPss.length; j++) { 13458 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13459 dalvikSubitemSwapPss[j] += 13460 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13461 dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13462 } 13463 ss[INDEX_OTHER_PSS] += mi.otherPss; 13464 ss[INDEX_OTHER_RSS] += mi.otherRss; 13465 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss; 13466 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13467 long mem = mi.getOtherPss(j); 13468 miscPss[j] += mem; 13469 ss[INDEX_OTHER_PSS] -= mem; 13470 mem = mi.getOtherSwappedOutPss(j); 13471 miscSwapPss[j] += mem; 13472 ss[INDEX_OTHER_SWAP_PSS] -= mem; 13473 mem = mi.getOtherRss(j); 13474 miscRss[j] += mem; 13475 ss[INDEX_OTHER_RSS] -= mem; 13476 } 13477 13478 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 13479 cachedPss += myTotalPss; 13480 cachedSwapPss += myTotalSwapPss; 13481 } 13482 13483 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 13484 if (oomIndex == (oomPss.length - 1) 13485 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 13486 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 13487 oomPss[oomIndex] += myTotalPss; 13488 oomSwapPss[oomIndex] += myTotalSwapPss; 13489 if (oomProcs[oomIndex] == null) { 13490 oomProcs[oomIndex] = new ArrayList<MemItem>(); 13491 } 13492 oomProcs[oomIndex].add(pssItem); 13493 oomRss[oomIndex] += myTotalRss; 13494 break; 13495 } 13496 } 13497 } 13498 } 13499 13500 long nativeProcTotalPss = 0; 13501 13502 if (collectNative) { 13503 mi = null; 13504 final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1]; 13505 mAppProfiler.forAllCpuStats((st) -> { 13506 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 13507 if (memInfos[0] == null) { 13508 memInfos[0] = new Debug.MemoryInfo(); 13509 } 13510 final Debug.MemoryInfo info = memInfos[0]; 13511 if (!brief && !opts.oomOnly) { 13512 if (!Debug.getMemoryInfo(st.pid, info)) { 13513 return; 13514 } 13515 } else { 13516 long pss = Debug.getPss(st.pid, tmpLong, null); 13517 if (pss == 0) { 13518 return; 13519 } 13520 info.nativePss = (int) pss; 13521 info.nativePrivateDirty = (int) tmpLong[0]; 13522 info.nativeRss = (int) tmpLong[2]; 13523 } 13524 13525 final long myTotalPss = info.getTotalPss(); 13526 final long myTotalSwapPss = info.getTotalSwappedOutPss(); 13527 final long myTotalRss = info.getTotalRss(); 13528 ss[INDEX_TOTAL_PSS] += myTotalPss; 13529 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 13530 ss[INDEX_TOTAL_RSS] += myTotalRss; 13531 ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss; 13532 13533 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 13534 st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss, 0, 13535 st.pid, UserHandle.getUserId(st.uid), false); 13536 procMems.add(pssItem); 13537 13538 ss[INDEX_NATIVE_PSS] += info.nativePss; 13539 ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss; 13540 ss[INDEX_NATIVE_RSS] += info.nativeRss; 13541 ss[INDEX_DALVIK_PSS] += info.dalvikPss; 13542 ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss; 13543 ss[INDEX_DALVIK_RSS] += info.dalvikRss; 13544 for (int j = 0; j < dalvikSubitemPss.length; j++) { 13545 dalvikSubitemPss[j] += info.getOtherPss( 13546 Debug.MemoryInfo.NUM_OTHER_STATS + j); 13547 dalvikSubitemSwapPss[j] += 13548 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13549 dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS 13550 + j); 13551 } 13552 ss[INDEX_OTHER_PSS] += info.otherPss; 13553 ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss; 13554 ss[INDEX_OTHER_RSS] += info.otherRss; 13555 for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13556 long mem = info.getOtherPss(j); 13557 miscPss[j] += mem; 13558 ss[INDEX_OTHER_PSS] -= mem; 13559 mem = info.getOtherSwappedOutPss(j); 13560 miscSwapPss[j] += mem; 13561 ss[INDEX_OTHER_SWAP_PSS] -= mem; 13562 mem = info.getOtherRss(j); 13563 miscRss[j] += mem; 13564 ss[INDEX_OTHER_RSS] -= mem; 13565 } 13566 oomPss[0] += myTotalPss; 13567 oomSwapPss[0] += myTotalSwapPss; 13568 if (oomProcs[0] == null) { 13569 oomProcs[0] = new ArrayList<MemItem>(); 13570 } 13571 oomProcs[0].add(pssItem); 13572 oomRss[0] += myTotalRss; 13573 } 13574 }); 13575 13576 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 13577 13578 catMems.add(new MemItem("Native", "Native", ss[INDEX_NATIVE_PSS], 13579 ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], 0, -1)); 13580 final int dalvikId = -2; 13581 catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS], 13582 ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], 0, dalvikId)); 13583 catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS], 13584 ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], 0, -3)); 13585 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13586 String label = Debug.MemoryInfo.getOtherLabel(j); 13587 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], 13588 miscRss[j], 0, j)); 13589 } 13590 if (dalvikSubitemPss.length > 0) { 13591 // Add dalvik subitems. 13592 for (MemItem memItem : catMems) { 13593 int memItemStart = 0, memItemEnd = 0; 13594 if (memItem.id == dalvikId) { 13595 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 13596 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 13597 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 13598 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 13599 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 13600 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 13601 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 13602 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 13603 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 13604 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 13605 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 13606 } else { 13607 continue; // No subitems, continue. 13608 } 13609 memItem.subitems = new ArrayList<MemItem>(); 13610 for (int j=memItemStart; j<=memItemEnd; j++) { 13611 final String name = Debug.MemoryInfo.getOtherLabel( 13612 Debug.MemoryInfo.NUM_OTHER_STATS + j); 13613 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 13614 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], 0, j)); 13615 } 13616 } 13617 } 13618 13619 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 13620 for (int j=0; j<oomPss.length; j++) { 13621 if (oomPss[j] != 0) { 13622 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 13623 : DUMP_MEM_OOM_LABEL[j]; 13624 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j], 0, 13625 DUMP_MEM_OOM_ADJ[j]); 13626 item.subitems = oomProcs[j]; 13627 oomMems.add(item); 13628 } 13629 } 13630 13631 if (!opts.oomOnly) { 13632 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_PROCESS, "proc", 13633 procMems, true, false, false); 13634 } 13635 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_OOM_ADJUSTMENT, "oom", 13636 oomMems, false, false, false); 13637 if (!brief && !opts.oomOnly) { 13638 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_CATEGORY, "cat", 13639 catMems, true, false, false); 13640 } 13641 13642 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0; 13643 if (!opts.oomOnly) { 13644 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc", 13645 procMems, true, true, opts.dumpSwapPss); 13646 } 13647 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom", 13648 oomMems, false, true, opts.dumpSwapPss); 13649 if (!brief && !opts.oomOnly) { 13650 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat", 13651 catMems, true, true, opts.dumpSwapPss); 13652 } 13653 MemInfoReader memInfo = new MemInfoReader(); 13654 memInfo.readMemInfo(); 13655 if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) { 13656 synchronized (mProcessStats.mLock) { 13657 final long cachedKb = memInfo.getCachedSizeKb(); 13658 final long freeKb = memInfo.getFreeSizeKb(); 13659 final long zramKb = memInfo.getZramTotalSizeKb(); 13660 final long kernelKb = memInfo.getKernelUsedSizeKb(); 13661 EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, 13662 kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024); 13663 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 13664 ss[INDEX_TOTAL_NATIVE_PSS]); 13665 } 13666 } 13667 if (!brief) { 13668 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb()); 13669 proto.write(MemInfoDumpProto.STATUS, mAppProfiler.getLastMemoryLevelLocked()); 13670 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss); 13671 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb()); 13672 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb()); 13673 } 13674 long lostRAM = memInfo.getTotalSizeKb() 13675 - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS]) 13676 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 13677 - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb(); 13678 proto.write(MemInfoDumpProto.USED_PSS_KB, ss[INDEX_TOTAL_PSS] - cachedPss); 13679 proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb()); 13680 proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM); 13681 if (!brief) { 13682 if (memInfo.getZramTotalSizeKb() != 0) { 13683 proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb()); 13684 proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB, 13685 memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb()); 13686 proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb()); 13687 } 13688 final long[] ksm = getKsmInfo(); 13689 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]); 13690 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]); 13691 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]); 13692 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]); 13693 13694 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass()); 13695 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass()); 13696 proto.write(MemInfoDumpProto.OOM_KB, 13697 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024); 13698 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB, 13699 mProcessList.getCachedRestoreThresholdKb()); 13700 13701 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic()); 13702 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx()); 13703 } 13704 } 13705 13706 proto.flush(); 13707 } 13708 appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)13709 static void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, 13710 long memtrack, String name) { 13711 sb.append(" "); 13712 sb.append(ProcessList.makeOomAdjString(oomAdj, false)); 13713 sb.append(' '); 13714 sb.append(ProcessList.makeProcStateString(procState)); 13715 sb.append(' '); 13716 ProcessList.appendRamKb(sb, pss); 13717 sb.append(": "); 13718 sb.append(name); 13719 if (memtrack > 0) { 13720 sb.append(" ("); 13721 sb.append(stringifyKBSize(memtrack)); 13722 sb.append(" memtrack)"); 13723 } 13724 } 13725 appendMemInfo(StringBuilder sb, ProcessMemInfo mi)13726 static void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) { 13727 appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name); 13728 sb.append(" (pid "); 13729 sb.append(mi.pid); 13730 sb.append(") "); 13731 sb.append(mi.adjType); 13732 sb.append('\n'); 13733 if (mi.adjReason != null) { 13734 sb.append(" "); 13735 sb.append(mi.adjReason); 13736 sb.append('\n'); 13737 } 13738 } 13739 13740 /** 13741 * Searches array of arguments for the specified string 13742 * @param args array of argument strings 13743 * @param value value to search for 13744 * @return true if the value is contained in the array 13745 */ scanArgs(String[] args, String value)13746 private static boolean scanArgs(String[] args, String value) { 13747 if (args != null) { 13748 for (String arg : args) { 13749 if (value.equals(arg)) { 13750 return true; 13751 } 13752 } 13753 } 13754 return false; 13755 } 13756 13757 /** 13758 * Main code for cleaning up a process when it has gone away. This is 13759 * called both as a result of the process dying, or directly when stopping 13760 * a process when running in single process mode. 13761 * 13762 * @return Returns true if the given process has been restarted, so the 13763 * app that was passed in must remain on the process lists. 13764 */ 13765 @GuardedBy("this") cleanUpApplicationRecordLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, int index, boolean replacingPid, boolean fromBinderDied)13766 final boolean cleanUpApplicationRecordLocked(ProcessRecord app, int pid, 13767 boolean restarting, boolean allowRestart, int index, boolean replacingPid, 13768 boolean fromBinderDied) { 13769 boolean restart; 13770 synchronized (mProcLock) { 13771 if (index >= 0) { 13772 removeLruProcessLocked(app); 13773 ProcessList.remove(pid); 13774 } 13775 13776 // We don't want to unlinkDeathRecipient immediately, if it's not called from binder 13777 // and it's not isolated, as we'd need the signal to bookkeeping the dying process list. 13778 restart = app.onCleanupApplicationRecordLSP(mProcessStats, allowRestart, 13779 fromBinderDied || app.isolated /* unlinkDeath */); 13780 13781 // Cancel pending frozen task and clean up frozen record if there is any. 13782 mOomAdjuster.mCachedAppOptimizer.onCleanupApplicationRecordLocked(app); 13783 } 13784 mAppProfiler.onCleanupApplicationRecordLocked(app); 13785 mBroadcastQueue.onApplicationCleanupLocked(app); 13786 clearProcessForegroundLocked(app); 13787 mServices.killServicesLocked(app, allowRestart); 13788 mPhantomProcessList.onAppDied(pid); 13789 13790 // If the app is undergoing backup, tell the backup manager about it 13791 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 13792 if (backupTarget != null && pid == backupTarget.app.getPid()) { 13793 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App " 13794 + backupTarget.appInfo + " died during backup"); 13795 mHandler.post(new Runnable() { 13796 @Override 13797 public void run() { 13798 try { 13799 IBackupManager bm = IBackupManager.Stub.asInterface( 13800 ServiceManager.getService(Context.BACKUP_SERVICE)); 13801 bm.agentDisconnectedForUser(app.userId, app.info.packageName); 13802 } catch (RemoteException e) { 13803 // can't happen; backup manager is local 13804 } 13805 } 13806 }); 13807 } 13808 13809 mProcessList.scheduleDispatchProcessDiedLocked(pid, app.info.uid); 13810 13811 // If this is a preceding instance of another process instance 13812 allowRestart = mProcessList.handlePrecedingAppDiedLocked(app); 13813 13814 // If somehow this process was still waiting for the death of its predecessor, 13815 // (probably it's "killed" before starting for real), reset the bookkeeping. 13816 final ProcessRecord predecessor = app.mPredecessor; 13817 if (predecessor != null) { 13818 predecessor.mSuccessor = null; 13819 predecessor.mSuccessorStartRunnable = null; 13820 app.mPredecessor = null; 13821 } 13822 13823 // If the caller is restarting this app, then leave it in its 13824 // current lists and let the caller take care of it. 13825 if (restarting) { 13826 return false; 13827 } 13828 13829 if (!app.isPersistent() || app.isolated) { 13830 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 13831 "Removing non-persistent process during cleanup: " + app); 13832 if (!replacingPid) { 13833 mProcessList.removeProcessNameLocked(app.processName, app.uid, app); 13834 } 13835 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 13836 } else if (!app.isRemoved()) { 13837 // This app is persistent, so we need to keep its record around. 13838 // If it is not already on the pending app list, add it there 13839 // and start a new process for it. 13840 if (mPersistentStartingProcesses.indexOf(app) < 0) { 13841 mPersistentStartingProcesses.add(app); 13842 restart = true; 13843 } 13844 } 13845 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v( 13846 TAG_CLEANUP, "Clean-up removing on hold: " + app); 13847 mProcessesOnHold.remove(app); 13848 13849 mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController()); 13850 mProcessList.noteProcessDiedLocked(app); 13851 13852 if (restart && allowRestart && !app.isolated) { 13853 // We have components that still need to be running in the 13854 // process, so re-launch it. 13855 if (index < 0) { 13856 ProcessList.remove(pid); 13857 } 13858 13859 // Remove provider publish timeout because we will start a new timeout when the 13860 // restarted process is attaching (if the process contains launching providers). 13861 mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, app); 13862 13863 mProcessList.addProcessNameLocked(app); 13864 app.setPendingStart(false); 13865 mProcessList.startProcessLocked(app, new HostingRecord( 13866 HostingRecord.HOSTING_TYPE_RESTART, app.processName), 13867 ZYGOTE_POLICY_FLAG_EMPTY); 13868 return true; 13869 } else if (pid > 0 && pid != MY_PID) { 13870 // Goodbye! 13871 removePidLocked(pid, app); 13872 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 13873 mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_SOFT_MSG, app); 13874 mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_HARD_MSG, app); 13875 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 13876 if (app.isolated) { 13877 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 13878 } 13879 app.setPid(0); 13880 } 13881 return false; 13882 } 13883 13884 // ========================================================= 13885 // SERVICES 13886 // ========================================================= 13887 13888 @Override getServices(int maxNum, int flags)13889 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) { 13890 enforceNotIsolatedCaller("getServices"); 13891 13892 final int callingUid = Binder.getCallingUid(); 13893 final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission( 13894 INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED); 13895 final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices", 13896 Binder.getCallingPid(), callingUid); 13897 synchronized (this) { 13898 return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid, 13899 allowed, canInteractAcrossUsers); 13900 } 13901 } 13902 13903 @Override getRunningServiceControlPanel(ComponentName name)13904 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 13905 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 13906 final int callingUid = Binder.getCallingUid(); 13907 final int callingUserId = UserHandle.getUserId(callingUid); 13908 if (name == null || getPackageManagerInternal() 13909 .filterAppAccess(name.getPackageName(), callingUid, callingUserId)) { 13910 return null; 13911 } 13912 synchronized (this) { 13913 return mServices.getRunningServiceControlPanelLocked(name); 13914 } 13915 } 13916 13917 @Override logFgsApiBegin(@oregroundServiceApiType int apiType, int uid, int pid)13918 public void logFgsApiBegin(@ForegroundServiceApiType int apiType, 13919 int uid, int pid) { 13920 enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE, 13921 "logFgsApiBegin"); 13922 synchronized (this) { 13923 mServices.logFgsApiBeginLocked(apiType, uid, pid); 13924 } 13925 } 13926 13927 @Override logFgsApiEnd(@oregroundServiceApiType int apiType, int uid, int pid)13928 public void logFgsApiEnd(@ForegroundServiceApiType int apiType, 13929 int uid, int pid) { 13930 enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE, 13931 "logFgsApiEnd"); 13932 synchronized (this) { 13933 mServices.logFgsApiEndLocked(apiType, uid, pid); 13934 } 13935 } 13936 13937 @Override logFgsApiStateChanged(@oregroundServiceApiType int apiType, int state, int uid, int pid)13938 public void logFgsApiStateChanged(@ForegroundServiceApiType int apiType, 13939 int state, int uid, int pid) { 13940 enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE, 13941 "logFgsApiEvent"); 13942 synchronized (this) { 13943 mServices.logFgsApiStateChangedLocked(apiType, uid, pid, state); 13944 } 13945 } 13946 13947 @Override startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId)13948 public ComponentName startService(IApplicationThread caller, Intent service, 13949 String resolvedType, boolean requireForeground, String callingPackage, 13950 String callingFeatureId, int userId) 13951 throws TransactionTooLargeException { 13952 return startService(caller, service, resolvedType, requireForeground, callingPackage, 13953 callingFeatureId, userId, false /* isSdkSandboxService */, INVALID_UID, null, null); 13954 } 13955 startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)13956 private ComponentName startService(IApplicationThread caller, Intent service, 13957 String resolvedType, boolean requireForeground, String callingPackage, 13958 String callingFeatureId, int userId, boolean isSdkSandboxService, 13959 int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName) 13960 throws TransactionTooLargeException { 13961 enforceNotIsolatedCaller("startService"); 13962 enforceAllowedToStartOrBindServiceIfSdkSandbox(service); 13963 if (service != null) { 13964 // Refuse possible leaked file descriptors 13965 if (service.hasFileDescriptors()) { 13966 throw new IllegalArgumentException("File descriptors passed in Intent"); 13967 } 13968 // Remove existing mismatch flag so it can be properly updated later 13969 service.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH); 13970 } 13971 13972 if (callingPackage == null) { 13973 throw new IllegalArgumentException("callingPackage cannot be null"); 13974 } 13975 13976 if (isSdkSandboxService && instanceName == null) { 13977 throw new IllegalArgumentException("No instance name provided for SDK sandbox process"); 13978 } 13979 validateServiceInstanceName(instanceName); 13980 13981 if (DEBUG_SERVICE) 13982 Slog.v( 13983 TAG_SERVICE, 13984 "*** startService: " 13985 + service 13986 + " type=" 13987 + resolvedType 13988 + " fg=" 13989 + requireForeground); 13990 final int callingPid = Binder.getCallingPid(); 13991 final int callingUid = Binder.getCallingUid(); 13992 final long origId = Binder.clearCallingIdentity(); 13993 ComponentName res; 13994 try { 13995 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 13996 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startService: " 13997 + "intent=" + service + ", caller=" + callingPackage 13998 + ", fgRequired=" + requireForeground); 13999 } 14000 synchronized (this) { 14001 res = mServices.startServiceLocked(caller, service, 14002 resolvedType, callingPid, callingUid, 14003 requireForeground, callingPackage, callingFeatureId, userId, 14004 isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage, 14005 instanceName); 14006 } 14007 } finally { 14008 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 14009 Binder.restoreCallingIdentity(origId); 14010 } 14011 return res; 14012 } 14013 validateServiceInstanceName(String instanceName)14014 private void validateServiceInstanceName(String instanceName) { 14015 // Ensure that instanceName, which is caller provided, does not contain 14016 // unusual characters. 14017 if (instanceName != null) { 14018 if (!instanceName.matches("[a-zA-Z0-9_.]+")) { 14019 throw new IllegalArgumentException("Illegal instanceName"); 14020 } 14021 } 14022 } 14023 14024 @Override stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)14025 public int stopService(IApplicationThread caller, Intent service, 14026 String resolvedType, int userId) { 14027 return stopService(caller, service, resolvedType, userId, false /* isSdkSandboxService */, 14028 INVALID_UID, null, null); 14029 } 14030 stopService(IApplicationThread caller, Intent service, String resolvedType, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)14031 private int stopService(IApplicationThread caller, Intent service, String resolvedType, 14032 int userId, boolean isSdkSandboxService, 14033 int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName) { 14034 enforceNotIsolatedCaller("stopService"); 14035 // Refuse possible leaked file descriptors 14036 if (service != null && service.hasFileDescriptors() == true) { 14037 throw new IllegalArgumentException("File descriptors passed in Intent"); 14038 } 14039 14040 try { 14041 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 14042 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopService: " + service); 14043 } 14044 synchronized (this) { 14045 return mServices.stopServiceLocked(caller, service, resolvedType, userId, 14046 isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage, 14047 instanceName); 14048 } 14049 } finally { 14050 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 14051 } 14052 } 14053 14054 @Override peekService(Intent service, String resolvedType, String callingPackage)14055 public IBinder peekService(Intent service, String resolvedType, String callingPackage) { 14056 enforceNotIsolatedCaller("peekService"); 14057 // Refuse possible leaked file descriptors 14058 if (service != null && service.hasFileDescriptors() == true) { 14059 throw new IllegalArgumentException("File descriptors passed in Intent"); 14060 } 14061 14062 if (callingPackage == null) { 14063 throw new IllegalArgumentException("callingPackage cannot be null"); 14064 } 14065 14066 synchronized(this) { 14067 return mServices.peekServiceLocked(service, resolvedType, callingPackage); 14068 } 14069 } 14070 14071 @Override stopServiceToken(ComponentName className, IBinder token, int startId)14072 public boolean stopServiceToken(ComponentName className, IBinder token, 14073 int startId) { 14074 try { 14075 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 14076 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopServiceToken: " 14077 + (className != null ? className.toShortString() 14078 : ("from " + Binder.getCallingPid()))); 14079 } 14080 synchronized (this) { 14081 return mServices.stopServiceTokenLocked(className, token, startId); 14082 } 14083 } finally { 14084 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 14085 } 14086 } 14087 14088 @Override setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)14089 public void setServiceForeground(ComponentName className, IBinder token, 14090 int id, Notification notification, int flags, int foregroundServiceType) { 14091 synchronized(this) { 14092 mServices.setServiceForegroundLocked(className, token, id, notification, flags, 14093 foregroundServiceType); 14094 } 14095 } 14096 14097 @Override getForegroundServiceType(ComponentName className, IBinder token)14098 public int getForegroundServiceType(ComponentName className, IBinder token) { 14099 synchronized (this) { 14100 return mServices.getForegroundServiceTypeLocked(className, token); 14101 } 14102 } 14103 14104 @Override shouldServiceTimeOut(ComponentName className, IBinder token)14105 public boolean shouldServiceTimeOut(ComponentName className, IBinder token) { 14106 synchronized (this) { 14107 return mServices.shouldServiceTimeOutLocked(className, token); 14108 } 14109 } 14110 14111 @Override hasServiceTimeLimitExceeded(ComponentName className, IBinder token)14112 public boolean hasServiceTimeLimitExceeded(ComponentName className, IBinder token) { 14113 synchronized (this) { 14114 return mServices.hasServiceTimedOutLocked(className, token); 14115 } 14116 } 14117 14118 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)14119 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 14120 boolean requireFull, String name, String callerPackage) { 14121 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 14122 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 14123 } 14124 isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)14125 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 14126 String className, int flags) { 14127 boolean result = false; 14128 // For apps that don't have pre-defined UIDs, check for permission 14129 if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) { 14130 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 14131 if (ActivityManager.checkUidPermission( 14132 INTERACT_ACROSS_USERS, 14133 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 14134 ComponentName comp = new ComponentName(aInfo.packageName, className); 14135 String msg = "Permission Denial: Component " + comp.flattenToShortString() 14136 + " requests FLAG_SINGLE_USER, but app does not hold " 14137 + INTERACT_ACROSS_USERS; 14138 Slog.w(TAG, msg); 14139 throw new SecurityException(msg); 14140 } 14141 // Permission passed 14142 result = true; 14143 } 14144 } else if ("system".equals(componentProcessName)) { 14145 result = true; 14146 } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 14147 // Phone app and persistent apps are allowed to export singleuser providers. 14148 result = UserHandle.isSameApp(aInfo.uid, PHONE_UID) 14149 || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 14150 } 14151 if (DEBUG_MU) Slog.v(TAG_MU, 14152 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x" 14153 + Integer.toHexString(flags) + ") = " + result); 14154 return result; 14155 } 14156 isSystemUserOnly(int flags)14157 boolean isSystemUserOnly(int flags) { 14158 return android.multiuser.Flags.enableSystemUserOnlyForServicesAndProviders() 14159 && (flags & ServiceInfo.FLAG_SYSTEM_USER_ONLY) != 0; 14160 } 14161 14162 /** 14163 * Checks to see if the caller is in the same app as the singleton 14164 * component, or the component is in a special app. It allows special apps 14165 * to export singleton components but prevents exporting singleton 14166 * components for regular apps. 14167 */ isValidSingletonCall(int callingUid, int componentUid)14168 boolean isValidSingletonCall(int callingUid, int componentUid) { 14169 int componentAppId = UserHandle.getAppId(componentUid); 14170 return UserHandle.isSameApp(callingUid, componentUid) 14171 || componentAppId == SYSTEM_UID 14172 || componentAppId == PHONE_UID 14173 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 14174 == PackageManager.PERMISSION_GRANTED; 14175 } 14176 bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String callingPackage, int userId)14177 public int bindService(IApplicationThread caller, IBinder token, Intent service, 14178 String resolvedType, IServiceConnection connection, long flags, 14179 String callingPackage, int userId) throws TransactionTooLargeException { 14180 return bindServiceInstance(caller, token, service, resolvedType, connection, flags, 14181 null, callingPackage, userId); 14182 } 14183 14184 /** 14185 * Binds to a service with a given instanceName, creating it if it does not already exist. 14186 * If the instanceName field is not supplied, binding to the service occurs as usual. 14187 */ bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String instanceName, String callingPackage, int userId)14188 public int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, 14189 String resolvedType, IServiceConnection connection, long flags, String instanceName, 14190 String callingPackage, int userId) throws TransactionTooLargeException { 14191 return bindServiceInstance(caller, token, service, resolvedType, connection, flags, 14192 instanceName, false, INVALID_UID, null, null, callingPackage, userId); 14193 } 14194 bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, IApplicationThread sdkSandboxClientApplicationThread, String callingPackage, int userId)14195 private int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, 14196 String resolvedType, IServiceConnection connection, long flags, String instanceName, 14197 boolean isSdkSandboxService, int sdkSandboxClientAppUid, 14198 String sdkSandboxClientAppPackage, 14199 IApplicationThread sdkSandboxClientApplicationThread, 14200 String callingPackage, int userId) 14201 throws TransactionTooLargeException { 14202 enforceNotIsolatedCaller("bindService"); 14203 enforceAllowedToStartOrBindServiceIfSdkSandbox(service); 14204 14205 if (service != null) { 14206 // Refuse possible leaked file descriptors 14207 if (service.hasFileDescriptors()) { 14208 throw new IllegalArgumentException("File descriptors passed in Intent"); 14209 } 14210 // Remove existing mismatch flag so it can be properly updated later 14211 service.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH); 14212 } 14213 14214 if (callingPackage == null) { 14215 throw new IllegalArgumentException("callingPackage cannot be null"); 14216 } 14217 14218 if (isSdkSandboxService && instanceName == null) { 14219 throw new IllegalArgumentException("No instance name provided for isolated process"); 14220 } 14221 14222 validateServiceInstanceName(instanceName); 14223 14224 try { 14225 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 14226 final ComponentName cn = service.getComponent(); 14227 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindService:" 14228 + (cn != null ? cn.toShortString() : service.getAction())); 14229 } 14230 synchronized (this) { 14231 return mServices.bindServiceLocked(caller, token, service, resolvedType, connection, 14232 flags, instanceName, isSdkSandboxService, sdkSandboxClientAppUid, 14233 sdkSandboxClientAppPackage, sdkSandboxClientApplicationThread, 14234 callingPackage, userId); 14235 } 14236 } finally { 14237 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 14238 } 14239 } 14240 updateServiceGroup(IServiceConnection connection, int group, int importance)14241 public void updateServiceGroup(IServiceConnection connection, int group, int importance) { 14242 synchronized (this) { 14243 mServices.updateServiceGroupLocked(connection, group, importance); 14244 } 14245 } 14246 unbindService(IServiceConnection connection)14247 public boolean unbindService(IServiceConnection connection) { 14248 try { 14249 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 14250 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "unbindService"); 14251 } 14252 synchronized (this) { 14253 return mServices.unbindServiceLocked(connection); 14254 } 14255 } finally { 14256 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 14257 } 14258 } 14259 publishService(IBinder token, Intent intent, IBinder service)14260 public void publishService(IBinder token, Intent intent, IBinder service) { 14261 // Refuse possible leaked file descriptors 14262 if (intent != null && intent.hasFileDescriptors() == true) { 14263 throw new IllegalArgumentException("File descriptors passed in Intent"); 14264 } 14265 14266 synchronized(this) { 14267 if (!(token instanceof ServiceRecord)) { 14268 throw new IllegalArgumentException("Invalid service token"); 14269 } 14270 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 14271 } 14272 } 14273 unbindFinished(IBinder token, Intent intent, boolean doRebind)14274 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) { 14275 // Refuse possible leaked file descriptors 14276 if (intent != null && intent.hasFileDescriptors() == true) { 14277 throw new IllegalArgumentException("File descriptors passed in Intent"); 14278 } 14279 14280 synchronized(this) { 14281 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind); 14282 } 14283 } 14284 14285 @Override serviceDoneExecuting(IBinder token, int type, int startId, int res, Intent intent)14286 public void serviceDoneExecuting(IBinder token, int type, int startId, int res, Intent intent) { 14287 synchronized(this) { 14288 if (!(token instanceof ServiceRecord)) { 14289 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token); 14290 throw new IllegalArgumentException("Invalid service token"); 14291 } 14292 mServices.serviceDoneExecutingLocked((ServiceRecord) token, type, startId, res, false, 14293 intent); 14294 } 14295 } 14296 14297 // ========================================================= 14298 // BACKUP AND RESTORE 14299 // ========================================================= 14300 14301 // Cause the target app to be launched if necessary and its backup agent 14302 // instantiated. The backup agent will invoke backupAgentCreated() on the 14303 // activity manager to announce its creation. bindBackupAgent(String packageName, int backupMode, int targetUserId, @BackupDestination int backupDestination)14304 public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId, 14305 @BackupDestination int backupDestination) { 14306 long startTimeNs = SystemClock.uptimeNanos(); 14307 if (DEBUG_BACKUP) { 14308 Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode 14309 + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid() 14310 + " uid = " + Process.myUid()); 14311 } 14312 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 14313 14314 // The instantiatedUserId is the user of the process the backup agent is started in. This is 14315 // different from the targetUserId which is the user whose data is to be backed up or 14316 // restored. This distinction is important for system-process packages that live in the 14317 // system user's process but backup/restore data for non-system users. 14318 // TODO (b/123688746): Handle all system-process packages with singleton check. 14319 boolean useSystemUser = PLATFORM_PACKAGE_NAME.equals(packageName) 14320 || getPackageManagerInternal().getSystemUiServiceComponent().getPackageName() 14321 .equals(packageName); 14322 final int instantiatedUserId = useSystemUser ? UserHandle.USER_SYSTEM : targetUserId; 14323 14324 IPackageManager pm = AppGlobals.getPackageManager(); 14325 ApplicationInfo app = null; 14326 try { 14327 app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId); 14328 } catch (RemoteException e) { 14329 // can't happen; package manager is process-local 14330 } 14331 if (app == null) { 14332 Slog.w(TAG, "Unable to bind backup agent for " + packageName); 14333 return false; 14334 } 14335 if (app.backupAgentName != null) { 14336 final ComponentName backupAgentName = new ComponentName( 14337 app.packageName, app.backupAgentName); 14338 int enableState = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 14339 try { 14340 enableState = pm.getComponentEnabledSetting(backupAgentName, instantiatedUserId); 14341 } catch (RemoteException e) { 14342 // can't happen; package manager is process-local 14343 } 14344 switch (enableState) { 14345 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED: 14346 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER: 14347 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED: 14348 Slog.w(TAG, "Unable to bind backup agent for " + backupAgentName 14349 + ", the backup agent component is disabled."); 14350 return false; 14351 14352 case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT: 14353 case PackageManager.COMPONENT_ENABLED_STATE_ENABLED: 14354 default: 14355 // Since there's no way to declare a backup agent disabled in the manifest, 14356 // assume the case COMPONENT_ENABLED_STATE_DEFAULT to be enabled. 14357 break; 14358 } 14359 } 14360 14361 int oldBackupUid; 14362 int newBackupUid; 14363 14364 synchronized(this) { 14365 if (android.app.Flags.appRestrictionsApi()) { 14366 try { 14367 final boolean wasStopped = mPackageManagerInt.isPackageStopped(app.packageName, 14368 UserHandle.getUserId(app.uid)); 14369 if (wasStopped) { 14370 noteAppRestrictionEnabled(app.packageName, app.uid, 14371 RESTRICTION_LEVEL_FORCE_STOPPED, false, 14372 RESTRICTION_REASON_DEFAULT, "restore", 14373 RESTRICTION_SOURCE_SYSTEM, 0L); 14374 } 14375 } catch (NameNotFoundException e) { 14376 Slog.w(TAG, "No such package", e); 14377 } 14378 } 14379 14380 // !!! TODO: currently no check here that we're already bound 14381 // Backup agent is now in use, its package can't be stopped. 14382 try { 14383 mPackageManagerInt.setPackageStoppedState( 14384 app.packageName, false, UserHandle.getUserId(app.uid)); 14385 } catch (IllegalArgumentException e) { 14386 Slog.w(TAG, "Failed trying to unstop package " 14387 + app.packageName + ": " + e); 14388 } 14389 14390 BackupRecord r = new BackupRecord(app, backupMode, targetUserId, backupDestination); 14391 ComponentName hostingName = 14392 (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL 14393 || backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE) 14394 ? new ComponentName(app.packageName, app.backupAgentName) 14395 : new ComponentName("android", "FullBackupAgent"); 14396 14397 ProcessRecord proc = getProcessRecordLocked(app.processName, app.uid); 14398 boolean isProcessStarted = proc != null; 14399 if (!isProcessStarted) { 14400 proc = startProcessLocked(app.processName, app, 14401 false, 0, 14402 new HostingRecord(HostingRecord.HOSTING_TYPE_BACKUP, hostingName), 14403 ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false); 14404 } 14405 if (proc == null) { 14406 Slog.e(TAG, "Unable to start backup agent process " + r); 14407 return false; 14408 } 14409 mProcessList.getAppStartInfoTracker().handleProcessBackupStart(startTimeNs, proc, r, 14410 !isProcessStarted); 14411 14412 // If the app is a regular app (uid >= 10000) and not the system server or phone 14413 // process, etc, then mark it as being in full backup so that certain calls to the 14414 // process can be blocked. This is not reset to false anywhere because we kill the 14415 // process after the full backup is done and the ProcessRecord will vaporize anyway. 14416 if (UserHandle.isApp(app.uid) && 14417 backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) { 14418 proc.setInFullBackup(true); 14419 } 14420 r.app = proc; 14421 final BackupRecord backupTarget = mBackupTargets.get(targetUserId); 14422 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 14423 newBackupUid = proc.isInFullBackup() ? r.appInfo.uid : -1; 14424 mBackupTargets.put(targetUserId, r); 14425 14426 proc.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP); 14427 14428 // Try not to kill the process during backup 14429 updateOomAdjLocked(proc, OOM_ADJ_REASON_BACKUP); 14430 14431 // If the process is already attached, schedule the creation of the backup agent now. 14432 // If it is not yet live, this will be done when it attaches to the framework. 14433 final IApplicationThread thread = proc.getThread(); 14434 if (thread != null) { 14435 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc); 14436 try { 14437 thread.scheduleCreateBackupAgent(app, backupMode, targetUserId, 14438 backupDestination); 14439 } catch (RemoteException e) { 14440 // Will time out on the backup manager side 14441 } 14442 } else { 14443 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach"); 14444 } 14445 // Invariants: at this point, the target app process exists and the application 14446 // is either already running or in the process of coming up. mBackupTarget and 14447 // mBackupAppName describe the app, so that when it binds back to the AM we 14448 // know that it's scheduled for a backup-agent operation. 14449 } 14450 14451 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14452 if (oldBackupUid != -1) { 14453 js.removeBackingUpUid(oldBackupUid); 14454 } 14455 if (newBackupUid != -1) { 14456 js.addBackingUpUid(newBackupUid); 14457 } 14458 14459 return true; 14460 } 14461 clearPendingBackup(int userId)14462 private void clearPendingBackup(int userId) { 14463 if (DEBUG_BACKUP) { 14464 Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = " 14465 + Binder.getCallingUid() + " uid = " + Process.myUid()); 14466 } 14467 14468 synchronized (this) { 14469 final int indexOfKey = mBackupTargets.indexOfKey(userId); 14470 if (indexOfKey >= 0) { 14471 final BackupRecord backupTarget = mBackupTargets.valueAt(indexOfKey); 14472 if (backupTarget != null && backupTarget.app != null) { 14473 backupTarget.app.mProfile.clearHostingComponentType( 14474 HOSTING_COMPONENT_TYPE_BACKUP); 14475 } 14476 mBackupTargets.removeAt(indexOfKey); 14477 } 14478 } 14479 14480 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14481 js.clearAllBackingUpUids(); 14482 } 14483 14484 // A backup agent has just come up 14485 @Override backupAgentCreated(String agentPackageName, IBinder agent, int userId)14486 public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) { 14487 final int callingUid = Binder.getCallingUid(); 14488 enforceCallingPackage(agentPackageName, callingUid); 14489 14490 // Resolve the target user id and enforce permissions. 14491 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, 14492 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null); 14493 if (DEBUG_BACKUP) { 14494 Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent 14495 + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId 14496 + " callingUid = " + callingUid + " uid = " + Process.myUid()); 14497 } 14498 14499 synchronized(this) { 14500 final BackupRecord backupTarget = mBackupTargets.get(userId); 14501 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 14502 if (!agentPackageName.equals(backupAppName)) { 14503 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 14504 return; 14505 } 14506 } 14507 14508 final long oldIdent = Binder.clearCallingIdentity(); 14509 try { 14510 IBackupManager bm = IBackupManager.Stub.asInterface( 14511 ServiceManager.getService(Context.BACKUP_SERVICE)); 14512 bm.agentConnectedForUser(userId, agentPackageName, agent); 14513 } catch (RemoteException e) { 14514 // can't happen; the backup manager service is local 14515 } catch (Exception e) { 14516 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 14517 e.printStackTrace(); 14518 } finally { 14519 Binder.restoreCallingIdentity(oldIdent); 14520 } 14521 } 14522 14523 // done with this agent unbindBackupAgent(ApplicationInfo appInfo)14524 public void unbindBackupAgent(ApplicationInfo appInfo) { 14525 if (DEBUG_BACKUP) { 14526 Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = " 14527 + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = " 14528 + Process.myUid()); 14529 } 14530 14531 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent"); 14532 if (appInfo == null) { 14533 Slog.w(TAG, "unbind backup agent for null app"); 14534 return; 14535 } 14536 14537 int oldBackupUid; 14538 14539 final int userId = UserHandle.getUserId(appInfo.uid); 14540 synchronized(this) { 14541 final BackupRecord backupTarget = mBackupTargets.get(userId); 14542 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 14543 try { 14544 if (backupAppName == null) { 14545 Slog.w(TAG, "Unbinding backup agent with no active backup"); 14546 return; 14547 } 14548 14549 if (!backupAppName.equals(appInfo.packageName)) { 14550 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 14551 return; 14552 } 14553 14554 // Not backing this app up any more; reset its OOM adjustment 14555 final ProcessRecord proc = backupTarget.app; 14556 updateOomAdjLocked(proc, OOM_ADJ_REASON_BACKUP); 14557 proc.setInFullBackup(false); 14558 proc.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP); 14559 14560 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 14561 14562 // If the app crashed during backup, 'thread' will be null here 14563 final IApplicationThread thread = proc.getThread(); 14564 if (thread != null) { 14565 try { 14566 thread.scheduleDestroyBackupAgent(appInfo, userId); 14567 } catch (Exception e) { 14568 Slog.e(TAG, "Exception when unbinding backup agent:"); 14569 e.printStackTrace(); 14570 } 14571 } 14572 } finally { 14573 mBackupTargets.delete(userId); 14574 } 14575 } 14576 14577 if (oldBackupUid != -1) { 14578 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14579 js.removeBackingUpUid(oldBackupUid); 14580 } 14581 } 14582 14583 // ========================================================= 14584 // BROADCASTS 14585 // ========================================================= 14586 isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)14587 private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) { 14588 if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) { 14589 return false; 14590 } 14591 // Easy case -- we have the app's ProcessRecord. 14592 if (record != null) { 14593 return record.info.isInstantApp(); 14594 } 14595 // Otherwise check with PackageManager. 14596 IPackageManager pm = AppGlobals.getPackageManager(); 14597 try { 14598 if (callerPackage == null) { 14599 final String[] packageNames = pm.getPackagesForUid(uid); 14600 if (packageNames == null || packageNames.length == 0) { 14601 throw new IllegalArgumentException("Unable to determine caller package name"); 14602 } 14603 // Instant Apps can't use shared uids, so its safe to only check the first package. 14604 callerPackage = packageNames[0]; 14605 } 14606 mAppOpsService.checkPackage(uid, callerPackage); 14607 return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid)); 14608 } catch (RemoteException e) { 14609 Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e); 14610 return true; 14611 } 14612 } 14613 14614 /** 14615 * @deprecated Use {@link #registerReceiverWithFeature} 14616 */ 14617 @Deprecated registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)14618 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 14619 IIntentReceiver receiver, IntentFilter filter, String permission, int userId, 14620 int flags) { 14621 return registerReceiverWithFeature(caller, callerPackage, null, null, 14622 receiver, filter, permission, userId, flags); 14623 } 14624 registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)14625 public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage, 14626 String callerFeatureId, String receiverId, IIntentReceiver receiver, 14627 IntentFilter filter, String permission, int userId, int flags) { 14628 traceRegistrationBegin(receiverId, receiver, filter, userId); 14629 try { 14630 return registerReceiverWithFeatureTraced(caller, callerPackage, callerFeatureId, 14631 receiverId, receiver, filter, permission, userId, flags); 14632 } finally { 14633 traceRegistrationEnd(); 14634 } 14635 } 14636 traceRegistrationBegin(String receiverId, IIntentReceiver receiver, IntentFilter filter, int userId)14637 private static void traceRegistrationBegin(String receiverId, IIntentReceiver receiver, 14638 IntentFilter filter, int userId) { 14639 if (!Flags.traceReceiverRegistration()) { 14640 return; 14641 } 14642 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 14643 final StringBuilder sb = new StringBuilder("registerReceiver: "); 14644 sb.append(Binder.getCallingUid()); sb.append('/'); 14645 sb.append(receiverId == null ? "null" : receiverId); sb.append('/'); 14646 final int actionsCount = filter.safeCountActions(); 14647 if (actionsCount > 0) { 14648 for (int i = 0; i < actionsCount; ++i) { 14649 sb.append(filter.getAction(i)); 14650 if (i != actionsCount - 1) sb.append(','); 14651 } 14652 } else { 14653 sb.append("null"); 14654 } 14655 sb.append('/'); 14656 sb.append('u'); sb.append(userId); sb.append('/'); 14657 sb.append(receiver == null ? "null" : receiver.asBinder()); 14658 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString()); 14659 } 14660 } 14661 traceRegistrationEnd()14662 private static void traceRegistrationEnd() { 14663 if (!Flags.traceReceiverRegistration()) { 14664 return; 14665 } 14666 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 14667 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 14668 } 14669 } 14670 registerReceiverWithFeatureTraced(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)14671 private Intent registerReceiverWithFeatureTraced(IApplicationThread caller, 14672 String callerPackage, String callerFeatureId, String receiverId, 14673 IIntentReceiver receiver, IntentFilter filter, String permission, 14674 int userId, int flags) { 14675 enforceNotIsolatedCaller("registerReceiver"); 14676 ArrayList<StickyBroadcast> stickyBroadcasts = null; 14677 ProcessRecord callerApp = null; 14678 final boolean visibleToInstantApps 14679 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0; 14680 14681 int callingUid; 14682 int callingPid; 14683 boolean instantApp; 14684 synchronized (mProcLock) { 14685 callerApp = getRecordForAppLOSP(caller); 14686 if (callerApp == null) { 14687 Slog.w(TAG, "registerReceiverWithFeature: no app for " + caller); 14688 return null; 14689 } 14690 if (callerApp.info.uid != SYSTEM_UID 14691 && !callerApp.getPkgList().containsKey(callerPackage) 14692 && !"android".equals(callerPackage)) { 14693 throw new SecurityException("Given caller package " + callerPackage 14694 + " is not running in process " + callerApp); 14695 } 14696 callingUid = callerApp.info.uid; 14697 callingPid = callerApp.getPid(); 14698 14699 instantApp = isInstantApp(callerApp, callerPackage, callingUid); 14700 } 14701 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 14702 ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 14703 14704 // Warn if system internals are registering for important broadcasts 14705 // without also using a priority to ensure they process the event 14706 // before normal apps hear about it 14707 if (UserHandle.isCore(callingUid)) { 14708 final int priority = filter.getPriority(); 14709 final boolean systemPriority = (priority >= IntentFilter.SYSTEM_HIGH_PRIORITY) 14710 || (priority <= IntentFilter.SYSTEM_LOW_PRIORITY); 14711 if (!systemPriority) { 14712 final int N = filter.countActions(); 14713 for (int i = 0; i < N; i++) { 14714 // TODO: expand to additional important broadcasts over time 14715 final String action = filter.getAction(i); 14716 if (action.startsWith("android.intent.action.USER_") 14717 || action.startsWith("android.intent.action.PACKAGE_") 14718 || action.startsWith("android.intent.action.UID_") 14719 || action.startsWith("android.intent.action.EXTERNAL_") 14720 || action.startsWith("android.bluetooth.") 14721 || action.equals(Intent.ACTION_SHUTDOWN)) { 14722 if (DEBUG_BROADCAST) { 14723 Slog.wtf(TAG, 14724 "System internals registering for " + filter.toLongString() 14725 + " with app priority; this will race with apps!", 14726 new Throwable()); 14727 } 14728 14729 // When undefined, assume that system internals need 14730 // to hear about the event first; they can use 14731 // SYSTEM_LOW_PRIORITY if they need to hear last 14732 if (priority == 0) { 14733 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 14734 } 14735 break; 14736 } 14737 } 14738 } 14739 } 14740 14741 Iterator<String> actions = filter.actionsIterator(); 14742 if (actions == null) { 14743 ArrayList<String> noAction = new ArrayList<String>(1); 14744 noAction.add(null); 14745 actions = noAction.iterator(); 14746 } 14747 boolean onlyProtectedBroadcasts = true; 14748 14749 // Collect stickies of users and check if broadcast is only registered for protected 14750 // broadcasts 14751 int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) }; 14752 synchronized (mStickyBroadcasts) { 14753 while (actions.hasNext()) { 14754 String action = actions.next(); 14755 for (int id : userIds) { 14756 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = 14757 mStickyBroadcasts.get(id); 14758 if (stickies != null) { 14759 ArrayList<StickyBroadcast> broadcasts = stickies.get(action); 14760 if (broadcasts != null) { 14761 if (stickyBroadcasts == null) { 14762 stickyBroadcasts = new ArrayList<>(); 14763 } 14764 stickyBroadcasts.addAll(broadcasts); 14765 } 14766 } 14767 } 14768 if (onlyProtectedBroadcasts) { 14769 try { 14770 onlyProtectedBroadcasts &= 14771 AppGlobals.getPackageManager().isProtectedBroadcast(action); 14772 } catch (RemoteException e) { 14773 onlyProtectedBroadcasts = false; 14774 Slog.w(TAG, "Remote exception", e); 14775 } 14776 } 14777 } 14778 } 14779 14780 if (Process.isSdkSandboxUid(Binder.getCallingUid())) { 14781 SdkSandboxManagerLocal sdkSandboxManagerLocal = 14782 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 14783 if (sdkSandboxManagerLocal == null) { 14784 throw new IllegalStateException("SdkSandboxManagerLocal not found when checking" 14785 + " whether SDK sandbox uid can register to broadcast receivers."); 14786 } 14787 if (!sdkSandboxManagerLocal.canRegisterBroadcastReceiver( 14788 /*IntentFilter=*/ filter, flags, onlyProtectedBroadcasts)) { 14789 throw new SecurityException("SDK sandbox not allowed to register receiver" 14790 + " with the given IntentFilter: " + filter.toLongString()); 14791 } 14792 } 14793 14794 // If the change is enabled, but neither exported or not exported is set, we need to log 14795 // an error so the consumer can know to explicitly set the value for their flag. 14796 // If the caller is registering for a sticky broadcast with a null receiver, we won't 14797 // require a flag 14798 final boolean explicitExportStateDefined = 14799 (flags & (Context.RECEIVER_EXPORTED | Context.RECEIVER_NOT_EXPORTED)) != 0; 14800 if (((flags & Context.RECEIVER_EXPORTED) != 0) && ( 14801 (flags & Context.RECEIVER_NOT_EXPORTED) != 0)) { 14802 throw new IllegalArgumentException( 14803 "Receiver can't specify both RECEIVER_EXPORTED and RECEIVER_NOT_EXPORTED" 14804 + "flag"); 14805 } 14806 14807 // Don't enforce the flag check if we're EITHER registering for only protected 14808 // broadcasts, or the receiver is null (a sticky broadcast). Sticky broadcasts should 14809 // not be used generally, so we will be marking them as exported by default 14810 boolean requireExplicitFlagForDynamicReceivers = CompatChanges.isChangeEnabled( 14811 DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED, callingUid); 14812 14813 // A receiver that is visible to instant apps must also be exported. 14814 final boolean unexportedReceiverVisibleToInstantApps = 14815 ((flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0) && ( 14816 (flags & Context.RECEIVER_NOT_EXPORTED) != 0); 14817 if (unexportedReceiverVisibleToInstantApps && requireExplicitFlagForDynamicReceivers) { 14818 throw new IllegalArgumentException( 14819 "Receiver can't specify both RECEIVER_VISIBLE_TO_INSTANT_APPS and " 14820 + "RECEIVER_NOT_EXPORTED flag"); 14821 } 14822 14823 if (!onlyProtectedBroadcasts) { 14824 if (receiver == null && !explicitExportStateDefined) { 14825 // sticky broadcast, no flag specified (flag isn't required) 14826 flags |= Context.RECEIVER_EXPORTED; 14827 } else if (requireExplicitFlagForDynamicReceivers && !explicitExportStateDefined) { 14828 throw new SecurityException( 14829 callerPackage + ": One of RECEIVER_EXPORTED or " 14830 + "RECEIVER_NOT_EXPORTED should be specified when a receiver " 14831 + "isn't being registered exclusively for system broadcasts"); 14832 // Assume default behavior-- flag check is not enforced 14833 } else if (!requireExplicitFlagForDynamicReceivers && ( 14834 (flags & Context.RECEIVER_NOT_EXPORTED) == 0)) { 14835 // Change is not enabled, assume exported unless otherwise specified. 14836 flags |= Context.RECEIVER_EXPORTED; 14837 } 14838 } else if ((flags & Context.RECEIVER_NOT_EXPORTED) == 0) { 14839 flags |= Context.RECEIVER_EXPORTED; 14840 } 14841 14842 // Dynamic receivers are exported by default for versions prior to T 14843 final boolean exported = (flags & Context.RECEIVER_EXPORTED) != 0; 14844 14845 ArrayList<StickyBroadcast> allSticky = null; 14846 if (stickyBroadcasts != null) { 14847 final ContentResolver resolver = mContext.getContentResolver(); 14848 // Look for any matching sticky broadcasts... 14849 for (int i = 0, N = stickyBroadcasts.size(); i < N; i++) { 14850 final StickyBroadcast broadcast = stickyBroadcasts.get(i); 14851 Intent intent = broadcast.intent; 14852 // Don't provided intents that aren't available to instant apps. 14853 if (instantApp && 14854 (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) { 14855 continue; 14856 } 14857 // If intent has scheme "content", it will need to access 14858 // provider that needs to lock mProviderMap in ActivityThread 14859 // and also it may need to wait application response, so we 14860 // cannot lock ActivityManagerService here. 14861 final int match; 14862 if (Flags.avoidResolvingType()) { 14863 match = filter.match(intent.getAction(), broadcast.resolvedDataType, 14864 intent.getScheme(), intent.getData(), intent.getCategories(), 14865 TAG, false /* supportsWildcards */, null /* ignoreActions */, 14866 intent.getExtras()); 14867 } else { 14868 match = filter.match(resolver, intent, true, TAG); 14869 } 14870 if (match >= 0) { 14871 if (allSticky == null) { 14872 allSticky = new ArrayList<>(); 14873 } 14874 allSticky.add(broadcast); 14875 } 14876 } 14877 } 14878 14879 // The first sticky in the list is returned directly back to the client. 14880 Intent sticky = allSticky != null ? allSticky.get(0).intent : null; 14881 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky); 14882 if (receiver == null) { 14883 return sticky; 14884 } 14885 14886 // SafetyNet logging for b/177931370. If any process other than system_server tries to 14887 // listen to this broadcast action, then log it. 14888 if (callingPid != Process.myPid()) { 14889 if (filter.hasAction("com.android.server.net.action.SNOOZE_WARNING") 14890 || filter.hasAction("com.android.server.net.action.SNOOZE_RAPID")) { 14891 EventLog.writeEvent(0x534e4554, "177931370", callingUid, ""); 14892 } 14893 } 14894 14895 synchronized (this) { 14896 IApplicationThread thread; 14897 if (callerApp != null && ((thread = callerApp.getThread()) == null 14898 || thread.asBinder() != caller.asBinder())) { 14899 // Original caller already died 14900 return null; 14901 } 14902 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 14903 if (rl == null) { 14904 rl = new ReceiverList(this, callerApp, callingPid, callingUid, 14905 userId, receiver); 14906 if (rl.app != null) { 14907 final int totalReceiversForApp = rl.app.mReceivers.numberOfReceivers(); 14908 if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) { 14909 throw new IllegalStateException("Too many receivers, total of " 14910 + totalReceiversForApp + ", registered for pid: " 14911 + rl.pid + ", callerPackage: " + callerPackage); 14912 } 14913 rl.app.mReceivers.addReceiver(rl); 14914 } else { 14915 try { 14916 receiver.asBinder().linkToDeath(rl, 0); 14917 } catch (RemoteException e) { 14918 return sticky; 14919 } 14920 rl.linkedToDeath = true; 14921 } 14922 mRegisteredReceivers.put(receiver.asBinder(), rl); 14923 } else if (rl.uid != callingUid) { 14924 throw new IllegalArgumentException( 14925 "Receiver requested to register for uid " + callingUid 14926 + " was previously registered for uid " + rl.uid 14927 + " callerPackage is " + callerPackage); 14928 } else if (rl.pid != callingPid) { 14929 throw new IllegalArgumentException( 14930 "Receiver requested to register for pid " + callingPid 14931 + " was previously registered for pid " + rl.pid 14932 + " callerPackage is " + callerPackage); 14933 } else if (rl.userId != userId) { 14934 throw new IllegalArgumentException( 14935 "Receiver requested to register for user " + userId 14936 + " was previously registered for user " + rl.userId 14937 + " callerPackage is " + callerPackage); 14938 } 14939 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId, 14940 receiverId, permission, callingUid, userId, instantApp, visibleToInstantApps, 14941 exported); 14942 if (rl.containsFilter(filter)) { 14943 Slog.w(TAG, "Receiver with filter " + filter 14944 + " already registered for pid " + rl.pid 14945 + ", callerPackage is " + callerPackage); 14946 } else { 14947 rl.add(bf); 14948 if (!bf.debugCheck()) { 14949 Slog.w(TAG, "==> For Dynamic broadcast"); 14950 } 14951 mReceiverResolver.addFilter(getPackageManagerInternal().snapshot(), bf); 14952 } 14953 14954 // Enqueue broadcasts for all existing stickies that match 14955 // this filter. 14956 if (allSticky != null) { 14957 ArrayList receivers = new ArrayList(); 14958 receivers.add(bf); 14959 sticky = null; 14960 14961 final int stickyCount = allSticky.size(); 14962 for (int i = 0; i < stickyCount; i++) { 14963 final StickyBroadcast broadcast = allSticky.get(i); 14964 final int originalStickyCallingUid = allSticky.get(i).originalCallingUid; 14965 // TODO(b/281889567): consider using checkComponentPermission instead of 14966 // canAccessUnexportedComponents 14967 if (sticky == null && (exported || originalStickyCallingUid == callingUid 14968 || ActivityManager.canAccessUnexportedComponents( 14969 originalStickyCallingUid))) { 14970 sticky = broadcast.intent; 14971 } 14972 BroadcastQueue queue = mBroadcastQueue; 14973 BroadcastRecord r = new BroadcastRecord(queue, broadcast.intent, null, 14974 null, null, -1, -1, false, null, null, null, null, OP_NONE, 14975 BroadcastOptions.makeWithDeferUntilActive(broadcast.deferUntilActive), 14976 receivers, null, null, 0, null, null, false, true, true, -1, 14977 originalStickyCallingUid, BackgroundStartPrivileges.NONE, 14978 false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */, 14979 null /* filterExtrasForReceiver */, 14980 broadcast.originalCallingAppProcessState); 14981 queue.enqueueBroadcastLocked(r); 14982 } 14983 } 14984 14985 return sticky; 14986 } 14987 } 14988 unregisterReceiver(IIntentReceiver receiver)14989 public void unregisterReceiver(IIntentReceiver receiver) { 14990 traceUnregistrationBegin(receiver); 14991 try { 14992 unregisterReceiverTraced(receiver); 14993 } finally { 14994 traceUnregistrationEnd(); 14995 } 14996 } 14997 traceUnregistrationBegin(IIntentReceiver receiver)14998 private static void traceUnregistrationBegin(IIntentReceiver receiver) { 14999 if (!Flags.traceReceiverRegistration()) { 15000 return; 15001 } 15002 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 15003 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, 15004 TextUtils.formatSimple("unregisterReceiver: %d/%s", Binder.getCallingUid(), 15005 receiver == null ? "null" : receiver.asBinder())); 15006 } 15007 } 15008 traceUnregistrationEnd()15009 private static void traceUnregistrationEnd() { 15010 if (!Flags.traceReceiverRegistration()) { 15011 return; 15012 } 15013 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 15014 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 15015 } 15016 } 15017 unregisterReceiverTraced(IIntentReceiver receiver)15018 private void unregisterReceiverTraced(IIntentReceiver receiver) { 15019 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver); 15020 15021 final long origId = Binder.clearCallingIdentity(); 15022 try { 15023 boolean doTrim = false; 15024 synchronized(this) { 15025 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 15026 if (rl != null) { 15027 final BroadcastRecord r = rl.curBroadcast; 15028 if (r != null) { 15029 final boolean doNext = r.queue.finishReceiverLocked( 15030 rl.app, r.resultCode, r.resultData, r.resultExtras, 15031 r.resultAbort, false); 15032 if (doNext) { 15033 doTrim = true; 15034 } 15035 } 15036 if (rl.app != null) { 15037 rl.app.mReceivers.removeReceiver(rl); 15038 } 15039 removeReceiverLocked(rl); 15040 if (rl.linkedToDeath) { 15041 rl.linkedToDeath = false; 15042 rl.receiver.asBinder().unlinkToDeath(rl, 0); 15043 } 15044 } 15045 15046 // If we actually concluded any broadcasts, we might now be able 15047 // to trim the recipients' apps from our working set 15048 if (doTrim) { 15049 trimApplicationsLocked(false, OOM_ADJ_REASON_FINISH_RECEIVER); 15050 return; 15051 } 15052 } 15053 15054 } finally { 15055 Binder.restoreCallingIdentity(origId); 15056 } 15057 } 15058 removeReceiverLocked(ReceiverList rl)15059 void removeReceiverLocked(ReceiverList rl) { 15060 mRegisteredReceivers.remove(rl.receiver.asBinder()); 15061 for (int i = rl.size() - 1; i >= 0; i--) { 15062 mReceiverResolver.removeFilter(rl.get(i)); 15063 } 15064 } 15065 sendPackageBroadcastLocked(int cmd, String[] packages, int userId)15066 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 15067 mProcessList.sendPackageBroadcastLocked(cmd, packages, userId); 15068 } 15069 collectReceiverComponents( Intent intent, String resolvedType, int callingUid, int callingPid, int[] users, int[] broadcastAllowList)15070 private List<ResolveInfo> collectReceiverComponents( 15071 Intent intent, String resolvedType, int callingUid, int callingPid, 15072 int[] users, int[] broadcastAllowList) { 15073 // TODO: come back and remove this assumption to triage all broadcasts 15074 long pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING; 15075 15076 List<ResolveInfo> receivers = null; 15077 HashSet<ComponentName> singleUserReceivers = null; 15078 boolean scannedFirstReceivers = false; 15079 for (int user : users) { 15080 // Skip users that have Shell restrictions 15081 if (callingUid == SHELL_UID 15082 && mUserController.hasUserRestriction( 15083 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) { 15084 continue; 15085 } 15086 List<ResolveInfo> newReceivers = mPackageManagerInt.queryIntentReceivers( 15087 intent, resolvedType, pmFlags, callingUid, callingPid, user, /* forSend */true); 15088 if (user != UserHandle.USER_SYSTEM && newReceivers != null) { 15089 // If this is not the system user, we need to check for 15090 // any receivers that should be filtered out. 15091 for (int i = 0; i < newReceivers.size(); i++) { 15092 ResolveInfo ri = newReceivers.get(i); 15093 if ((ri.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 15094 newReceivers.remove(i); 15095 i--; 15096 } 15097 } 15098 } 15099 // Replace the alias receivers with their targets. 15100 if (newReceivers != null) { 15101 for (int i = newReceivers.size() - 1; i >= 0; i--) { 15102 final ResolveInfo ri = newReceivers.get(i); 15103 final Resolution<ResolveInfo> resolution = 15104 mComponentAliasResolver.resolveReceiver(intent, ri, resolvedType, 15105 pmFlags, user, callingUid, callingPid); 15106 if (resolution == null) { 15107 // It was an alias, but the target was not found. 15108 newReceivers.remove(i); 15109 continue; 15110 } 15111 if (resolution.isAlias()) { 15112 newReceivers.set(i, resolution.getTarget()); 15113 } 15114 } 15115 } 15116 if (newReceivers != null && newReceivers.size() == 0) { 15117 newReceivers = null; 15118 } 15119 15120 if (receivers == null) { 15121 receivers = newReceivers; 15122 } else if (newReceivers != null) { 15123 // We need to concatenate the additional receivers 15124 // found with what we have do far. This would be easy, 15125 // but we also need to de-dup any receivers that are 15126 // singleUser. 15127 if (!scannedFirstReceivers) { 15128 // Collect any single user receivers we had already retrieved. 15129 scannedFirstReceivers = true; 15130 for (int i = 0; i < receivers.size(); i++) { 15131 ResolveInfo ri = receivers.get(i); 15132 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 15133 ComponentName cn = new ComponentName( 15134 ri.activityInfo.packageName, ri.activityInfo.name); 15135 if (singleUserReceivers == null) { 15136 singleUserReceivers = new HashSet<ComponentName>(); 15137 } 15138 singleUserReceivers.add(cn); 15139 } 15140 } 15141 } 15142 // Add the new results to the existing results, tracking 15143 // and de-dupping single user receivers. 15144 for (int i = 0; i < newReceivers.size(); i++) { 15145 ResolveInfo ri = newReceivers.get(i); 15146 if ((ri.activityInfo.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 15147 ComponentName cn = new ComponentName( 15148 ri.activityInfo.packageName, ri.activityInfo.name); 15149 if (singleUserReceivers == null) { 15150 singleUserReceivers = new HashSet<ComponentName>(); 15151 } 15152 if (!singleUserReceivers.contains(cn)) { 15153 singleUserReceivers.add(cn); 15154 receivers.add(ri); 15155 } 15156 } else { 15157 receivers.add(ri); 15158 } 15159 } 15160 } 15161 } 15162 if (receivers != null && broadcastAllowList != null) { 15163 for (int i = receivers.size() - 1; i >= 0; i--) { 15164 final int receiverAppId = UserHandle.getAppId( 15165 receivers.get(i).activityInfo.applicationInfo.uid); 15166 if (receiverAppId >= Process.FIRST_APPLICATION_UID 15167 && Arrays.binarySearch(broadcastAllowList, receiverAppId) < 0) { 15168 receivers.remove(i); 15169 } 15170 } 15171 } 15172 return receivers; 15173 } 15174 checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)15175 private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, 15176 String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) { 15177 if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 15178 // Don't yell about broadcasts sent via shell 15179 return; 15180 } 15181 15182 final String action = intent.getAction(); 15183 if (isProtectedBroadcast 15184 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action) 15185 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action) 15186 || Intent.ACTION_MEDIA_BUTTON.equals(action) 15187 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action) 15188 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action) 15189 || Intent.ACTION_MASTER_CLEAR.equals(action) 15190 || Intent.ACTION_FACTORY_RESET.equals(action) 15191 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 15192 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) 15193 || TelephonyManager.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action) 15194 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action) 15195 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action) 15196 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) { 15197 // Broadcast is either protected, or it's a public action that 15198 // we've relaxed, so it's fine for system internals to send. 15199 return; 15200 } 15201 15202 // This broadcast may be a problem... but there are often system components that 15203 // want to send an internal broadcast to themselves, which is annoying to have to 15204 // explicitly list each action as a protected broadcast, so we will check for that 15205 // one safe case and allow it: an explicit broadcast, only being received by something 15206 // that has protected itself. 15207 if (intent.getPackage() != null || intent.getComponent() != null) { 15208 if (receivers == null || receivers.size() == 0) { 15209 // Intent is explicit and there's no receivers. 15210 // This happens, e.g. , when a system component sends a broadcast to 15211 // its own runtime receiver, and there's no manifest receivers for it, 15212 // because this method is called twice for each broadcast, 15213 // for runtime receivers and manifest receivers and the later check would find 15214 // no receivers. 15215 return; 15216 } 15217 boolean allProtected = true; 15218 for (int i = receivers.size()-1; i >= 0; i--) { 15219 Object target = receivers.get(i); 15220 if (target instanceof ResolveInfo) { 15221 ResolveInfo ri = (ResolveInfo)target; 15222 if (ri.activityInfo.exported && ri.activityInfo.permission == null) { 15223 allProtected = false; 15224 break; 15225 } 15226 } else { 15227 BroadcastFilter bf = (BroadcastFilter)target; 15228 if (bf.exported && bf.requiredPermission == null) { 15229 allProtected = false; 15230 break; 15231 } 15232 } 15233 } 15234 if (allProtected) { 15235 // All safe! 15236 return; 15237 } 15238 } 15239 15240 // The vast majority of broadcasts sent from system internals 15241 // should be protected to avoid security holes, so yell loudly 15242 // to ensure we examine these cases. 15243 if (callerApp != null) { 15244 Log.wtf(TAG, "Sending non-protected broadcast " + action 15245 + " from system " + callerApp.toShortString() + " pkg " + callerPackage, 15246 new Throwable()); 15247 } else { 15248 Log.wtf(TAG, "Sending non-protected broadcast " + action 15249 + " from system uid " + UserHandle.formatUid(callingUid) 15250 + " pkg " + callerPackage, 15251 new Throwable()); 15252 } 15253 } 15254 15255 // Apply permission policy around the use of specific broadcast options enforceBroadcastOptionPermissionsInternal( @ullable Bundle options, int callingUid)15256 void enforceBroadcastOptionPermissionsInternal( 15257 @Nullable Bundle options, int callingUid) { 15258 enforceBroadcastOptionPermissionsInternal(BroadcastOptions.fromBundleNullable(options), 15259 callingUid); 15260 } 15261 enforceBroadcastOptionPermissionsInternal( @ullable BroadcastOptions options, int callingUid)15262 void enforceBroadcastOptionPermissionsInternal( 15263 @Nullable BroadcastOptions options, int callingUid) { 15264 if (options != null && callingUid != Process.SYSTEM_UID) { 15265 if (options.isAlarmBroadcast()) { 15266 if (DEBUG_BROADCAST_LIGHT) { 15267 Slog.w(TAG, "Non-system caller " + callingUid 15268 + " may not flag broadcast as alarm"); 15269 } 15270 throw new SecurityException( 15271 "Non-system callers may not flag broadcasts as alarm"); 15272 } 15273 if (options.isInteractive()) { 15274 enforceCallingPermission( 15275 android.Manifest.permission.BROADCAST_OPTION_INTERACTIVE, 15276 "setInteractive"); 15277 } 15278 } 15279 } 15280 15281 @GuardedBy("this") broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, String callerFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId)15282 final int broadcastIntentLocked(ProcessRecord callerApp, 15283 String callerPackage, String callerFeatureId, Intent intent, String resolvedType, 15284 IIntentReceiver resultTo, int resultCode, String resultData, 15285 Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, 15286 String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered, 15287 boolean sticky, int callingPid, 15288 int callingUid, int realCallingUid, int realCallingPid, int userId) { 15289 return broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, intent, 15290 resolvedType, null, resultTo, resultCode, resultData, resultExtras, 15291 requiredPermissions, excludedPermissions, excludedPackages, appOp, bOptions, 15292 ordered, sticky, callingPid, callingUid, realCallingUid, realCallingPid, userId, 15293 BackgroundStartPrivileges.NONE, 15294 null /* broadcastAllowList */, null /* filterExtrasForReceiver */); 15295 } 15296 15297 @GuardedBy("this") broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver)15298 final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, 15299 @Nullable String callerFeatureId, Intent intent, String resolvedType, 15300 ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, 15301 Bundle resultExtras, String[] requiredPermissions, 15302 String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, 15303 boolean ordered, boolean sticky, int callingPid, int callingUid, 15304 int realCallingUid, int realCallingPid, int userId, 15305 BackgroundStartPrivileges backgroundStartPrivileges, 15306 @Nullable int[] broadcastAllowList, 15307 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver) { 15308 final int cookie = traceBroadcastIntentBegin(intent, resultTo, ordered, sticky, 15309 callingUid, realCallingUid, userId); 15310 try { 15311 final int res = broadcastIntentLockedTraced(callerApp, callerPackage, callerFeatureId, 15312 intent, resolvedType, resultToApp, resultTo, resultCode, resultData, 15313 resultExtras, requiredPermissions, excludedPermissions, excludedPackages, 15314 appOp, BroadcastOptions.fromBundleNullable(bOptions), ordered, sticky, 15315 callingPid, callingUid, realCallingUid, realCallingPid, userId, 15316 backgroundStartPrivileges, broadcastAllowList, filterExtrasForReceiver); 15317 return res; 15318 } finally { 15319 traceBroadcastIntentEnd(cookie); 15320 } 15321 } 15322 traceBroadcastIntentBegin(Intent intent, IIntentReceiver resultTo, boolean ordered, boolean sticky, int callingUid, int realCallingUid, int userId)15323 private static int traceBroadcastIntentBegin(Intent intent, IIntentReceiver resultTo, 15324 boolean ordered, boolean sticky, int callingUid, int realCallingUid, int userId) { 15325 if (!Flags.traceReceiverRegistration()) { 15326 return BroadcastQueue.traceBegin("broadcastIntentLockedTraced"); 15327 } 15328 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 15329 final StringBuilder sb = new StringBuilder("broadcastIntent: "); 15330 sb.append(callingUid); sb.append('/'); 15331 final String action = intent.getAction(); 15332 sb.append(action == null ? null : action); sb.append('/'); 15333 sb.append("0x"); sb.append(Integer.toHexString(intent.getFlags())); sb.append('/'); 15334 sb.append(ordered ? "O" : "_"); 15335 sb.append(sticky ? "S" : "_"); 15336 sb.append(resultTo != null ? "C" : "_"); 15337 sb.append('/'); 15338 sb.append('u'); sb.append(userId); 15339 if (callingUid != realCallingUid) { 15340 sb.append('/'); 15341 sb.append("sender="); sb.append(realCallingUid); 15342 } 15343 return BroadcastQueue.traceBegin(sb.toString()); 15344 } 15345 return 0; 15346 } 15347 traceBroadcastIntentEnd(int cookie)15348 private static void traceBroadcastIntentEnd(int cookie) { 15349 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 15350 BroadcastQueue.traceEnd(cookie); 15351 } 15352 } 15353 15354 @GuardedBy("this") broadcastIntentLockedTraced(ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, BroadcastOptions brOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver)15355 final int broadcastIntentLockedTraced(ProcessRecord callerApp, String callerPackage, 15356 @Nullable String callerFeatureId, Intent intent, String resolvedType, 15357 ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, 15358 Bundle resultExtras, String[] requiredPermissions, 15359 String[] excludedPermissions, String[] excludedPackages, int appOp, 15360 BroadcastOptions brOptions, boolean ordered, boolean sticky, int callingPid, 15361 int callingUid, int realCallingUid, int realCallingPid, int userId, 15362 BackgroundStartPrivileges backgroundStartPrivileges, 15363 @Nullable int[] broadcastAllowList, 15364 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver) { 15365 // Ensure all internal loopers are registered for idle checks 15366 BroadcastLoopers.addMyLooper(); 15367 15368 if (Process.isSdkSandboxUid(realCallingUid)) { 15369 final SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager( 15370 SdkSandboxManagerLocal.class); 15371 if (sdkSandboxManagerLocal == null) { 15372 throw new IllegalStateException("SdkSandboxManagerLocal not found when sending" 15373 + " a broadcast from an SDK sandbox uid."); 15374 } 15375 if (!sdkSandboxManagerLocal.canSendBroadcast(intent)) { 15376 throw new SecurityException( 15377 "Intent " + intent.getAction() + " may not be broadcast from an SDK sandbox" 15378 + " uid. Given caller package " + callerPackage + " (pid=" + callingPid 15379 + ", realCallingUid=" + realCallingUid + ", callingUid= " + callingUid 15380 + ")"); 15381 } 15382 } 15383 15384 if ((resultTo != null) && (resultToApp == null)) { 15385 if (resultTo.asBinder() instanceof BinderProxy) { 15386 // Warn when requesting results without a way to deliver them 15387 Slog.wtf(TAG, "Sending broadcast " + intent.getAction() 15388 + " with resultTo requires resultToApp", new Throwable()); 15389 } else { 15390 // If not a BinderProxy above, then resultTo is an in-process 15391 // receiver, so splice in system_server process 15392 resultToApp = getProcessRecordLocked("system", SYSTEM_UID); 15393 } 15394 } 15395 15396 intent = new Intent(intent); 15397 15398 final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid); 15399 // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS 15400 if (callerInstantApp) { 15401 intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 15402 } 15403 15404 if (userId == UserHandle.USER_ALL && broadcastAllowList != null) { 15405 Slog.e(TAG, "broadcastAllowList only applies when sending to individual users. " 15406 + "Assuming restrictive whitelist."); 15407 broadcastAllowList = new int[]{}; 15408 } 15409 15410 // By default broadcasts do not go to stopped apps. 15411 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 15412 15413 // If we have not finished booting, don't allow this to launch new processes. 15414 if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 15415 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 15416 } 15417 15418 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 15419 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent 15420 + " ordered=" + ordered + " userid=" + userId 15421 + " options=" + (brOptions == null ? "null" : brOptions.toBundle())); 15422 if ((resultTo != null) && !ordered) { 15423 if (!UserHandle.isCore(callingUid)) { 15424 String msg = "Unauthorized unordered resultTo broadcast " 15425 + intent + " sent from uid " + callingUid; 15426 Slog.w(TAG, msg); 15427 throw new SecurityException(msg); 15428 } 15429 } 15430 15431 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 15432 ALLOW_NON_FULL, "broadcast", callerPackage); 15433 15434 // Make sure that the user who is receiving this broadcast or its parent is running. 15435 // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps. 15436 if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) { 15437 if ((callingUid != SYSTEM_UID 15438 || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) 15439 && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { 15440 Slog.w(TAG, "Skipping broadcast of " + intent 15441 + ": user " + userId + " and its parent (if any) are stopped"); 15442 scheduleCanceledResultTo(resultToApp, resultTo, intent, userId, 15443 brOptions, callingUid, callerPackage); 15444 return ActivityManager.BROADCAST_FAILED_USER_STOPPED; 15445 } 15446 } 15447 15448 final String action = intent.getAction(); 15449 if (brOptions != null) { 15450 if (brOptions.getTemporaryAppAllowlistDuration() > 0) { 15451 // See if the caller is allowed to do this. Note we are checking against 15452 // the actual real caller (not whoever provided the operation as say a 15453 // PendingIntent), because that who is actually supplied the arguments. 15454 if (checkComponentPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, 15455 realCallingPid, realCallingUid, -1, true) 15456 != PackageManager.PERMISSION_GRANTED 15457 && checkComponentPermission(START_ACTIVITIES_FROM_BACKGROUND, 15458 realCallingPid, realCallingUid, -1, true) 15459 != PackageManager.PERMISSION_GRANTED 15460 && checkComponentPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, 15461 realCallingPid, realCallingUid, -1, true) 15462 != PackageManager.PERMISSION_GRANTED) { 15463 String msg = "Permission Denial: " + intent.getAction() 15464 + " broadcast from " + callerPackage + " (pid=" + callingPid 15465 + ", uid=" + callingUid + ")" 15466 + " requires " 15467 + CHANGE_DEVICE_IDLE_TEMP_WHITELIST + " or " 15468 + START_ACTIVITIES_FROM_BACKGROUND + " or " 15469 + START_FOREGROUND_SERVICES_FROM_BACKGROUND; 15470 Slog.w(TAG, msg); 15471 throw new SecurityException(msg); 15472 } 15473 } 15474 if (brOptions.isDontSendToRestrictedApps() 15475 && !isUidActiveLOSP(callingUid) 15476 && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) { 15477 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage 15478 + " has background restrictions"); 15479 return ActivityManager.START_CANCELED; 15480 } 15481 if (brOptions.allowsBackgroundActivityStarts()) { 15482 // See if the caller is allowed to do this. Note we are checking against 15483 // the actual real caller (not whoever provided the operation as say a 15484 // PendingIntent), because that who is actually supplied the arguments. 15485 if (checkComponentPermission( 15486 android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND, 15487 realCallingPid, realCallingUid, -1, true) 15488 != PackageManager.PERMISSION_GRANTED) { 15489 String msg = "Permission Denial: " + intent.getAction() 15490 + " broadcast from " + callerPackage + " (pid=" + callingPid 15491 + ", uid=" + callingUid + ")" 15492 + " requires " 15493 + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; 15494 Slog.w(TAG, msg); 15495 throw new SecurityException(msg); 15496 } else { 15497 // We set the token to null since if it wasn't for it we'd allow anyway here 15498 backgroundStartPrivileges = BackgroundStartPrivileges.ALLOW_BAL; 15499 } 15500 } 15501 15502 if (brOptions.getIdForResponseEvent() > 0) { 15503 enforcePermission(android.Manifest.permission.ACCESS_BROADCAST_RESPONSE_STATS, 15504 callingPid, callingUid, "recordResponseEventWhileInBackground"); 15505 } 15506 } 15507 15508 // Verify that protected broadcasts are only being sent by system code, 15509 // and that system code is only sending protected broadcasts. 15510 final boolean isProtectedBroadcast; 15511 try { 15512 isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action); 15513 } catch (RemoteException e) { 15514 Slog.w(TAG, "Remote exception", e); 15515 scheduleCanceledResultTo(resultToApp, resultTo, intent, 15516 userId, brOptions, callingUid, callerPackage); 15517 return ActivityManager.BROADCAST_SUCCESS; 15518 } 15519 15520 final boolean isCallerSystem; 15521 switch (UserHandle.getAppId(callingUid)) { 15522 case ROOT_UID: 15523 case SYSTEM_UID: 15524 case PHONE_UID: 15525 case BLUETOOTH_UID: 15526 case NFC_UID: 15527 case SE_UID: 15528 case NETWORK_STACK_UID: 15529 isCallerSystem = true; 15530 break; 15531 default: 15532 isCallerSystem = (callerApp != null) && callerApp.isPersistent(); 15533 break; 15534 } 15535 15536 // First line security check before anything else: stop non-system apps from 15537 // sending protected broadcasts. 15538 if (!isCallerSystem) { 15539 if (isProtectedBroadcast) { 15540 String msg = "Permission Denial: not allowed to send broadcast " 15541 + action + " from pid=" 15542 + callingPid + ", uid=" + callingUid; 15543 Slog.w(TAG, msg); 15544 throw new SecurityException(msg); 15545 15546 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 15547 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { 15548 // Special case for compatibility: we don't want apps to send this, 15549 // but historically it has not been protected and apps may be using it 15550 // to poke their own app widget. So, instead of making it protected, 15551 // just limit it to the caller. 15552 if (callerPackage == null) { 15553 String msg = "Permission Denial: not allowed to send broadcast " 15554 + action + " from unknown caller."; 15555 Slog.w(TAG, msg); 15556 throw new SecurityException(msg); 15557 } else if (intent.getComponent() != null) { 15558 // They are good enough to send to an explicit component... verify 15559 // it is being sent to the calling app. 15560 if (!intent.getComponent().getPackageName().equals( 15561 callerPackage)) { 15562 String msg = "Permission Denial: not allowed to send broadcast " 15563 + action + " to " 15564 + intent.getComponent().getPackageName() + " from " 15565 + callerPackage; 15566 Slog.w(TAG, msg); 15567 throw new SecurityException(msg); 15568 } 15569 } else { 15570 // Limit broadcast to their own package. 15571 intent.setPackage(callerPackage); 15572 } 15573 } 15574 } 15575 15576 boolean timeoutExempt = false; 15577 15578 if (action != null) { 15579 if (getBackgroundLaunchBroadcasts().contains(action)) { 15580 if (DEBUG_BACKGROUND_CHECK) { 15581 Slog.i(TAG, "Broadcast action " + action + " forcing include-background"); 15582 } 15583 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 15584 } 15585 15586 // TODO: b/329211459 - Remove this after background remote intent is fixed. 15587 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH) 15588 && getWearRemoteIntentAction().equals(action)) { 15589 final int callerProcState = callerApp != null 15590 ? callerApp.getCurProcState() 15591 : ActivityManager.PROCESS_STATE_NONEXISTENT; 15592 if (ActivityManager.RunningAppProcessInfo.procStateToImportance(callerProcState) 15593 > ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { 15594 return ActivityManager.START_CANCELED; 15595 } 15596 } 15597 15598 switch (action) { 15599 case Intent.ACTION_MEDIA_SCANNER_SCAN_FILE: 15600 UserManagerInternal umInternal = LocalServices.getService( 15601 UserManagerInternal.class); 15602 UserInfo userInfo = umInternal.getUserInfo(userId); 15603 if (userInfo != null && userInfo.isCloneProfile()) { 15604 userId = umInternal.getProfileParentId(userId); 15605 } 15606 break; 15607 case Intent.ACTION_UID_REMOVED: 15608 case Intent.ACTION_PACKAGE_REMOVED: 15609 case Intent.ACTION_PACKAGE_CHANGED: 15610 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 15611 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 15612 case Intent.ACTION_PACKAGES_SUSPENDED: 15613 case Intent.ACTION_PACKAGES_UNSUSPENDED: 15614 // Handle special intents: if this broadcast is from the package 15615 // manager about a package being removed, we need to remove all of 15616 // its activities from the history stack. 15617 if (checkComponentPermission( 15618 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 15619 callingPid, callingUid, -1, true) 15620 != PackageManager.PERMISSION_GRANTED) { 15621 String msg = "Permission Denial: " + intent.getAction() 15622 + " broadcast from " + callerPackage + " (pid=" + callingPid 15623 + ", uid=" + callingUid + ")" 15624 + " requires " 15625 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 15626 Slog.w(TAG, msg); 15627 throw new SecurityException(msg); 15628 } 15629 switch (action) { 15630 case Intent.ACTION_UID_REMOVED: 15631 final int uid = getUidFromIntent(intent); 15632 if (uid >= 0) { 15633 mBatteryStatsService.removeUid(uid); 15634 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 15635 mAppOpsService.resetAllModes(UserHandle.getUserId(uid), 15636 intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME)); 15637 } else { 15638 mAppOpsService.uidRemoved(uid); 15639 mServices.onUidRemovedLocked(uid); 15640 } 15641 } 15642 break; 15643 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 15644 // If resources are unavailable just force stop all those packages 15645 // and flush the attribute cache as well. 15646 String list[] = 15647 intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 15648 if (list != null && list.length > 0) { 15649 for (int i = 0; i < list.length; i++) { 15650 forceStopPackageLocked(list[i], -1, false, true, true, 15651 false, false, false, userId, "storage unmount"); 15652 } 15653 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 15654 sendPackageBroadcastLocked( 15655 ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE, 15656 list, userId); 15657 } 15658 break; 15659 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 15660 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 15661 break; 15662 case Intent.ACTION_PACKAGE_REMOVED: 15663 case Intent.ACTION_PACKAGE_CHANGED: 15664 Uri data = intent.getData(); 15665 String ssp; 15666 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 15667 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action); 15668 final boolean replacing = 15669 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 15670 final boolean killProcess = 15671 !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false); 15672 final boolean fullUninstall = removed && !replacing; 15673 15674 if (removed) { 15675 if (killProcess) { 15676 forceStopPackageLocked(ssp, UserHandle.getAppId( 15677 intent.getIntExtra(Intent.EXTRA_UID, -1)), 15678 false, true, true, false, fullUninstall, false, 15679 userId, "pkg removed"); 15680 getPackageManagerInternal() 15681 .onPackageProcessKilledForUninstall(ssp); 15682 } else { 15683 // Kill any app zygotes always, since they can't fork new 15684 // processes with references to the old code 15685 forceStopAppZygoteLocked(ssp, UserHandle.getAppId( 15686 intent.getIntExtra(Intent.EXTRA_UID, -1)), 15687 userId); 15688 } 15689 final int cmd = killProcess 15690 ? ApplicationThreadConstants.PACKAGE_REMOVED 15691 : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL; 15692 sendPackageBroadcastLocked(cmd, 15693 new String[] {ssp}, userId); 15694 if (fullUninstall) { 15695 // Remove all permissions granted from/to this package 15696 mUgmInternal.removeUriPermissionsForPackage(ssp, userId, 15697 true, false); 15698 15699 mAtmInternal.removeRecentTasksByPackageName(ssp, userId); 15700 15701 mServices.forceStopPackageLocked(ssp, userId); 15702 mAtmInternal.onPackageUninstalled(ssp, userId); 15703 mBatteryStatsService.notePackageUninstalled(ssp); 15704 } 15705 } else { 15706 if (killProcess) { 15707 int reason; 15708 int subReason; 15709 if (replacing) { 15710 reason = ApplicationExitInfo.REASON_PACKAGE_UPDATED; 15711 subReason = ApplicationExitInfo.SUBREASON_UNKNOWN; 15712 } else { 15713 reason = 15714 ApplicationExitInfo.REASON_PACKAGE_STATE_CHANGE; 15715 subReason = ApplicationExitInfo.SUBREASON_UNKNOWN; 15716 } 15717 15718 final int extraUid = intent.getIntExtra(Intent.EXTRA_UID, 15719 -1); 15720 synchronized (mProcLock) { 15721 mProcessList.killPackageProcessesLSP(ssp, 15722 UserHandle.getAppId(extraUid), 15723 userId, ProcessList.INVALID_ADJ, 15724 reason, 15725 subReason, 15726 "change " + ssp); 15727 } 15728 } 15729 cleanupDisabledPackageComponentsLocked(ssp, userId, 15730 intent.getStringArrayExtra( 15731 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST)); 15732 mServices.schedulePendingServiceStartLocked(ssp, userId); 15733 } 15734 } 15735 break; 15736 case Intent.ACTION_PACKAGES_SUSPENDED: 15737 case Intent.ACTION_PACKAGES_UNSUSPENDED: 15738 final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals( 15739 intent.getAction()); 15740 final String[] packageNames = intent.getStringArrayExtra( 15741 Intent.EXTRA_CHANGED_PACKAGE_LIST); 15742 final int userIdExtra = intent.getIntExtra( 15743 Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 15744 15745 mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended, 15746 userIdExtra); 15747 15748 final boolean quarantined = intent.getBooleanExtra( 15749 Intent.EXTRA_QUARANTINED, false); 15750 if (suspended && quarantined && packageNames != null) { 15751 for (int i = 0; i < packageNames.length; i++) { 15752 forceStopPackage(packageNames[i], userId, 15753 ActivityManager.FLAG_OR_STOPPED, "quarantined"); 15754 } 15755 } 15756 15757 break; 15758 } 15759 break; 15760 case Intent.ACTION_PACKAGE_REPLACED: 15761 { 15762 final Uri data = intent.getData(); 15763 final String ssp; 15764 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 15765 ApplicationInfo aInfo = null; 15766 try { 15767 aInfo = AppGlobals.getPackageManager() 15768 .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId); 15769 } catch (RemoteException ignore) {} 15770 if (aInfo == null) { 15771 Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:" 15772 + " ssp=" + ssp + " data=" + data); 15773 scheduleCanceledResultTo(resultToApp, resultTo, intent, 15774 userId, brOptions, callingUid, callerPackage); 15775 return ActivityManager.BROADCAST_SUCCESS; 15776 } 15777 updateAssociationForApp(aInfo); 15778 mAtmInternal.onPackageReplaced(aInfo); 15779 mServices.updateServiceApplicationInfoLocked(aInfo); 15780 sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED, 15781 new String[] {ssp}, userId); 15782 } 15783 break; 15784 } 15785 case Intent.ACTION_PACKAGE_ADDED: 15786 { 15787 // Special case for adding a package: by default turn on compatibility mode. 15788 Uri data = intent.getData(); 15789 String ssp; 15790 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 15791 final boolean replacing = 15792 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 15793 mAtmInternal.onPackageAdded(ssp, replacing); 15794 15795 try { 15796 ApplicationInfo ai = AppGlobals.getPackageManager(). 15797 getApplicationInfo(ssp, STOCK_PM_FLAGS, 0); 15798 mBatteryStatsService.notePackageInstalled(ssp, 15799 ai != null ? ai.longVersionCode : 0); 15800 } catch (RemoteException e) { 15801 } 15802 } 15803 break; 15804 } 15805 case Intent.ACTION_PACKAGE_DATA_CLEARED: 15806 { 15807 Uri data = intent.getData(); 15808 String ssp; 15809 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 15810 mAtmInternal.onPackageDataCleared(ssp, userId); 15811 } 15812 break; 15813 } 15814 case Intent.ACTION_TIMEZONE_CHANGED: 15815 // If this is the time zone changed action, queue up a message that will reset 15816 // the timezone of all currently running processes. This message will get 15817 // queued up before the broadcast happens. 15818 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 15819 break; 15820 case Intent.ACTION_TIME_CHANGED: 15821 // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between 15822 // the tri-state value it may contain and "unknown". 15823 // For convenience we re-use the Intent extra values. 15824 final int NO_EXTRA_VALUE_FOUND = -1; 15825 final int timeFormatPreferenceMsgValue = intent.getIntExtra( 15826 Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, 15827 NO_EXTRA_VALUE_FOUND /* defaultValue */); 15828 // Only send a message if the time preference is available. 15829 if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) { 15830 Message updateTimePreferenceMsg = 15831 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG, 15832 timeFormatPreferenceMsgValue, 0); 15833 mHandler.sendMessage(updateTimePreferenceMsg); 15834 } 15835 mBatteryStatsService.noteCurrentTimeChanged(); 15836 break; 15837 case ConnectivityManager.ACTION_CLEAR_DNS_CACHE: 15838 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 15839 break; 15840 case Proxy.PROXY_CHANGE_ACTION: 15841 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG)); 15842 break; 15843 case android.hardware.Camera.ACTION_NEW_PICTURE: 15844 case android.hardware.Camera.ACTION_NEW_VIDEO: 15845 // In N we just turned these off; in O we are turing them back on partly, 15846 // only for registered receivers. This will still address the main problem 15847 // (a spam of apps waking up when a picture is taken putting significant 15848 // memory pressure on the system at a bad point), while still allowing apps 15849 // that are already actively running to know about this happening. 15850 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 15851 break; 15852 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED: 15853 mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG); 15854 break; 15855 case "com.android.launcher.action.INSTALL_SHORTCUT": 15856 // As of O, we no longer support this broadcasts, even for pre-O apps. 15857 // Apps should now be using ShortcutManager.pinRequestShortcut(). 15858 Log.w(TAG, "Broadcast " + action 15859 + " no longer supported. It will not be delivered."); 15860 scheduleCanceledResultTo(resultToApp, resultTo, intent, 15861 userId, brOptions, callingUid, callerPackage); 15862 return ActivityManager.BROADCAST_SUCCESS; 15863 case Intent.ACTION_PRE_BOOT_COMPLETED: 15864 timeoutExempt = true; 15865 break; 15866 case Intent.ACTION_CLOSE_SYSTEM_DIALOGS: 15867 if (!mAtmInternal.checkCanCloseSystemDialogs(callingPid, callingUid, 15868 callerPackage)) { 15869 scheduleCanceledResultTo(resultToApp, resultTo, intent, 15870 userId, brOptions, callingUid, callerPackage); 15871 // Returning success seems to be the pattern here 15872 return ActivityManager.BROADCAST_SUCCESS; 15873 } 15874 break; 15875 } 15876 15877 if (Intent.ACTION_PACKAGE_ADDED.equals(action) || 15878 Intent.ACTION_PACKAGE_REMOVED.equals(action) || 15879 Intent.ACTION_PACKAGE_REPLACED.equals(action)) { 15880 final int uid = getUidFromIntent(intent); 15881 if (uid != -1) { 15882 final UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 15883 if (uidRec != null) { 15884 uidRec.updateHasInternetPermission(); 15885 } 15886 } 15887 } 15888 } 15889 15890 final int callerAppProcessState = getRealProcessStateLocked(callerApp, realCallingPid); 15891 // Add to the sticky list if requested. 15892 if (sticky) { 15893 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY, 15894 callingPid, callingUid) 15895 != PackageManager.PERMISSION_GRANTED) { 15896 String msg = 15897 "Permission Denial: broadcastIntent() requesting a sticky broadcast from" 15898 + " pid=" 15899 + callingPid 15900 + ", uid=" 15901 + callingUid 15902 + " requires " 15903 + android.Manifest.permission.BROADCAST_STICKY; 15904 Slog.w(TAG, msg); 15905 throw new SecurityException(msg); 15906 } 15907 if (requiredPermissions != null && requiredPermissions.length > 0) { 15908 Slog.w(TAG, "Can't broadcast sticky intent " + intent 15909 + " and enforce permissions " + Arrays.toString(requiredPermissions)); 15910 scheduleCanceledResultTo(resultToApp, resultTo, intent, 15911 userId, brOptions, callingUid, callerPackage); 15912 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 15913 } 15914 if (intent.getComponent() != null) { 15915 throw new SecurityException( 15916 "Sticky broadcasts can't target a specific component"); 15917 } 15918 synchronized (mStickyBroadcasts) { 15919 // We use userId directly here, since the "all" target is maintained 15920 // as a separate set of sticky broadcasts. 15921 if (userId != UserHandle.USER_ALL) { 15922 // But first, if this is not a broadcast to all users, then 15923 // make sure it doesn't conflict with an existing broadcast to 15924 // all users. 15925 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get( 15926 UserHandle.USER_ALL); 15927 if (stickies != null) { 15928 ArrayList<StickyBroadcast> list = stickies.get(intent.getAction()); 15929 if (list != null) { 15930 int N = list.size(); 15931 int i; 15932 for (i = 0; i < N; i++) { 15933 if (intent.filterEquals(list.get(i).intent)) { 15934 throw new IllegalArgumentException("Sticky broadcast " + intent 15935 + " for user " + userId 15936 + " conflicts with existing global broadcast"); 15937 } 15938 } 15939 } 15940 } 15941 } 15942 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = 15943 mStickyBroadcasts.get(userId); 15944 if (stickies == null) { 15945 stickies = new ArrayMap<>(); 15946 mStickyBroadcasts.put(userId, stickies); 15947 } 15948 ArrayList<StickyBroadcast> list = stickies.get(intent.getAction()); 15949 if (list == null) { 15950 list = new ArrayList<>(); 15951 stickies.put(intent.getAction(), list); 15952 } 15953 final boolean deferUntilActive = BroadcastRecord.calculateDeferUntilActive( 15954 callingUid, brOptions, resultTo, ordered, 15955 BroadcastRecord.calculateUrgent(intent, brOptions)); 15956 final int stickiesCount = list.size(); 15957 int i; 15958 for (i = 0; i < stickiesCount; i++) { 15959 if (intent.filterEquals(list.get(i).intent)) { 15960 // This sticky already exists, replace it. 15961 list.set(i, StickyBroadcast.create(new Intent(intent), deferUntilActive, 15962 callingUid, callerAppProcessState, resolvedType)); 15963 break; 15964 } 15965 } 15966 if (i >= stickiesCount) { 15967 list.add(StickyBroadcast.create(new Intent(intent), deferUntilActive, 15968 callingUid, callerAppProcessState, resolvedType)); 15969 } 15970 } 15971 } 15972 15973 int[] users; 15974 if (userId == UserHandle.USER_ALL) { 15975 // Caller wants broadcast to go to all started users. 15976 users = mUserController.getStartedUserArray(); 15977 } else { 15978 // Caller wants broadcast to go to one specific user. 15979 users = new int[] {userId}; 15980 } 15981 15982 var args = new SaferIntentUtils.IntentArgs(intent, resolvedType, 15983 true /* isReceiver */, true /* resolveForStart */, callingUid, callingPid); 15984 args.platformCompat = mPlatformCompat; 15985 15986 // Figure out who all will receive this broadcast. 15987 final int cookie = BroadcastQueue.traceBegin("queryReceivers"); 15988 List receivers = null; 15989 List<BroadcastFilter> registeredReceivers = null; 15990 // Need to resolve the intent to interested receivers... 15991 if ((intent.getFlags() & Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 15992 receivers = collectReceiverComponents( 15993 intent, resolvedType, callingUid, callingPid, users, broadcastAllowList); 15994 } 15995 if (intent.getComponent() == null) { 15996 final PackageDataSnapshot snapshot = getPackageManagerInternal().snapshot(); 15997 if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) { 15998 // Query one target user at a time, excluding shell-restricted users 15999 for (int i = 0; i < users.length; i++) { 16000 if (mUserController.hasUserRestriction( 16001 UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) { 16002 continue; 16003 } 16004 List<BroadcastFilter> registeredReceiversForUser = 16005 mReceiverResolver.queryIntent(snapshot, intent, 16006 resolvedType, false /*defaultOnly*/, users[i]); 16007 if (registeredReceivers == null) { 16008 registeredReceivers = registeredReceiversForUser; 16009 } else if (registeredReceiversForUser != null) { 16010 registeredReceivers.addAll(registeredReceiversForUser); 16011 } 16012 } 16013 } else { 16014 registeredReceivers = mReceiverResolver.queryIntent(snapshot, intent, 16015 resolvedType, false /*defaultOnly*/, userId); 16016 } 16017 if (registeredReceivers != null) { 16018 SaferIntentUtils.blockNullAction(args, registeredReceivers); 16019 } 16020 } 16021 BroadcastQueue.traceEnd(cookie); 16022 16023 final boolean replacePending = 16024 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 16025 16026 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction() 16027 + " replacePending=" + replacePending); 16028 if (registeredReceivers != null && broadcastAllowList != null) { 16029 // if a uid whitelist was provided, remove anything in the application space that wasn't 16030 // in it. 16031 for (int i = registeredReceivers.size() - 1; i >= 0; i--) { 16032 final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid); 16033 if (owningAppId >= Process.FIRST_APPLICATION_UID 16034 && Arrays.binarySearch(broadcastAllowList, owningAppId) < 0) { 16035 registeredReceivers.remove(i); 16036 } 16037 } 16038 } 16039 16040 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 16041 16042 // Merge into one list. 16043 int ir = 0; 16044 if (receivers != null) { 16045 // A special case for PACKAGE_ADDED: do not allow the package 16046 // being added to see this broadcast. This prevents them from 16047 // using this as a back door to get run as soon as they are 16048 // installed. Maybe in the future we want to have a special install 16049 // broadcast or such for apps, but we'd like to deliberately make 16050 // this decision. 16051 String skipPackages[] = null; 16052 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 16053 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 16054 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 16055 Uri data = intent.getData(); 16056 if (data != null) { 16057 String pkgName = data.getSchemeSpecificPart(); 16058 if (pkgName != null) { 16059 skipPackages = new String[] { pkgName }; 16060 } 16061 } 16062 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 16063 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 16064 } 16065 if (skipPackages != null && (skipPackages.length > 0)) { 16066 for (String skipPackage : skipPackages) { 16067 if (skipPackage != null) { 16068 int NT = receivers.size(); 16069 for (int it=0; it<NT; it++) { 16070 ResolveInfo curt = (ResolveInfo)receivers.get(it); 16071 if (curt.activityInfo.packageName.equals(skipPackage)) { 16072 receivers.remove(it); 16073 it--; 16074 NT--; 16075 } 16076 } 16077 } 16078 } 16079 } 16080 16081 int NT = receivers != null ? receivers.size() : 0; 16082 int it = 0; 16083 ResolveInfo curt = null; 16084 BroadcastFilter curr = null; 16085 while (it < NT && ir < NR) { 16086 if (curt == null) { 16087 curt = (ResolveInfo)receivers.get(it); 16088 } 16089 if (curr == null) { 16090 curr = registeredReceivers.get(ir); 16091 } 16092 if (curr.getPriority() >= curt.priority) { 16093 // Insert this broadcast record into the final list. 16094 receivers.add(it, curr); 16095 ir++; 16096 curr = null; 16097 it++; 16098 NT++; 16099 } else { 16100 // Skip to the next ResolveInfo in the final list. 16101 it++; 16102 curt = null; 16103 } 16104 } 16105 } 16106 while (ir < NR) { 16107 if (receivers == null) { 16108 receivers = new ArrayList(); 16109 } 16110 receivers.add(registeredReceivers.get(ir)); 16111 ir++; 16112 } 16113 16114 if (isCallerSystem) { 16115 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid, 16116 isProtectedBroadcast, receivers); 16117 } 16118 16119 if ((receivers != null && receivers.size() > 0) 16120 || resultTo != null) { 16121 BroadcastQueue queue = mBroadcastQueue; 16122 SaferIntentUtils.filterNonExportedComponents(args, receivers); 16123 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, 16124 callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType, 16125 requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions, 16126 receivers, resultToApp, resultTo, resultCode, resultData, resultExtras, 16127 ordered, sticky, false, userId, 16128 backgroundStartPrivileges, timeoutExempt, filterExtrasForReceiver, 16129 callerAppProcessState); 16130 16131 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r); 16132 queue.enqueueBroadcastLocked(r); 16133 } else { 16134 // There was nobody interested in the broadcast, but we still want to record 16135 // that it happened. 16136 if (intent.getComponent() == null && intent.getPackage() == null 16137 && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 16138 // This was an implicit broadcast... let's record it for posterity. 16139 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0); 16140 } 16141 } 16142 16143 return ActivityManager.BROADCAST_SUCCESS; 16144 } 16145 16146 @GuardedBy("this") scheduleCanceledResultTo(ProcessRecord resultToApp, IIntentReceiver resultTo, Intent intent, int userId, BroadcastOptions options, int callingUid, String callingPackage)16147 private void scheduleCanceledResultTo(ProcessRecord resultToApp, IIntentReceiver resultTo, 16148 Intent intent, int userId, BroadcastOptions options, int callingUid, 16149 String callingPackage) { 16150 if (resultTo == null) { 16151 return; 16152 } 16153 final ProcessRecord app = resultToApp; 16154 final IApplicationThread thread = (app != null) ? app.getOnewayThread() : null; 16155 if (thread != null) { 16156 try { 16157 final boolean shareIdentity = (options != null && options.isShareIdentityEnabled()); 16158 thread.scheduleRegisteredReceiver( 16159 resultTo, intent, Activity.RESULT_CANCELED, null, null, 16160 false, false, true, userId, app.mState.getReportedProcState(), 16161 shareIdentity ? callingUid : Process.INVALID_UID, 16162 shareIdentity ? callingPackage : null); 16163 } catch (RemoteException e) { 16164 final String msg = "Failed to schedule result of " + intent + " via " 16165 + app + ": " + e; 16166 app.killLocked("Can't schedule resultTo", ApplicationExitInfo.REASON_OTHER, 16167 ApplicationExitInfo.SUBREASON_UNDELIVERED_BROADCAST, true); 16168 Slog.d(TAG, msg); 16169 } 16170 } 16171 } 16172 16173 @GuardedBy("this") getRealProcessStateLocked(ProcessRecord app, int pid)16174 private int getRealProcessStateLocked(ProcessRecord app, int pid) { 16175 if (app == null) { 16176 synchronized (mPidsSelfLocked) { 16177 app = mPidsSelfLocked.get(pid); 16178 } 16179 } 16180 if (app != null && app.getThread() != null && !app.isKilled()) { 16181 return app.mState.getCurProcState(); 16182 } 16183 return PROCESS_STATE_NONEXISTENT; 16184 } 16185 16186 @VisibleForTesting getStickyBroadcastsForTest(String action, int userId)16187 ArrayList<StickyBroadcast> getStickyBroadcastsForTest(String action, int userId) { 16188 synchronized (mStickyBroadcasts) { 16189 final ArrayMap<String, ArrayList<StickyBroadcast>> stickyBroadcasts = 16190 mStickyBroadcasts.get(userId); 16191 if (stickyBroadcasts == null) { 16192 return null; 16193 } 16194 return stickyBroadcasts.get(action); 16195 } 16196 } 16197 16198 /** 16199 * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1 16200 */ getUidFromIntent(Intent intent)16201 private int getUidFromIntent(Intent intent) { 16202 if (intent == null) { 16203 return -1; 16204 } 16205 final Bundle intentExtras = intent.getExtras(); 16206 return intent.hasExtra(Intent.EXTRA_UID) 16207 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 16208 } 16209 rotateBroadcastStatsIfNeededLocked()16210 final void rotateBroadcastStatsIfNeededLocked() { 16211 final long now = SystemClock.elapsedRealtime(); 16212 if (mCurBroadcastStats == null || 16213 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) { 16214 mLastBroadcastStats = mCurBroadcastStats; 16215 if (mLastBroadcastStats != null) { 16216 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime(); 16217 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis(); 16218 } 16219 mCurBroadcastStats = new BroadcastStats(); 16220 } 16221 } 16222 addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)16223 final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount, 16224 int skipCount, long dispatchTime) { 16225 rotateBroadcastStatsIfNeededLocked(); 16226 mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime); 16227 } 16228 addBackgroundCheckViolationLocked(String action, String targetPackage)16229 final void addBackgroundCheckViolationLocked(String action, String targetPackage) { 16230 rotateBroadcastStatsIfNeededLocked(); 16231 mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage); 16232 } 16233 notifyBroadcastFinishedLocked(@onNull BroadcastRecord original)16234 final void notifyBroadcastFinishedLocked(@NonNull BroadcastRecord original) { 16235 final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null; 16236 final String callerPackage = info != null ? info.packageName : original.callerPackage; 16237 if (callerPackage != null) { 16238 mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT, 16239 original.callingUid, 0, callerPackage).sendToTarget(); 16240 } 16241 } 16242 verifyBroadcastLocked(Intent intent)16243 final Intent verifyBroadcastLocked(Intent intent) { 16244 if (intent != null) { 16245 // Refuse possible leaked file descriptors 16246 if (intent.hasFileDescriptors()) { 16247 throw new IllegalArgumentException("File descriptors passed in Intent"); 16248 } 16249 // Remove existing mismatch flag so it can be properly updated later 16250 intent.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH); 16251 } 16252 16253 int flags = intent.getFlags(); 16254 16255 if (!mProcessesReady) { 16256 // if the caller really truly claims to know what they're doing, go 16257 // ahead and allow the broadcast without launching any receivers 16258 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 16259 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed. 16260 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 16261 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 16262 + " before boot completion"); 16263 throw new IllegalStateException("Cannot broadcast before boot completed"); 16264 } 16265 } 16266 16267 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 16268 throw new IllegalArgumentException( 16269 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 16270 } 16271 16272 if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 16273 switch (Binder.getCallingUid()) { 16274 case ROOT_UID: 16275 case SHELL_UID: 16276 break; 16277 default: 16278 Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID " 16279 + Binder.getCallingUid()); 16280 intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL); 16281 break; 16282 } 16283 } 16284 16285 return intent; 16286 } 16287 16288 /** 16289 * @deprecated Use {@link #broadcastIntentWithFeature} 16290 */ 16291 @Deprecated 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)16292 public final int broadcastIntent(IApplicationThread caller, 16293 Intent intent, String resolvedType, IIntentReceiver resultTo, 16294 int resultCode, String resultData, Bundle resultExtras, 16295 String[] requiredPermissions, int appOp, Bundle bOptions, 16296 boolean serialized, boolean sticky, int userId) { 16297 return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode, 16298 resultData, resultExtras, requiredPermissions, null, null, appOp, bOptions, 16299 serialized, sticky, userId); 16300 } 16301 16302 @Override broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, boolean serialized, boolean sticky, int userId)16303 public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, 16304 Intent intent, String resolvedType, IIntentReceiver resultTo, 16305 int resultCode, String resultData, Bundle resultExtras, 16306 String[] requiredPermissions, String[] excludedPermissions, 16307 String[] excludedPackages, int appOp, Bundle bOptions, 16308 boolean serialized, boolean sticky, int userId) { 16309 enforceNotIsolatedCaller("broadcastIntent"); 16310 synchronized(this) { 16311 intent = verifyBroadcastLocked(intent); 16312 16313 final ProcessRecord callerApp = getRecordForAppLOSP(caller); 16314 final int callingPid = Binder.getCallingPid(); 16315 final int callingUid = Binder.getCallingUid(); 16316 16317 // We're delivering the result to the caller 16318 final ProcessRecord resultToApp = callerApp; 16319 16320 // Permission regimes around sender-supplied broadcast options. 16321 enforceBroadcastOptionPermissionsInternal(bOptions, callingUid); 16322 16323 final long origId = Binder.clearCallingIdentity(); 16324 try { 16325 return broadcastIntentLocked(callerApp, 16326 callerApp != null ? callerApp.info.packageName : null, callingFeatureId, 16327 intent, resolvedType, resultToApp, resultTo, resultCode, resultData, 16328 resultExtras, requiredPermissions, excludedPermissions, excludedPackages, 16329 appOp, bOptions, serialized, sticky, callingPid, callingUid, callingUid, 16330 callingPid, userId, BackgroundStartPrivileges.NONE, null, null); 16331 } finally { 16332 Binder.restoreCallingIdentity(origId); 16333 } 16334 } 16335 } 16336 16337 // Not the binder call surface broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList)16338 int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, 16339 int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 16340 ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, 16341 String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, 16342 boolean serialized, boolean sticky, int userId, 16343 BackgroundStartPrivileges backgroundStartPrivileges, 16344 @Nullable int[] broadcastAllowList) { 16345 synchronized(this) { 16346 intent = verifyBroadcastLocked(intent); 16347 16348 final long origId = Binder.clearCallingIdentity(); 16349 String[] requiredPermissions = requiredPermission == null ? null 16350 : new String[] {requiredPermission}; 16351 try { 16352 return broadcastIntentLocked(null, packageName, featureId, intent, resolvedType, 16353 resultToApp, resultTo, resultCode, resultData, resultExtras, 16354 requiredPermissions, null, null, OP_NONE, bOptions, serialized, sticky, -1, 16355 uid, realCallingUid, realCallingPid, userId, 16356 backgroundStartPrivileges, broadcastAllowList, 16357 null /* filterExtrasForReceiver */); 16358 } finally { 16359 Binder.restoreCallingIdentity(origId); 16360 } 16361 } 16362 } 16363 16364 @Override unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)16365 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 16366 // Refuse possible leaked file descriptors 16367 if (intent != null && intent.hasFileDescriptors() == true) { 16368 throw new IllegalArgumentException("File descriptors passed in Intent"); 16369 } 16370 16371 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 16372 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null); 16373 16374 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 16375 != PackageManager.PERMISSION_GRANTED) { 16376 String msg = "Permission Denial: unbroadcastIntent() from pid=" 16377 + Binder.getCallingPid() 16378 + ", uid=" + Binder.getCallingUid() 16379 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 16380 Slog.w(TAG, msg); 16381 throw new SecurityException(msg); 16382 } 16383 synchronized (mStickyBroadcasts) { 16384 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get(userId); 16385 if (stickies != null) { 16386 ArrayList<StickyBroadcast> list = stickies.get(intent.getAction()); 16387 if (list != null) { 16388 int N = list.size(); 16389 int i; 16390 for (i = 0; i < N; i++) { 16391 if (intent.filterEquals(list.get(i).intent)) { 16392 list.remove(i); 16393 break; 16394 } 16395 } 16396 if (list.size() <= 0) { 16397 stickies.remove(intent.getAction()); 16398 } 16399 } 16400 if (stickies.size() <= 0) { 16401 mStickyBroadcasts.remove(userId); 16402 } 16403 } 16404 } 16405 } 16406 backgroundServicesFinishedLocked(int userId)16407 void backgroundServicesFinishedLocked(int userId) { 16408 mBroadcastQueue.backgroundServicesFinishedLocked(userId); 16409 } 16410 finishReceiver(IBinder caller, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)16411 public void finishReceiver(IBinder caller, int resultCode, String resultData, 16412 Bundle resultExtras, boolean resultAbort, int flags) { 16413 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + caller); 16414 16415 // Refuse possible leaked file descriptors 16416 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 16417 throw new IllegalArgumentException("File descriptors passed in Bundle"); 16418 } 16419 16420 final long origId = Binder.clearCallingIdentity(); 16421 try { 16422 synchronized(this) { 16423 final ProcessRecord callerApp = getRecordForAppLOSP(caller); 16424 if (callerApp == null) { 16425 Slog.w(TAG, "finishReceiver: no app for " + caller); 16426 return; 16427 } 16428 16429 mBroadcastQueue.finishReceiverLocked(callerApp, resultCode, 16430 resultData, resultExtras, resultAbort, true); 16431 // updateOomAdjLocked() will be done here 16432 trimApplicationsLocked(false, OOM_ADJ_REASON_FINISH_RECEIVER); 16433 } 16434 16435 } finally { 16436 Binder.restoreCallingIdentity(origId); 16437 } 16438 } 16439 16440 // ========================================================= 16441 // INSTRUMENTATION 16442 // ========================================================= 16443 startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)16444 public boolean startInstrumentation(ComponentName className, 16445 String profileFile, int flags, Bundle arguments, 16446 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 16447 int userId, String abiOverride) { 16448 enforceNotIsolatedCaller("startInstrumentation"); 16449 final int callingUid = Binder.getCallingUid(); 16450 final int callingPid = Binder.getCallingPid(); 16451 userId = mUserController.handleIncomingUser(callingPid, callingUid, 16452 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 16453 // Refuse possible leaked file descriptors 16454 if (arguments != null && arguments.hasFileDescriptors()) { 16455 throw new IllegalArgumentException("File descriptors passed in Bundle"); 16456 } 16457 final IPackageManager pm = AppGlobals.getPackageManager(); 16458 16459 synchronized(this) { 16460 InstrumentationInfo ii = null; 16461 ApplicationInfo ai = null; 16462 16463 boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0; 16464 16465 try { 16466 ii = pm.getInstrumentationInfoAsUser(className, STOCK_PM_FLAGS, userId); 16467 if (ii == null) { 16468 reportStartInstrumentationFailureLocked(watcher, className, 16469 "Unable to find instrumentation info for: " + className); 16470 return false; 16471 } 16472 ai = pm.getApplicationInfo(ii.targetPackage, STOCK_PM_FLAGS, userId); 16473 if (ai == null) { 16474 reportStartInstrumentationFailureLocked(watcher, className, 16475 "Unable to find instrumentation target package: " + ii.targetPackage); 16476 return false; 16477 } 16478 } catch (RemoteException e) { 16479 } 16480 16481 if (ii.targetPackage.equals("android")) { 16482 if (!noRestart) { 16483 reportStartInstrumentationFailureLocked(watcher, className, 16484 "Cannot instrument system server without 'no-restart'"); 16485 return false; 16486 } 16487 } else if (!ai.hasCode()) { 16488 reportStartInstrumentationFailureLocked(watcher, className, 16489 "Instrumentation target has no code: " + ii.targetPackage); 16490 return false; 16491 } 16492 16493 int match = SIGNATURE_NO_MATCH; 16494 try { 16495 match = pm.checkSignatures(ii.targetPackage, ii.packageName, userId); 16496 } catch (RemoteException e) { 16497 } 16498 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 16499 if (Build.IS_DEBUGGABLE && (callingUid == Process.ROOT_UID) 16500 && (flags & INSTR_FLAG_ALWAYS_CHECK_SIGNATURE) == 0) { 16501 Slog.w(TAG, "Instrumentation test " + ii.packageName 16502 + " doesn't have a signature matching the target " + ii.targetPackage 16503 + ", which would not be allowed on the production Android builds"); 16504 } else { 16505 String msg = "Permission Denial: starting instrumentation " 16506 + className + " from pid=" 16507 + Binder.getCallingPid() 16508 + ", uid=" + Binder.getCallingUid() 16509 + " not allowed because package " + ii.packageName 16510 + " does not have a signature matching the target " 16511 + ii.targetPackage; 16512 reportStartInstrumentationFailureLocked(watcher, className, msg); 16513 throw new SecurityException(msg); 16514 } 16515 } 16516 16517 if (!Build.IS_DEBUGGABLE && callingUid != ROOT_UID && callingUid != SHELL_UID 16518 && callingUid != SYSTEM_UID && !hasActiveInstrumentationLocked(callingPid)) { 16519 // If it's not debug build and not called from root/shell/system uid, reject it. 16520 final String msg = "Permission Denial: instrumentation test " 16521 + className + " from pid=" + callingPid + ", uid=" + callingUid 16522 + ", pkgName=" + mInternal.getPackageNameByPid(callingPid) 16523 + " not allowed because it's not started from SHELL"; 16524 Slog.wtfQuiet(TAG, msg); 16525 reportStartInstrumentationFailureLocked(watcher, className, msg); 16526 throw new SecurityException(msg); 16527 } 16528 16529 boolean disableHiddenApiChecks = ai.usesNonSdkApi() 16530 || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0; 16531 boolean disableTestApiChecks = disableHiddenApiChecks 16532 || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0; 16533 16534 if (disableHiddenApiChecks || disableTestApiChecks) { 16535 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS, 16536 "disable hidden API checks"); 16537 } 16538 16539 if ((flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_SANDBOX) != 0) { 16540 return startInstrumentationOfSdkSandbox( 16541 className, 16542 profileFile, 16543 arguments, 16544 watcher, 16545 uiAutomationConnection, 16546 userId, 16547 abiOverride, 16548 ii, 16549 ai, 16550 noRestart, 16551 disableHiddenApiChecks, 16552 disableTestApiChecks, 16553 (flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_IN_SANDBOX) != 0); 16554 } 16555 16556 ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); 16557 activeInstr.mClass = className; 16558 String defProcess = ai.processName;; 16559 if (ii.targetProcesses == null) { 16560 activeInstr.mTargetProcesses = new String[]{ai.processName}; 16561 } else if (ii.targetProcesses.equals("*")) { 16562 activeInstr.mTargetProcesses = new String[0]; 16563 } else { 16564 activeInstr.mTargetProcesses = ii.targetProcesses.split(","); 16565 defProcess = activeInstr.mTargetProcesses[0]; 16566 } 16567 activeInstr.mTargetInfo = ai; 16568 activeInstr.mProfileFile = profileFile; 16569 activeInstr.mArguments = arguments; 16570 activeInstr.mWatcher = watcher; 16571 activeInstr.mUiAutomationConnection = uiAutomationConnection; 16572 activeInstr.mResultClass = className; 16573 activeInstr.mHasBackgroundActivityStartsPermission = checkPermission( 16574 START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid) 16575 == PackageManager.PERMISSION_GRANTED; 16576 activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission( 16577 START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid) 16578 == PackageManager.PERMISSION_GRANTED; 16579 activeInstr.mNoRestart = noRestart; 16580 16581 final long origId = Binder.clearCallingIdentity(); 16582 16583 ProcessRecord app; 16584 synchronized (mProcLock) { 16585 if (noRestart) { 16586 app = getProcessRecordLocked(ai.processName, ai.uid); 16587 } else { 16588 // Instrumentation can kill and relaunch even persistent processes 16589 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, 16590 false, userId, "start instr"); 16591 // Inform usage stats to make the target package active 16592 if (mUsageStatsService != null) { 16593 mUsageStatsService.reportEvent(ii.targetPackage, userId, 16594 UsageEvents.Event.SYSTEM_INTERACTION); 16595 } 16596 app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks, 16597 disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY); 16598 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 16599 } 16600 16601 app.setActiveInstrumentation(activeInstr); 16602 activeInstr.mFinished = false; 16603 activeInstr.mSourceUid = callingUid; 16604 activeInstr.mRunningProcesses.add(app); 16605 if (!mActiveInstrumentation.contains(activeInstr)) { 16606 mActiveInstrumentation.add(activeInstr); 16607 } 16608 } 16609 16610 if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) { 16611 // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with 16612 // --no-isolated-storage flag. 16613 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid, 16614 ii.packageName, AppOpsManager.MODE_ALLOWED); 16615 } 16616 Binder.restoreCallingIdentity(origId); 16617 16618 if (noRestart) { 16619 instrumentWithoutRestart(activeInstr, ai); 16620 } 16621 } 16622 16623 return true; 16624 } 16625 16626 @GuardedBy("this") hasActiveInstrumentationLocked(int pid)16627 private boolean hasActiveInstrumentationLocked(int pid) { 16628 if (pid == 0) { 16629 return false; 16630 } 16631 synchronized (mPidsSelfLocked) { 16632 ProcessRecord process = mPidsSelfLocked.get(pid); 16633 return process != null && process.getActiveInstrumentation() != null; 16634 } 16635 } 16636 16637 @GuardedBy("this") startInstrumentationOfSdkSandbox( ComponentName className, String profileFile, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride, InstrumentationInfo instrumentationInfo, ApplicationInfo sdkSandboxClientAppInfo, boolean noRestart, boolean disableHiddenApiChecks, boolean disableTestApiChecks, boolean isSdkInSandbox)16638 private boolean startInstrumentationOfSdkSandbox( 16639 ComponentName className, 16640 String profileFile, 16641 Bundle arguments, 16642 IInstrumentationWatcher watcher, 16643 IUiAutomationConnection uiAutomationConnection, 16644 int userId, 16645 String abiOverride, 16646 InstrumentationInfo instrumentationInfo, 16647 ApplicationInfo sdkSandboxClientAppInfo, 16648 boolean noRestart, 16649 boolean disableHiddenApiChecks, 16650 boolean disableTestApiChecks, 16651 boolean isSdkInSandbox) { 16652 16653 if (noRestart) { 16654 reportStartInstrumentationFailureLocked( 16655 watcher, 16656 className, 16657 "Instrumenting sdk sandbox with --no-restart flag is not supported"); 16658 return false; 16659 } 16660 16661 final SdkSandboxManagerLocal sandboxManagerLocal = 16662 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 16663 if (sandboxManagerLocal == null) { 16664 reportStartInstrumentationFailureLocked( 16665 watcher, className, "Can't locate SdkSandboxManagerLocal"); 16666 return false; 16667 } 16668 16669 final ApplicationInfo sdkSandboxInfo; 16670 final String processName; 16671 try { 16672 if (sdkSandboxInstrumentationInfo()) { 16673 sdkSandboxInfo = 16674 sandboxManagerLocal.getSdkSandboxApplicationInfoForInstrumentation( 16675 sdkSandboxClientAppInfo, isSdkInSandbox); 16676 processName = sdkSandboxInfo.processName; 16677 } else { 16678 final PackageManager pm = mContext.getPackageManager(); 16679 sdkSandboxInfo = 16680 pm.getApplicationInfoAsUser(pm.getSdkSandboxPackageName(), 0, userId); 16681 processName = 16682 sandboxManagerLocal.getSdkSandboxProcessNameForInstrumentation( 16683 sdkSandboxClientAppInfo); 16684 sdkSandboxInfo.uid = Process.toSdkSandboxUid(sdkSandboxClientAppInfo.uid); 16685 } 16686 } catch (NameNotFoundException e) { 16687 reportStartInstrumentationFailureLocked( 16688 watcher, className, "Can't find SdkSandbox package"); 16689 return false; 16690 } 16691 16692 ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); 16693 activeInstr.mClass = className; 16694 activeInstr.mTargetProcesses = new String[]{processName}; 16695 activeInstr.mTargetInfo = sdkSandboxInfo; 16696 activeInstr.mIsSdkInSandbox = isSdkInSandbox; 16697 activeInstr.mProfileFile = profileFile; 16698 activeInstr.mArguments = arguments; 16699 activeInstr.mWatcher = watcher; 16700 activeInstr.mUiAutomationConnection = uiAutomationConnection; 16701 activeInstr.mResultClass = className; 16702 activeInstr.mHasBackgroundActivityStartsPermission = 16703 isSdkInSandbox 16704 // TODO(b/261864298): consider using START_ACTIVITIES_FROM_BACKGROUND. 16705 && checkPermission( 16706 android.Manifest.permission 16707 .START_ACTIVITIES_FROM_SDK_SANDBOX, 16708 Binder.getCallingPid(), 16709 Binder.getCallingUid()) 16710 == PackageManager.PERMISSION_GRANTED; 16711 activeInstr.mHasBackgroundForegroundServiceStartsPermission = false; 16712 // Instrumenting sdk sandbox without a restart is not supported 16713 activeInstr.mNoRestart = false; 16714 16715 final int callingUid = Binder.getCallingUid(); 16716 final long token = Binder.clearCallingIdentity(); 16717 try { 16718 sandboxManagerLocal.notifyInstrumentationStarted( 16719 sdkSandboxClientAppInfo.packageName, sdkSandboxClientAppInfo.uid); 16720 synchronized (mProcLock) { 16721 // Kill the package sdk sandbox process belong to. At this point sdk sandbox is 16722 // already killed. 16723 forceStopPackageLocked( 16724 instrumentationInfo.targetPackage, 16725 /* appId= */ -1, 16726 /* callerWillRestart= */ true, 16727 /* purgeCache= */ false, 16728 /* doIt= */ true, 16729 /* evenPersistent= */ true, 16730 /* uninstalling= */ false, 16731 /* packageStateStopped= */ false, 16732 userId, 16733 "start instr"); 16734 16735 ProcessRecord app = addAppLocked( 16736 sdkSandboxInfo, 16737 processName, 16738 /* isolated= */ false, 16739 /* isSdkSandbox= */ true, 16740 sdkSandboxInfo.uid, 16741 sdkSandboxClientAppInfo.packageName, 16742 disableHiddenApiChecks, 16743 disableTestApiChecks, 16744 abiOverride, 16745 ZYGOTE_POLICY_FLAG_EMPTY); 16746 16747 app.setActiveInstrumentation(activeInstr); 16748 activeInstr.mFinished = false; 16749 activeInstr.mSourceUid = callingUid; 16750 activeInstr.mRunningProcesses.add(app); 16751 if (!mActiveInstrumentation.contains(activeInstr)) { 16752 mActiveInstrumentation.add(activeInstr); 16753 } 16754 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 16755 } 16756 } finally { 16757 Binder.restoreCallingIdentity(token); 16758 } 16759 16760 return true; 16761 } 16762 instrumentWithoutRestart(ActiveInstrumentation activeInstr, ApplicationInfo targetInfo)16763 private void instrumentWithoutRestart(ActiveInstrumentation activeInstr, 16764 ApplicationInfo targetInfo) { 16765 ProcessRecord pr; 16766 synchronized (this) { 16767 pr = getProcessRecordLocked(targetInfo.processName, targetInfo.uid); 16768 } 16769 16770 try { 16771 pr.getThread().instrumentWithoutRestart( 16772 activeInstr.mClass, 16773 activeInstr.mArguments, 16774 activeInstr.mWatcher, 16775 activeInstr.mUiAutomationConnection, 16776 targetInfo); 16777 } catch (RemoteException e) { 16778 Slog.i(TAG, "RemoteException from instrumentWithoutRestart", e); 16779 } 16780 } 16781 isCallerShell()16782 private boolean isCallerShell() { 16783 final int callingUid = Binder.getCallingUid(); 16784 return callingUid == SHELL_UID || callingUid == ROOT_UID; 16785 } 16786 16787 /** 16788 * Report errors that occur while attempting to start Instrumentation. Always writes the 16789 * error to the logs, but if somebody is watching, send the report there too. This enables 16790 * the "am" command to report errors with more information. 16791 * 16792 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 16793 * @param cn The component name of the instrumentation. 16794 * @param report The error report. 16795 */ reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)16796 private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, 16797 ComponentName cn, String report) { 16798 Slog.w(TAG, report); 16799 if (watcher != null) { 16800 Bundle results = new Bundle(); 16801 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 16802 results.putString("Error", report); 16803 mInstrumentationReporter.reportStatus(watcher, cn, -1, results); 16804 } 16805 } 16806 addInstrumentationResultsLocked(ProcessRecord app, Bundle results)16807 void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) { 16808 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 16809 if (instr == null) { 16810 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 16811 return; 16812 } 16813 16814 if (!instr.mFinished && results != null) { 16815 if (instr.mCurResults == null) { 16816 instr.mCurResults = new Bundle(results); 16817 } else { 16818 instr.mCurResults.putAll(results); 16819 } 16820 } 16821 } 16822 addInstrumentationResults(IApplicationThread target, Bundle results)16823 public void addInstrumentationResults(IApplicationThread target, Bundle results) { 16824 int userId = UserHandle.getCallingUserId(); 16825 // Refuse possible leaked file descriptors 16826 if (results != null && results.hasFileDescriptors()) { 16827 throw new IllegalArgumentException("File descriptors passed in Intent"); 16828 } 16829 16830 synchronized(this) { 16831 ProcessRecord app = getRecordForAppLOSP(target); 16832 if (app == null) { 16833 Slog.w(TAG, "addInstrumentationResults: no app for " + target); 16834 return; 16835 } 16836 final long origId = Binder.clearCallingIdentity(); 16837 try { 16838 addInstrumentationResultsLocked(app, results); 16839 } finally { 16840 Binder.restoreCallingIdentity(origId); 16841 } 16842 } 16843 } 16844 16845 @GuardedBy("this") finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)16846 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 16847 try { 16848 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "finishInstrumentationLocked()"); 16849 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 16850 if (instr == null) { 16851 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 16852 return; 16853 } 16854 16855 synchronized (mProcLock) { 16856 if (!instr.mFinished) { 16857 if (instr.mWatcher != null) { 16858 Bundle finalResults = instr.mCurResults; 16859 if (finalResults != null) { 16860 if (instr.mCurResults != null && results != null) { 16861 finalResults.putAll(results); 16862 } 16863 } else { 16864 finalResults = results; 16865 } 16866 mInstrumentationReporter.reportFinished(instr.mWatcher, 16867 instr.mClass, resultCode, finalResults); 16868 } 16869 16870 // Can't call out of the system process with a lock held, so post a message. 16871 if (instr.mUiAutomationConnection != null) { 16872 // Go back to the default mode of denying OP_NO_ISOLATED_STORAGE app op. 16873 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, app.uid, 16874 app.info.packageName, AppOpsManager.MODE_ERRORED); 16875 getAccessCheckDelegateHelper() 16876 .onInstrumentationFinished(app.uid, app.info.packageName); 16877 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG, 16878 instr.mUiAutomationConnection).sendToTarget(); 16879 } 16880 instr.mFinished = true; 16881 } 16882 16883 instr.removeProcess(app); 16884 app.setActiveInstrumentation(null); 16885 } 16886 app.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 16887 16888 if (app.isSdkSandbox) { 16889 // For sharedUid apps this will kill all sdk sandbox processes, which is not ideal. 16890 // TODO(b/209061624): should we call ProcessList.removeProcessLocked instead? 16891 killUid(UserHandle.getAppId(app.uid), UserHandle.getUserId(app.uid), 16892 "finished instr"); 16893 final SdkSandboxManagerLocal sandboxManagerLocal = 16894 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 16895 if (sandboxManagerLocal != null) { 16896 sandboxManagerLocal.notifyInstrumentationFinished( 16897 app.sdkSandboxClientAppPackage, 16898 Process.getAppUidForSdkSandboxUid(app.uid)); 16899 } 16900 } else if (!instr.mNoRestart) { 16901 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, 16902 false, app.userId, "finished inst"); 16903 } 16904 } finally { 16905 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 16906 } 16907 } 16908 finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)16909 public void finishInstrumentation(IApplicationThread target, 16910 int resultCode, Bundle results) { 16911 int userId = UserHandle.getCallingUserId(); 16912 // Refuse possible leaked file descriptors 16913 if (results != null && results.hasFileDescriptors()) { 16914 throw new IllegalArgumentException("File descriptors passed in Intent"); 16915 } 16916 16917 synchronized(this) { 16918 ProcessRecord app = getRecordForAppLOSP(target); 16919 if (app == null) { 16920 Slog.w(TAG, "finishInstrumentation: no app for " + target); 16921 return; 16922 } 16923 final long origId = Binder.clearCallingIdentity(); 16924 finishInstrumentationLocked(app, resultCode, results); 16925 Binder.restoreCallingIdentity(origId); 16926 } 16927 } 16928 16929 @Override getFocusedRootTaskInfo()16930 public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException { 16931 return mActivityTaskManager.getFocusedRootTaskInfo(); 16932 } 16933 16934 @Override getConfiguration()16935 public Configuration getConfiguration() { 16936 return mActivityTaskManager.getConfiguration(); 16937 } 16938 16939 @Override suppressResizeConfigChanges(boolean suppress)16940 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException { 16941 mActivityTaskManager.suppressResizeConfigChanges(suppress); 16942 } 16943 16944 @Override updatePersistentConfiguration(Configuration values)16945 public void updatePersistentConfiguration(Configuration values) { 16946 updatePersistentConfigurationWithAttribution(values, 16947 Settings.getPackageNameForUid(mContext, Binder.getCallingUid()), null); 16948 } 16949 16950 @Override updatePersistentConfigurationWithAttribution(Configuration values, String callingPackage, String callingAttributionTag)16951 public void updatePersistentConfigurationWithAttribution(Configuration values, 16952 String callingPackage, String callingAttributionTag) { 16953 enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()"); 16954 enforceWriteSettingsPermission("updatePersistentConfiguration()", callingPackage, 16955 callingAttributionTag); 16956 if (values == null) { 16957 throw new NullPointerException("Configuration must not be null"); 16958 } 16959 16960 int userId = UserHandle.getCallingUserId(); 16961 16962 if (UserManager.isVisibleBackgroundUsersEnabled() && userId != getCurrentUserId()) { 16963 // The check is added mainly for auto devices. On auto devices, it is possible that 16964 // multiple users are visible simultaneously using visible background users. 16965 // In such cases, it is desired that only the current user (not the visible background 16966 // user) can change the locale and other persistent settings of the device. 16967 Slog.w(TAG, "Only current user is allowed to update persistent configuration if " 16968 + "visible background users are enabled. Current User" + getCurrentUserId() 16969 + ". Calling User: " + userId); 16970 throw new SecurityException("Only current user is allowed to update persistent " 16971 + "configuration."); 16972 } 16973 16974 mActivityTaskManager.updatePersistentConfiguration(values, userId); 16975 } 16976 enforceWriteSettingsPermission(String func, String callingPackage, String callingAttributionTag)16977 private void enforceWriteSettingsPermission(String func, String callingPackage, 16978 String callingAttributionTag) { 16979 int uid = Binder.getCallingUid(); 16980 if (uid == ROOT_UID) { 16981 return; 16982 } 16983 16984 if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid, 16985 callingPackage, callingAttributionTag, false)) { 16986 return; 16987 } 16988 16989 String msg = "Permission Denial: " + func + " from pid=" 16990 + Binder.getCallingPid() 16991 + ", uid=" + uid 16992 + " requires " + android.Manifest.permission.WRITE_SETTINGS; 16993 Slog.w(TAG, msg); 16994 throw new SecurityException(msg); 16995 } 16996 16997 @Override updateConfiguration(Configuration values)16998 public boolean updateConfiguration(Configuration values) { 16999 return mActivityTaskManager.updateConfiguration(values); 17000 } 17001 17002 @Override updateMccMncConfiguration(String mcc, String mnc)17003 public boolean updateMccMncConfiguration(String mcc, String mnc) { 17004 int mccInt, mncInt; 17005 try { 17006 mccInt = Integer.parseInt(mcc); 17007 mncInt = Integer.parseInt(mnc); 17008 } catch (NumberFormatException | StringIndexOutOfBoundsException ex) { 17009 Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex); 17010 return false; 17011 } 17012 Configuration config = new Configuration(); 17013 config.mcc = mccInt; 17014 config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt; 17015 return mActivityTaskManager.updateConfiguration(config); 17016 } 17017 17018 @Override getLaunchedFromUid(IBinder activityToken)17019 public int getLaunchedFromUid(IBinder activityToken) { 17020 return ActivityClient.getInstance().getLaunchedFromUid(activityToken); 17021 } 17022 getLaunchedFromPackage(IBinder activityToken)17023 public String getLaunchedFromPackage(IBinder activityToken) { 17024 return ActivityClient.getInstance().getLaunchedFromPackage(activityToken); 17025 } 17026 17027 // ========================================================= 17028 // LIFETIME MANAGEMENT 17029 // ========================================================= 17030 isReceivingBroadcastLocked(ProcessRecord app, int[] outSchedGroup)17031 boolean isReceivingBroadcastLocked(ProcessRecord app, int[] outSchedGroup) { 17032 final int res = mBroadcastQueue.getPreferredSchedulingGroupLocked(app); 17033 outSchedGroup[0] = res; 17034 return res != ProcessList.SCHED_GROUP_UNDEFINED; 17035 } 17036 startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)17037 Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, 17038 int targetUid, long targetVersionCode, ComponentName targetComponent, 17039 String targetProcess) { 17040 if (!mTrackingAssociations) { 17041 return null; 17042 } 17043 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 17044 = mAssociations.get(targetUid); 17045 if (components == null) { 17046 components = new ArrayMap<>(); 17047 mAssociations.put(targetUid, components); 17048 } 17049 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 17050 if (sourceUids == null) { 17051 sourceUids = new SparseArray<>(); 17052 components.put(targetComponent, sourceUids); 17053 } 17054 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 17055 if (sourceProcesses == null) { 17056 sourceProcesses = new ArrayMap<>(); 17057 sourceUids.put(sourceUid, sourceProcesses); 17058 } 17059 Association ass = sourceProcesses.get(sourceProcess); 17060 if (ass == null) { 17061 ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent, 17062 targetProcess); 17063 sourceProcesses.put(sourceProcess, ass); 17064 } 17065 ass.mCount++; 17066 ass.mNesting++; 17067 if (ass.mNesting == 1) { 17068 ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis(); 17069 ass.mLastState = sourceState; 17070 } 17071 return ass; 17072 } 17073 stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)17074 void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, 17075 long targetVersionCode, ComponentName targetComponent, String targetProcess) { 17076 if (!mTrackingAssociations) { 17077 return; 17078 } 17079 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 17080 = mAssociations.get(targetUid); 17081 if (components == null) { 17082 return; 17083 } 17084 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 17085 if (sourceUids == null) { 17086 return; 17087 } 17088 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 17089 if (sourceProcesses == null) { 17090 return; 17091 } 17092 Association ass = sourceProcesses.get(sourceProcess); 17093 if (ass == null || ass.mNesting <= 0) { 17094 return; 17095 } 17096 ass.mNesting--; 17097 if (ass.mNesting == 0) { 17098 long uptime = SystemClock.uptimeMillis(); 17099 ass.mTime += uptime - ass.mStartTime; 17100 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 17101 += uptime - ass.mLastStateUptime; 17102 ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2; 17103 } 17104 } 17105 noteUidProcessState(final int uid, final int state, final @ProcessCapability int capability)17106 void noteUidProcessState(final int uid, final int state, 17107 final @ProcessCapability int capability) { 17108 mBatteryStatsService.noteUidProcessState(uid, state); 17109 mAppOpsService.updateUidProcState(uid, state, capability); 17110 if (StatsPullAtomService.ENABLE_MOBILE_DATA_STATS_AGGREGATED_PULLER) { 17111 try { 17112 if (mStatsPullAtomServiceInternal == null) { 17113 mStatsPullAtomServiceInternal = LocalServices.getService( 17114 StatsPullAtomServiceInternal.class); 17115 } 17116 if (mStatsPullAtomServiceInternal != null) { 17117 mStatsPullAtomServiceInternal.noteUidProcessState(uid, state); 17118 } else { 17119 Slog.d(TAG, "StatsPullAtomService not ready yet"); 17120 } 17121 } catch (Exception e) { 17122 Slog.e(TAG, "Exception during logging uid proc state change event", e); 17123 } 17124 } 17125 if (mTrackingAssociations) { 17126 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 17127 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 17128 = mAssociations.valueAt(i1); 17129 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 17130 SparseArray<ArrayMap<String, Association>> sourceUids 17131 = targetComponents.valueAt(i2); 17132 ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid); 17133 if (sourceProcesses != null) { 17134 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 17135 Association ass = sourceProcesses.valueAt(i4); 17136 if (ass.mNesting >= 1) { 17137 // currently associated 17138 long uptime = SystemClock.uptimeMillis(); 17139 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 17140 += uptime - ass.mLastStateUptime; 17141 ass.mLastState = state; 17142 ass.mLastStateUptime = uptime; 17143 } 17144 } 17145 } 17146 } 17147 } 17148 } 17149 } 17150 17151 /** 17152 * Returns true if things are idle enough to perform GCs. 17153 */ 17154 @GuardedBy("this") canGcNowLocked()17155 final boolean canGcNowLocked() { 17156 if (!mBroadcastQueue.isIdleLocked()) { 17157 return false; 17158 } 17159 return mAtmInternal.canGcNow(); 17160 } 17161 checkExcessivePowerUsage()17162 private void checkExcessivePowerUsage() { 17163 updateCpuStatsNow(); 17164 17165 final boolean monitorPhantomProcs = mSystemReady && FeatureFlagUtils.isEnabled(mContext, 17166 SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS); 17167 synchronized (mProcLock) { 17168 final boolean doCpuKills = mLastPowerCheckUptime != 0; 17169 final long curUptime = SystemClock.uptimeMillis(); 17170 final long uptimeSince = curUptime - mLastPowerCheckUptime; 17171 mLastPowerCheckUptime = curUptime; 17172 mProcessList.forEachLruProcessesLOSP(false, app -> { 17173 if (app.getThread() == null) { 17174 return; 17175 } 17176 if (app.mState.getSetProcState() >= ActivityManager.PROCESS_STATE_HOME) { 17177 int cpuLimit; 17178 long checkDur = curUptime - app.mState.getWhenUnimportant(); 17179 if (checkDur <= mConstants.POWER_CHECK_INTERVAL) { 17180 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1; 17181 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 2) 17182 || app.mState.getSetProcState() <= ActivityManager.PROCESS_STATE_HOME) { 17183 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2; 17184 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 3)) { 17185 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3; 17186 } else { 17187 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4; 17188 } 17189 17190 updateAppProcessCpuTimeLPr(uptimeSince, doCpuKills, checkDur, cpuLimit, app); 17191 17192 if (monitorPhantomProcs) { 17193 // Also check the phantom processes if there is any 17194 updatePhantomProcessCpuTimeLPr( 17195 uptimeSince, doCpuKills, checkDur, cpuLimit, app); 17196 } 17197 } 17198 }); 17199 } 17200 } 17201 17202 @GuardedBy("mProcLock") updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)17203 private void updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, 17204 final long checkDur, final int cpuLimit, final ProcessRecord app) { 17205 synchronized (mAppProfiler.mProfilerLock) { 17206 final ProcessProfileRecord profile = app.mProfile; 17207 final long curCpuTime = profile.mCurCpuTime.get(); 17208 final long lastCpuTime = profile.mLastCpuTime.get(); 17209 if (lastCpuTime > 0) { 17210 final long cpuTimeUsed = curCpuTime - lastCpuTime; 17211 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed, 17212 app.processName, app.toShortString(), cpuLimit, app)) { 17213 mHandler.post(() -> { 17214 synchronized (ActivityManagerService.this) { 17215 if (app.getThread() == null 17216 || app.mState.getSetProcState() < ActivityManager.PROCESS_STATE_HOME) { 17217 return; 17218 } 17219 app.killLocked("excessive cpu " + cpuTimeUsed + " during " 17220 + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit, 17221 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 17222 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU, 17223 true); 17224 } 17225 }); 17226 profile.reportExcessiveCpu(); 17227 } 17228 } 17229 17230 profile.mLastCpuTime.set(curCpuTime); 17231 } 17232 } 17233 17234 @GuardedBy("mProcLock") updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)17235 private void updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, 17236 final long checkDur, final int cpuLimit, final ProcessRecord app) { 17237 mPhantomProcessList.forEachPhantomProcessOfApp(app, r -> { 17238 if (r.mLastCputime > 0) { 17239 final long cpuTimeUsed = r.mCurrentCputime - r.mLastCputime; 17240 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed, 17241 app.processName, r.toString(), cpuLimit, app)) { 17242 mHandler.post(() -> { 17243 synchronized (ActivityManagerService.this) { 17244 if (app.getThread() == null 17245 || app.mState.getSetProcState() < ActivityManager.PROCESS_STATE_HOME) { 17246 return; 17247 } 17248 mPhantomProcessList.killPhantomProcessGroupLocked(app, r, 17249 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 17250 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU, 17251 "excessive cpu " + cpuTimeUsed + " during " 17252 + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit); 17253 } 17254 }); 17255 return false; 17256 } 17257 } 17258 r.mLastCputime = r.mCurrentCputime; 17259 return true; 17260 }); 17261 } 17262 17263 @GuardedBy("mProcLock") checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, final long cputimeUsed, final String processName, final String description, final int cpuLimit, final ProcessRecord app)17264 private boolean checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, 17265 final long cputimeUsed, final String processName, final String description, 17266 final int cpuLimit, final ProcessRecord app) { 17267 if (DEBUG_POWER && (uptimeSince > 0)) { 17268 StringBuilder sb = new StringBuilder(128); 17269 sb.append("CPU for "); 17270 sb.append(description); 17271 sb.append(": over "); 17272 TimeUtils.formatDuration(uptimeSince, sb); 17273 sb.append(" used "); 17274 TimeUtils.formatDuration(cputimeUsed, sb); 17275 sb.append(" ("); 17276 sb.append((cputimeUsed * 100.0) / uptimeSince); 17277 sb.append("%)"); 17278 Slog.i(TAG_POWER, sb.toString()); 17279 } 17280 // If the process has used too much CPU over the last duration, the 17281 // user probably doesn't want this, so kill! 17282 if (doCpuKills && uptimeSince > 0) { 17283 if (((cputimeUsed * 100) / uptimeSince) >= cpuLimit) { 17284 mBatteryStatsService.reportExcessiveCpu(app.info.uid, app.processName, 17285 uptimeSince, cputimeUsed); 17286 app.getPkgList().forEachPackageProcessStats(holder -> { 17287 final ProcessState state = holder.state; 17288 FrameworkStatsLog.write( 17289 FrameworkStatsLog.EXCESSIVE_CPU_USAGE_REPORTED, 17290 app.info.uid, 17291 processName, 17292 state != null ? state.getPackage() : app.info.packageName, 17293 holder.appVersion); 17294 }); 17295 return true; 17296 } 17297 } 17298 return false; 17299 } 17300 isEphemeralLocked(int uid)17301 private boolean isEphemeralLocked(int uid) { 17302 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid); 17303 if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid 17304 return false; 17305 } 17306 return getPackageManagerInternal().isPackageEphemeral( 17307 UserHandle.getUserId(uid), packages[0]); 17308 } 17309 17310 @GuardedBy("this") enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)17311 void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) { 17312 uid = uidRec != null ? uidRec.getUid() : uid; 17313 if (uid < 0) { 17314 throw new IllegalArgumentException("No UidRecord or uid"); 17315 } 17316 17317 final int procState = uidRec != null 17318 ? uidRec.getSetProcState() : PROCESS_STATE_NONEXISTENT; 17319 final int procAdj = uidRec != null 17320 ? uidRec.getMinProcAdj() : ProcessList.INVALID_ADJ; 17321 final long procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0; 17322 final int capability = uidRec != null ? uidRec.getSetCapability() : 0; 17323 final boolean ephemeral = uidRec != null ? uidRec.isEphemeral() : isEphemeralLocked(uid); 17324 17325 if (uidRec != null && uidRec.isIdle() && (change & UidRecord.CHANGE_IDLE) != 0) { 17326 mProcessList.killAppIfBgRestrictedAndCachedIdleLocked(uidRec); 17327 } 17328 17329 if (uidRec != null && !uidRec.isIdle() && (change & UidRecord.CHANGE_GONE) != 0) { 17330 // If this uid is going away, and we haven't yet reported it is gone, 17331 // then do so now. 17332 change |= UidRecord.CHANGE_IDLE; 17333 } 17334 final int enqueuedChange = mUidObserverController.enqueueUidChange( 17335 uidRec == null ? null : uidRec.pendingChange, 17336 uid, change, procState, procAdj, procStateSeq, capability, ephemeral); 17337 if (uidRec != null) { 17338 uidRec.setLastReportedChange(enqueuedChange); 17339 } 17340 17341 // Directly update the power manager, since we sit on top of it and it is critical 17342 // it be kept in sync (so wake locks will be held as soon as appropriate). 17343 if (mLocalPowerManager != null) { 17344 // TODO: dispatch cached/uncached changes here, so we don't need to report 17345 // all proc state changes. 17346 if ((enqueuedChange & UidRecord.CHANGE_ACTIVE) != 0) { 17347 mLocalPowerManager.uidActive(uid); 17348 } 17349 if ((enqueuedChange & UidRecord.CHANGE_IDLE) != 0) { 17350 mLocalPowerManager.uidIdle(uid); 17351 } 17352 if ((enqueuedChange & UidRecord.CHANGE_GONE) != 0) { 17353 mLocalPowerManager.uidGone(uid); 17354 } else if ((enqueuedChange & UidRecord.CHANGE_PROCSTATE) != 0) { 17355 mLocalPowerManager.updateUidProcState(uid, procState); 17356 } 17357 } 17358 } 17359 17360 @GuardedBy(anyOf = {"this", "mProcLock"}) setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor)17361 final void setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor) { 17362 if (proc.getThread() != null) { 17363 proc.mProfile.setProcessTrackerState( 17364 proc.mState.getReportedProcState(), memFactor); 17365 } 17366 } 17367 17368 @GuardedBy("this") clearProcessForegroundLocked(ProcessRecord proc)17369 final void clearProcessForegroundLocked(ProcessRecord proc) { 17370 updateProcessForegroundLocked(proc, /* isForeground =*/ false, 17371 /* fgsTypes =*/0, /* hasTypeNoneFgs =*/false, /* oomAdj= */ false); 17372 } 17373 17374 @GuardedBy("this") updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean hasTypeNoneFgs, boolean oomAdj)17375 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 17376 int fgServiceTypes, boolean hasTypeNoneFgs, boolean oomAdj) { 17377 final ProcessServiceRecord psr = proc.mServices; 17378 final boolean foregroundStateChanged = isForeground != psr.hasForegroundServices(); 17379 if (foregroundStateChanged 17380 || !psr.areForegroundServiceTypesSame(fgServiceTypes, hasTypeNoneFgs)) { 17381 if (foregroundStateChanged) { 17382 // Notify internal listeners. 17383 for (int i = mForegroundServiceStateListeners.size() - 1; i >= 0; i--) { 17384 mForegroundServiceStateListeners.get(i).onForegroundServiceStateChanged( 17385 proc.info.packageName, proc.info.uid, proc.getPid(), isForeground); 17386 } 17387 } 17388 psr.setHasForegroundServices(isForeground, fgServiceTypes, hasTypeNoneFgs); 17389 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 17390 proc.info.uid); 17391 if (isForeground) { 17392 if (curProcs == null) { 17393 curProcs = new ArrayList<ProcessRecord>(); 17394 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 17395 } 17396 if (!curProcs.contains(proc)) { 17397 curProcs.add(proc); 17398 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 17399 proc.info.packageName, proc.info.uid); 17400 } 17401 } else { 17402 if (curProcs != null) { 17403 if (curProcs.remove(proc)) { 17404 mBatteryStatsService.noteEvent( 17405 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 17406 proc.info.packageName, proc.info.uid); 17407 if (curProcs.size() <= 0) { 17408 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 17409 } 17410 } 17411 } 17412 } 17413 17414 psr.setReportedForegroundServiceTypes(fgServiceTypes); 17415 ProcessChangeItem item = mProcessList.enqueueProcessChangeItemLocked( 17416 proc.getPid(), proc.info.uid); 17417 item.changes |= ProcessChangeItem.CHANGE_FOREGROUND_SERVICES; 17418 item.foregroundServiceTypes = fgServiceTypes; 17419 } 17420 if (oomAdj) { 17421 updateOomAdjLocked(proc, OOM_ADJ_REASON_UI_VISIBILITY); 17422 } 17423 } 17424 17425 // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update 17426 // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities 17427 @Nullable getTopApp()17428 ProcessRecord getTopApp() { 17429 final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null; 17430 final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null; 17431 String pkg; 17432 int uid; 17433 if (r != null) { 17434 pkg = r.processName; 17435 uid = r.info.uid; 17436 } else { 17437 pkg = null; 17438 uid = -1; 17439 } 17440 // Has the UID or resumed package name changed? 17441 synchronized (mCurResumedAppLock) { 17442 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 17443 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 17444 17445 final long identity = Binder.clearCallingIdentity(); 17446 try { 17447 if (mCurResumedPackage != null) { 17448 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 17449 mCurResumedPackage, mCurResumedUid); 17450 } 17451 mCurResumedPackage = pkg; 17452 mCurResumedUid = uid; 17453 if (mCurResumedPackage != null) { 17454 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 17455 mCurResumedPackage, mCurResumedUid); 17456 } 17457 } finally { 17458 Binder.restoreCallingIdentity(identity); 17459 } 17460 } 17461 } 17462 return r; 17463 } 17464 17465 /** 17466 * Enqueue the given process into a todo list, and the caller should 17467 * call {@link #updateOomAdjPendingTargetsLocked} to kick off a pass of the oom adj update. 17468 */ 17469 @GuardedBy("this") enqueueOomAdjTargetLocked(ProcessRecord app)17470 void enqueueOomAdjTargetLocked(ProcessRecord app) { 17471 mOomAdjuster.enqueueOomAdjTargetLocked(app); 17472 } 17473 17474 /** 17475 * Remove the given process into a todo list. 17476 */ 17477 @GuardedBy("this") removeOomAdjTargetLocked(ProcessRecord app, boolean procDied)17478 void removeOomAdjTargetLocked(ProcessRecord app, boolean procDied) { 17479 mOomAdjuster.removeOomAdjTargetLocked(app, procDied); 17480 } 17481 17482 /** 17483 * Kick off an oom adj update pass for the pending targets which are enqueued via 17484 * {@link #enqueueOomAdjTargetLocked}. 17485 */ 17486 @GuardedBy("this") updateOomAdjPendingTargetsLocked(@omAdjReason int oomAdjReason)17487 void updateOomAdjPendingTargetsLocked(@OomAdjReason int oomAdjReason) { 17488 mOomAdjuster.updateOomAdjPendingTargetsLocked(oomAdjReason); 17489 } 17490 17491 static final class ProcStatsRunnable implements Runnable { 17492 private final ActivityManagerService mService; 17493 private final ProcessStatsService mProcessStats; 17494 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)17495 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) { 17496 this.mService = service; 17497 this.mProcessStats = mProcessStats; 17498 } 17499 run()17500 @Override public void run() { 17501 mProcessStats.writeStateAsync(); 17502 } 17503 } 17504 17505 @GuardedBy("this") updateOomAdjLocked(@omAdjReason int oomAdjReason)17506 final void updateOomAdjLocked(@OomAdjReason int oomAdjReason) { 17507 mOomAdjuster.updateOomAdjLocked(oomAdjReason); 17508 } 17509 17510 /** 17511 * Update OomAdj for a specific process and its reachable processes. 17512 * 17513 * @param app The process to update 17514 * @param oomAdjReason 17515 * @return whether updateOomAdjLocked(app) was successful. 17516 */ 17517 @GuardedBy("this") updateOomAdjLocked(ProcessRecord app, @OomAdjReason int oomAdjReason)17518 final boolean updateOomAdjLocked(ProcessRecord app, @OomAdjReason int oomAdjReason) { 17519 return mOomAdjuster.updateOomAdjLocked(app, oomAdjReason); 17520 } 17521 17522 @Override makePackageIdle(String packageName, int userId)17523 public void makePackageIdle(String packageName, int userId) { 17524 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 17525 != PackageManager.PERMISSION_GRANTED) { 17526 String msg = "Permission Denial: makePackageIdle() from pid=" 17527 + Binder.getCallingPid() 17528 + ", uid=" + Binder.getCallingUid() 17529 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 17530 Slog.w(TAG, msg); 17531 throw new SecurityException(msg); 17532 } 17533 final int callingPid = Binder.getCallingPid(); 17534 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 17535 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null); 17536 final long callingId = Binder.clearCallingIdentity(); 17537 try { 17538 IPackageManager pm = AppGlobals.getPackageManager(); 17539 int pkgUid = -1; 17540 try { 17541 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES 17542 | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM); 17543 } catch (RemoteException e) { 17544 } 17545 if (pkgUid == -1) { 17546 throw new IllegalArgumentException("Unknown package name " + packageName); 17547 } 17548 17549 synchronized (this) { 17550 try { 17551 if (mLocalPowerManager != null) { 17552 mLocalPowerManager.startUidChanges(); 17553 } 17554 final int appId = UserHandle.getAppId(pkgUid); 17555 for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; i--) { 17556 final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i); 17557 final long bgTime = uidRec.getLastBackgroundTime(); 17558 if (bgTime > 0 && !uidRec.isIdle()) { 17559 final int uid = uidRec.getUid(); 17560 if (UserHandle.getAppId(uid) == appId) { 17561 if (userId == UserHandle.USER_ALL 17562 || userId == UserHandle.getUserId(uid)) { 17563 EventLogTags.writeAmUidIdle(uid); 17564 synchronized (mProcLock) { 17565 uidRec.setIdle(true); 17566 uidRec.setSetIdle(true); 17567 } 17568 Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uid) 17569 + " from package " + packageName + " user " + userId); 17570 doStopUidLocked(uid, uidRec); 17571 } 17572 } 17573 } 17574 } 17575 } finally { 17576 if (mLocalPowerManager != null) { 17577 mLocalPowerManager.finishUidChanges(); 17578 } 17579 } 17580 } 17581 } finally { 17582 Binder.restoreCallingIdentity(callingId); 17583 } 17584 } 17585 17586 @Override setDeterministicUidIdle(boolean deterministic)17587 public void setDeterministicUidIdle(boolean deterministic) { 17588 synchronized (this) { 17589 mDeterministicUidIdle = deterministic; 17590 } 17591 } 17592 17593 /** Make the currently active UIDs idle after a certain grace period. */ idleUids()17594 final void idleUids() { 17595 synchronized (this) { 17596 mOomAdjuster.idleUidsLocked(); 17597 } 17598 } 17599 runInBackgroundDisabled(int uid)17600 final void runInBackgroundDisabled(int uid) { 17601 synchronized (this) { 17602 UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 17603 if (uidRec != null) { 17604 // This uid is actually running... should it be considered background now? 17605 if (uidRec.isIdle()) { 17606 doStopUidLocked(uidRec.getUid(), uidRec); 17607 } 17608 } else { 17609 // This uid isn't actually running... still send a report about it being "stopped". 17610 doStopUidLocked(uid, null); 17611 } 17612 } 17613 } 17614 cameraActiveChanged(@serIdInt int uid, boolean active)17615 final void cameraActiveChanged(@UserIdInt int uid, boolean active) { 17616 synchronized (mActiveCameraUids) { 17617 final int curIndex = mActiveCameraUids.indexOf(uid); 17618 if (active) { 17619 if (curIndex < 0) { 17620 mActiveCameraUids.add(uid); 17621 } 17622 } else { 17623 if (curIndex >= 0) { 17624 mActiveCameraUids.remove(curIndex); 17625 } 17626 } 17627 } 17628 17629 if (com.android.window.flags.Flags.fifoPriorityForMajorUiProcesses()) { 17630 synchronized (mProcLock) { 17631 adjustFifoProcessesIfNeeded(uid, !active /* allowFifo */); 17632 } 17633 } 17634 } 17635 isCameraActiveForUid(@serIdInt int uid)17636 final boolean isCameraActiveForUid(@UserIdInt int uid) { 17637 synchronized (mActiveCameraUids) { 17638 return mActiveCameraUids.indexOf(uid) >= 0; 17639 } 17640 } 17641 17642 /** 17643 * This is called when the given uid is using camera. If the uid has top process state, then 17644 * cancel the FIFO priority of the high priority processes. 17645 */ 17646 @VisibleForTesting 17647 @GuardedBy("mProcLock") adjustFifoProcessesIfNeeded(int preemptiveUid, boolean allowSpecifiedFifo)17648 void adjustFifoProcessesIfNeeded(int preemptiveUid, boolean allowSpecifiedFifo) { 17649 if (allowSpecifiedFifo == mAllowSpecifiedFifoScheduling) { 17650 return; 17651 } 17652 if (!allowSpecifiedFifo) { 17653 final UidRecord uidRec = mProcessList.mActiveUids.get(preemptiveUid); 17654 if (uidRec == null || uidRec.getCurProcState() > PROCESS_STATE_TOP) { 17655 // To avoid frequent switching by background camera usages, e.g. face unlock, 17656 // face detection (auto rotation), screen attention (keep screen on). 17657 return; 17658 } 17659 } 17660 mAllowSpecifiedFifoScheduling = allowSpecifiedFifo; 17661 for (int i = mSpecifiedFifoProcesses.size() - 1; i >= 0; i--) { 17662 final ProcessRecord proc = mSpecifiedFifoProcesses.get(i); 17663 if (proc.mState.getSetSchedGroup() != ProcessList.SCHED_GROUP_TOP_APP) { 17664 continue; 17665 } 17666 setFifoPriority(proc, allowSpecifiedFifo /* enable */); 17667 } 17668 } 17669 17670 @GuardedBy("this") doStopUidLocked(int uid, final UidRecord uidRec)17671 final void doStopUidLocked(int uid, final UidRecord uidRec) { 17672 mServices.stopInBackgroundLocked(uid); 17673 enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE | UidRecord.CHANGE_PROCSTATE); 17674 } 17675 17676 /** 17677 * Allowlists {@code targetUid} to temporarily bypass Power Save mode. 17678 */ 17679 @GuardedBy("this") tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)17680 void tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, 17681 long duration, int type, @ReasonCode int reasonCode, String reason) { 17682 if (DEBUG_ALLOWLISTS) { 17683 Slog.d(TAG, "tempAllowlistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", " 17684 + targetUid + ", " + duration + ", " + type + ")"); 17685 } 17686 17687 synchronized (mPidsSelfLocked) { 17688 final ProcessRecord pr = mPidsSelfLocked.get(callerPid); 17689 if (pr == null) { 17690 Slog.w(TAG, "tempAllowlistForPendingIntentLocked() no ProcessRecord for pid " 17691 + callerPid); 17692 return; 17693 } 17694 if (!pr.mServices.mAllowlistManager) { 17695 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid) 17696 != PackageManager.PERMISSION_GRANTED 17697 && checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callerPid, callerUid) 17698 != PackageManager.PERMISSION_GRANTED 17699 && checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callerPid, 17700 callerUid) != PackageManager.PERMISSION_GRANTED) { 17701 if (DEBUG_ALLOWLISTS) { 17702 Slog.d(TAG, "tempAllowlistForPendingIntentLocked() for target " + targetUid 17703 + ": pid " + callerPid + " is not allowed"); 17704 } 17705 return; 17706 } 17707 } 17708 } 17709 17710 tempAllowlistUidLocked(targetUid, duration, reasonCode, reason, type, callerUid); 17711 } 17712 17713 /** 17714 * Allowlists {@code targetUid} to temporarily bypass Power Save mode. 17715 */ 17716 @GuardedBy("this") tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, String reason, @TempAllowListType int type, int callingUid)17717 void tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, 17718 String reason, @TempAllowListType int type, int callingUid) { 17719 synchronized (mProcLock) { 17720 // The temp allowlist type could change according to the reasonCode. 17721 if (mLocalDeviceIdleController != null) { 17722 type = mLocalDeviceIdleController.getTempAllowListType(reasonCode, type); 17723 } 17724 if (type == TEMPORARY_ALLOW_LIST_TYPE_NONE) { 17725 return; 17726 } 17727 mPendingTempAllowlist.put(targetUid, 17728 new PendingTempAllowlist(targetUid, duration, reasonCode, reason, type, 17729 callingUid)); 17730 setUidTempAllowlistStateLSP(targetUid, true); 17731 mUiHandler.obtainMessage(PUSH_TEMP_ALLOWLIST_UI_MSG).sendToTarget(); 17732 17733 if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) { 17734 mFgsStartTempAllowList.add(targetUid, duration, 17735 new FgsTempAllowListItem(duration, reasonCode, reason, callingUid)); 17736 } 17737 } 17738 } 17739 pushTempAllowlist()17740 void pushTempAllowlist() { 17741 final int N; 17742 final PendingTempAllowlist[] list; 17743 17744 // First copy out the pending changes... we need to leave them in the map for now, 17745 // in case someone needs to check what is coming up while we don't have the lock held. 17746 synchronized (this) { 17747 synchronized (mProcLock) { 17748 N = mPendingTempAllowlist.size(); 17749 list = new PendingTempAllowlist[N]; 17750 for (int i = 0; i < N; i++) { 17751 list[i] = mPendingTempAllowlist.valueAt(i); 17752 } 17753 } 17754 } 17755 17756 // Now safely dispatch changes to device idle controller. Skip this if we're early 17757 // in boot and the controller hasn't yet been brought online: we do not apply 17758 // device idle policy anyway at this phase. 17759 if (mLocalDeviceIdleController != null) { 17760 for (int i = 0; i < N; i++) { 17761 PendingTempAllowlist ptw = list[i]; 17762 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid, 17763 ptw.duration, ptw.type, false, ptw.reasonCode, ptw.tag, 17764 ptw.callingUid); 17765 } 17766 } 17767 17768 // And now we can safely remove them from the map. 17769 synchronized (this) { 17770 synchronized (mProcLock) { 17771 for (int i = 0; i < N; i++) { 17772 PendingTempAllowlist ptw = list[i]; 17773 int index = mPendingTempAllowlist.indexOfKey(ptw.targetUid); 17774 if (index >= 0 && mPendingTempAllowlist.valueAt(index) == ptw) { 17775 mPendingTempAllowlist.removeAt(index); 17776 } 17777 } 17778 } 17779 } 17780 } 17781 17782 @GuardedBy({"this", "mProcLock"}) setUidTempAllowlistStateLSP(int uid, boolean onAllowlist)17783 final void setUidTempAllowlistStateLSP(int uid, boolean onAllowlist) { 17784 mOomAdjuster.setUidTempAllowlistStateLSP(uid, onAllowlist); 17785 } 17786 trimApplications(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason)17787 private void trimApplications(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason) { 17788 synchronized (this) { 17789 trimApplicationsLocked(forceFullOomAdj, oomAdjReason); 17790 } 17791 } 17792 17793 @GuardedBy("this") trimApplicationsLocked(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason)17794 private void trimApplicationsLocked(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason) { 17795 // First remove any unused application processes whose package 17796 // has been removed. 17797 boolean didSomething = false; 17798 for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) { 17799 final ProcessRecord app = mProcessList.mRemovedProcesses.get(i); 17800 if (!app.hasActivitiesOrRecentTasks() 17801 && app.mReceivers.numberOfCurReceivers() == 0 17802 && app.mServices.numberOfRunningServices() == 0) { 17803 final IApplicationThread thread = app.getThread(); 17804 Slog.i(TAG, "Exiting empty application process " 17805 + app.toShortString() + " (" 17806 + (thread != null ? thread.asBinder() : null) 17807 + ")\n"); 17808 final int pid = app.getPid(); 17809 if (pid > 0 && pid != MY_PID) { 17810 app.killLocked("empty", 17811 ApplicationExitInfo.REASON_OTHER, 17812 ApplicationExitInfo.SUBREASON_TRIM_EMPTY, 17813 false); 17814 } else if (thread != null) { 17815 try { 17816 thread.scheduleExit(); 17817 } catch (Exception e) { 17818 // Ignore exceptions. 17819 } 17820 } 17821 didSomething = true; 17822 cleanUpApplicationRecordLocked(app, pid, false, true, -1, false /*replacingPid*/, 17823 false /* fromBinderDied */); 17824 mProcessList.mRemovedProcesses.remove(i); 17825 17826 if (app.isPersistent()) { 17827 addAppLocked(app.info, null, false, null /* ABI override */, 17828 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 17829 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_PERSISTENT); 17830 } 17831 } 17832 } 17833 17834 // Now update the oom adj for all processes. Don't skip this, since other callers 17835 // might be depending on it. 17836 if (didSomething || forceFullOomAdj) { 17837 updateOomAdjLocked(oomAdjReason); 17838 } else { 17839 // Process any pending oomAdj targets, it'll be a no-op if nothing is pending. 17840 updateOomAdjPendingTargetsLocked(oomAdjReason); 17841 } 17842 } 17843 17844 /** This method sends the specified signal to each of the persistent apps */ signalPersistentProcesses(final int sig)17845 public void signalPersistentProcesses(final int sig) throws RemoteException { 17846 if (sig != SIGNAL_USR1) { 17847 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 17848 } 17849 17850 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 17851 != PackageManager.PERMISSION_GRANTED) { 17852 throw new SecurityException("Requires permission " 17853 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 17854 } 17855 17856 synchronized (mProcLock) { 17857 mProcessList.forEachLruProcessesLOSP(false, app -> { 17858 if (app.getThread() != null && app.isPersistent()) { 17859 sendSignal(app.getPid(), sig); 17860 } 17861 }); 17862 } 17863 } 17864 profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)17865 public boolean profileControl(String process, int userId, boolean start, 17866 ProfilerInfo profilerInfo, int profileType) throws RemoteException { 17867 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 17868 // its own permission. 17869 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17870 != PackageManager.PERMISSION_GRANTED) { 17871 throw new SecurityException("Requires permission " 17872 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17873 } 17874 17875 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) { 17876 throw new IllegalArgumentException("null profile info or fd"); 17877 } 17878 17879 ProcessRecord proc = null; 17880 synchronized (mProcLock) { 17881 if (process != null) { 17882 proc = findProcessLOSP(process, userId, "profileControl"); 17883 } 17884 17885 if (start && (proc == null || proc.getThread() == null)) { 17886 throw new IllegalArgumentException("Unknown process: " + process); 17887 } 17888 } 17889 17890 synchronized (mAppProfiler.mProfilerLock) { 17891 return mAppProfiler.profileControlLPf(proc, start, profilerInfo, profileType); 17892 } 17893 } 17894 17895 @GuardedBy(anyOf = {"this", "mProcLock"}) findProcessLOSP(String process, int userId, String callName)17896 private ProcessRecord findProcessLOSP(String process, int userId, String callName) { 17897 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 17898 userId, true, ALLOW_FULL_ONLY, callName, null); 17899 ProcessRecord proc = null; 17900 try { 17901 int pid = Integer.parseInt(process); 17902 synchronized (mPidsSelfLocked) { 17903 proc = mPidsSelfLocked.get(pid); 17904 } 17905 } catch (NumberFormatException e) { 17906 } 17907 17908 if (proc == null) { 17909 ArrayMap<String, SparseArray<ProcessRecord>> all = 17910 mProcessList.getProcessNamesLOSP().getMap(); 17911 SparseArray<ProcessRecord> procs = all.get(process); 17912 if (procs != null && procs.size() > 0) { 17913 proc = procs.valueAt(0); 17914 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 17915 for (int i=1; i<procs.size(); i++) { 17916 ProcessRecord thisProc = procs.valueAt(i); 17917 if (thisProc.userId == userId) { 17918 proc = thisProc; 17919 break; 17920 } 17921 } 17922 } 17923 } 17924 } 17925 17926 return proc; 17927 } 17928 17929 @Override dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String dumpBitmaps, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)17930 public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, 17931 boolean runGc, String dumpBitmaps, 17932 String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) { 17933 try { 17934 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 17935 // its own permission (same as profileControl). 17936 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17937 != PackageManager.PERMISSION_GRANTED) { 17938 throw new SecurityException("Requires permission " 17939 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17940 } 17941 17942 if (fd == null) { 17943 throw new IllegalArgumentException("null fd"); 17944 } 17945 17946 synchronized (this) { 17947 ProcessRecord proc = findProcessLOSP(process, userId, "dumpHeap"); 17948 IApplicationThread thread; 17949 if (proc == null || (thread = proc.getThread()) == null) { 17950 throw new IllegalArgumentException("Unknown process: " + process); 17951 } 17952 17953 enforceDebuggable(proc); 17954 17955 mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 17956 17957 final RemoteCallback intermediateCallback = new RemoteCallback( 17958 new RemoteCallback.OnResultListener() { 17959 @Override 17960 public void onResult(Bundle result) { 17961 finishCallback.sendResult(result); 17962 mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 17963 } 17964 }, null); 17965 17966 thread.dumpHeap(managed, mallocInfo, runGc, dumpBitmaps, 17967 path, fd, intermediateCallback); 17968 fd = null; 17969 return true; 17970 } 17971 } catch (RemoteException e) { 17972 throw new IllegalStateException("Process disappeared"); 17973 } finally { 17974 if (fd != null) { 17975 try { 17976 fd.close(); 17977 } catch (IOException e) { 17978 } 17979 } 17980 } 17981 } 17982 17983 /** 17984 * Dump the resources structure for the given process 17985 * 17986 * @param process The process to dump resource info for 17987 * @param fd The FileDescriptor to dump it into 17988 * @throws RemoteException 17989 */ dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback)17990 public boolean dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback) 17991 throws RemoteException { 17992 synchronized (this) { 17993 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_CURRENT, "dumpResources"); 17994 IApplicationThread thread; 17995 if (proc == null || (thread = proc.getThread()) == null) { 17996 throw new IllegalArgumentException("Unknown process: " + process); 17997 } 17998 thread.dumpResources(fd, callback); 17999 return true; 18000 } 18001 } 18002 18003 /** 18004 * Dump the resources structure for all processes 18005 * 18006 * @param fd The FileDescriptor to dump it into 18007 * @throws RemoteException 18008 */ dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw)18009 public void dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw) throws RemoteException { 18010 final ArrayList<ProcessRecord> processes = new ArrayList<>(); 18011 synchronized (this) { 18012 processes.addAll(mProcessList.getLruProcessesLOSP()); 18013 } 18014 for (int i = 0, size = processes.size(); i < size; i++) { 18015 ProcessRecord app = processes.get(i); 18016 pw.println(String.format("Resources History for %s (%s)", 18017 app.processName, 18018 app.info.packageName)); 18019 if (app.mOptRecord.isFrozen()) { 18020 pw.println(" Skipping frozen process"); 18021 pw.flush(); 18022 continue; 18023 } 18024 pw.flush(); 18025 try { 18026 TransferPipe tp = new TransferPipe(" "); 18027 try { 18028 IApplicationThread thread = app.getThread(); 18029 if (thread != null) { 18030 app.getThread().dumpResources(tp.getWriteFd(), null); 18031 tp.go(fd.getFileDescriptor(), 2000); 18032 } else { 18033 pw.println(String.format( 18034 " Resources history for %s (%s) failed, no thread", 18035 app.processName, 18036 app.info.packageName)); 18037 } 18038 } finally { 18039 tp.kill(); 18040 } 18041 } catch (IOException e) { 18042 pw.println(" " + e.getMessage()); 18043 pw.flush(); 18044 } 18045 18046 } 18047 } 18048 18049 @Override setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)18050 public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, 18051 String reportPackage) { 18052 if (processName != null) { 18053 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 18054 "setDumpHeapDebugLimit()"); 18055 } else { 18056 synchronized (mPidsSelfLocked) { 18057 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid()); 18058 if (proc == null) { 18059 throw new SecurityException("No process found for calling pid " 18060 + Binder.getCallingPid()); 18061 } 18062 enforceDebuggable(proc); 18063 processName = proc.processName; 18064 uid = proc.uid; 18065 if (reportPackage != null && !proc.getPkgList().containsKey(reportPackage)) { 18066 throw new SecurityException("Package " + reportPackage + " is not running in " 18067 + proc); 18068 } 18069 } 18070 } 18071 mAppProfiler.setDumpHeapDebugLimit(processName, uid, maxMemSize, reportPackage); 18072 } 18073 18074 @Override dumpHeapFinished(String path)18075 public void dumpHeapFinished(String path) { 18076 mAppProfiler.dumpHeapFinished(path, Binder.getCallingPid()); 18077 } 18078 18079 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ monitor()18080 public void monitor() { 18081 synchronized (this) { } 18082 } 18083 onCoreSettingsChange(Bundle settings)18084 void onCoreSettingsChange(Bundle settings) { 18085 synchronized (mProcLock) { 18086 mProcessList.updateCoreSettingsLOSP(settings); 18087 } 18088 } 18089 18090 // Multi-user methods 18091 18092 /** 18093 * Start user, if its not already running, but don't bring it to foreground. 18094 */ 18095 @Override startUserInBackground(final int userId)18096 public boolean startUserInBackground(final int userId) { 18097 return startUserInBackgroundWithListener(userId, null); 18098 } 18099 18100 @Override startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)18101 public boolean startUserInBackgroundWithListener(final int userId, 18102 @Nullable IProgressListener unlockListener) { 18103 return mUserController.startUser(userId, USER_START_MODE_BACKGROUND, unlockListener); 18104 } 18105 18106 @Override startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)18107 public boolean startUserInForegroundWithListener(final int userId, 18108 @Nullable IProgressListener unlockListener) { 18109 // Permission check done inside UserController. 18110 return mUserController.startUser(userId, USER_START_MODE_FOREGROUND, unlockListener); 18111 } 18112 18113 @Override startUserInBackgroundVisibleOnDisplay(int userId, int displayId, @Nullable IProgressListener unlockListener)18114 public boolean startUserInBackgroundVisibleOnDisplay(int userId, int displayId, 18115 @Nullable IProgressListener unlockListener) { 18116 int[] displayIds = getDisplayIdsForStartingVisibleBackgroundUsers(); 18117 boolean validDisplay = false; 18118 if (displayIds != null) { 18119 for (int i = 0; i < displayIds.length; i++) { 18120 if (displayId == displayIds[i]) { 18121 validDisplay = true; 18122 break; 18123 } 18124 } 18125 } 18126 if (!validDisplay) { 18127 throw new IllegalArgumentException("Invalid display (" + displayId + ") to start user. " 18128 + "Valid options are: " + Arrays.toString(displayIds)); 18129 } 18130 18131 if (DEBUG_MU) { 18132 Slogf.d(TAG_MU, "Calling startUserOnSecondaryDisplay(%d, %d, %s) using injector %s", 18133 userId, displayId, unlockListener, mInjector); 18134 } 18135 // Permission check done inside UserController. 18136 return mInjector.startUserInBackgroundVisibleOnDisplay(userId, displayId, unlockListener); 18137 } 18138 18139 @Override getDisplayIdsForStartingVisibleBackgroundUsers()18140 public int[] getDisplayIdsForStartingVisibleBackgroundUsers() { 18141 enforceCallingHasAtLeastOnePermission("getDisplayIdsForStartingVisibleBackgroundUsers()", 18142 MANAGE_USERS, INTERACT_ACROSS_USERS); 18143 return mInjector.getDisplayIdsForStartingVisibleBackgroundUsers(); 18144 } 18145 18146 /** @deprecated see the AIDL documentation {@inheritDoc} */ 18147 @Override 18148 @Deprecated unlockUser(@serIdInt int userId, @Nullable byte[] token, @Nullable byte[] secret, @Nullable IProgressListener listener)18149 public boolean unlockUser(@UserIdInt int userId, @Nullable byte[] token, 18150 @Nullable byte[] secret, @Nullable IProgressListener listener) { 18151 return mUserController.unlockUser(userId, listener); 18152 } 18153 18154 @Override unlockUser2(@serIdInt int userId, @Nullable IProgressListener listener)18155 public boolean unlockUser2(@UserIdInt int userId, @Nullable IProgressListener listener) { 18156 return mUserController.unlockUser(userId, listener); 18157 } 18158 18159 @Override switchUser(final int targetUserId)18160 public boolean switchUser(final int targetUserId) { 18161 return mUserController.switchUser(targetUserId); 18162 } 18163 18164 @Override getSwitchingFromUserMessage()18165 public String getSwitchingFromUserMessage() { 18166 return mUserController.getSwitchingFromSystemUserMessage(); 18167 } 18168 18169 @Override getSwitchingToUserMessage()18170 public String getSwitchingToUserMessage() { 18171 return mUserController.getSwitchingToSystemUserMessage(); 18172 } 18173 18174 @Override setStopUserOnSwitch(@topUserOnSwitch int value)18175 public void setStopUserOnSwitch(@StopUserOnSwitch int value) { 18176 mUserController.setStopUserOnSwitch(value); 18177 } 18178 18179 /** @deprecated use {@link #stopUserWithCallback(int, IStopUserCallback)} instead */ 18180 @Deprecated 18181 @Override stopUser(final int userId, boolean stopProfileRegardlessOfParent, final IStopUserCallback callback)18182 public int stopUser(final int userId, 18183 boolean stopProfileRegardlessOfParent, final IStopUserCallback callback) { 18184 return stopUserExceptCertainProfiles(userId, stopProfileRegardlessOfParent, callback); 18185 } 18186 18187 /** Stops the given user. */ 18188 @Override stopUserWithCallback(@serIdInt int userId, @Nullable IStopUserCallback callback)18189 public int stopUserWithCallback(@UserIdInt int userId, @Nullable IStopUserCallback callback) { 18190 return mUserController.stopUser(userId, /* allowDelayedLocking= */ false, 18191 /* callback= */ callback, /* keyEvictedCallback= */ null); 18192 } 18193 18194 /** 18195 * Stops the given user. 18196 * 18197 * Usually, callers can just use @link{#stopUserWithCallback(int, IStopUserCallback)} instead. 18198 * 18199 * @param stopProfileRegardlessOfParent whether to stop the profile regardless of who its 18200 * parent is, e.g. even if the parent is the current user; 18201 * its value is irrelevant for non-profile users. 18202 */ 18203 @Override stopUserExceptCertainProfiles(@serIdInt int userId, boolean stopProfileRegardlessOfParent, @Nullable IStopUserCallback callback)18204 public int stopUserExceptCertainProfiles(@UserIdInt int userId, 18205 boolean stopProfileRegardlessOfParent, @Nullable IStopUserCallback callback) { 18206 return mUserController.stopUser(userId, 18207 stopProfileRegardlessOfParent, /* allowDelayedLocking= */ false, 18208 /* callback= */ callback, /* keyEvictedCallback= */ null); 18209 } 18210 18211 /** 18212 * Stops user but allow delayed locking. Delayed locking keeps user unlocked even after 18213 * stopping only if {@code config_multiuserDelayUserDataLocking} overlay is set true on the 18214 * device or if the user has {@link UserProperties#getAllowStoppingUserWithDelayedLocking()} 18215 * set to true. 18216 * 18217 * <p>When delayed locking is not enabled through the overlay, this call becomes the same 18218 * with {@link #stopUserWithCallback(int, IStopUserCallback)} call. 18219 * 18220 * @param userId User id to stop. 18221 * @param callback Callback called when user has stopped. 18222 * 18223 * @return {@link ActivityManager#USER_OP_SUCCESS} when user is stopped successfully. Returns 18224 * other {@code ActivityManager#USER_OP_*} codes for failure. 18225 * 18226 */ 18227 @Override stopUserWithDelayedLocking(@serIdInt int userId, IStopUserCallback callback)18228 public int stopUserWithDelayedLocking(@UserIdInt int userId, IStopUserCallback callback) { 18229 return mUserController.stopUser(userId, /* allowDelayedLocking= */ true, 18230 /* callback= */ callback, /* keyEvictedCallback= */ null); 18231 } 18232 18233 @Override startProfile(@serIdInt int userId)18234 public boolean startProfile(@UserIdInt int userId) { 18235 return mUserController.startProfile(userId, /* evenWhenDisabled= */ false, 18236 /* unlockListener= */ null); 18237 } 18238 18239 @Override startProfileWithListener(@serIdInt int userId, @Nullable IProgressListener unlockListener)18240 public boolean startProfileWithListener(@UserIdInt int userId, 18241 @Nullable IProgressListener unlockListener) { 18242 return mUserController.startProfile(userId, /* evenWhenDisabled= */ false, unlockListener); 18243 } 18244 18245 @Override stopProfile(@serIdInt int userId)18246 public boolean stopProfile(@UserIdInt int userId) { 18247 return mUserController.stopProfile(userId); 18248 } 18249 18250 @Override getCurrentUser()18251 public UserInfo getCurrentUser() { 18252 return mUserController.getCurrentUser(); 18253 } 18254 18255 @Override getCurrentUserId()18256 public @UserIdInt int getCurrentUserId() { 18257 return mUserController.getCurrentUserIdChecked(); 18258 } 18259 getStartedUserState(int userId)18260 String getStartedUserState(int userId) { 18261 final UserState userState = mUserController.getStartedUserState(userId); 18262 return UserState.stateToString(userState.state); 18263 } 18264 18265 @Override isUserRunning(int userId, int flags)18266 public boolean isUserRunning(int userId, int flags) { 18267 if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId()) 18268 && checkCallingPermission(INTERACT_ACROSS_USERS) 18269 != PackageManager.PERMISSION_GRANTED) { 18270 String msg = "Permission Denial: isUserRunning() from pid=" 18271 + Binder.getCallingPid() 18272 + ", uid=" + Binder.getCallingUid() 18273 + " requires " + INTERACT_ACROSS_USERS; 18274 Slog.w(TAG, msg); 18275 throw new SecurityException(msg); 18276 } 18277 return mUserController.isUserRunning(userId, flags); 18278 } 18279 18280 @Override getRunningUserIds()18281 public int[] getRunningUserIds() { 18282 if (checkCallingPermission(INTERACT_ACROSS_USERS) 18283 != PackageManager.PERMISSION_GRANTED) { 18284 String msg = "Permission Denial: isUserRunning() from pid=" 18285 + Binder.getCallingPid() 18286 + ", uid=" + Binder.getCallingUid() 18287 + " requires " + INTERACT_ACROSS_USERS; 18288 Slog.w(TAG, msg); 18289 throw new SecurityException(msg); 18290 } 18291 return mUserController.getStartedUserArray(); 18292 } 18293 18294 @Override registerUserSwitchObserver(IUserSwitchObserver observer, String name)18295 public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) { 18296 mUserController.registerUserSwitchObserver(observer, name); 18297 } 18298 18299 @Override unregisterUserSwitchObserver(IUserSwitchObserver observer)18300 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 18301 mUserController.unregisterUserSwitchObserver(observer); 18302 } 18303 getAppInfoForUser(ApplicationInfo info, int userId)18304 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 18305 if (info == null) return null; 18306 ApplicationInfo newInfo = new ApplicationInfo(info); 18307 newInfo.initForUser(userId); 18308 return newInfo; 18309 } 18310 isUserStopped(int userId)18311 public boolean isUserStopped(int userId) { 18312 return mUserController.getStartedUserState(userId) == null; 18313 } 18314 getActivityInfoForUser(ActivityInfo aInfo, int userId)18315 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 18316 if (aInfo == null 18317 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 18318 return aInfo; 18319 } 18320 18321 ActivityInfo info = new ActivityInfo(aInfo); 18322 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 18323 return info; 18324 } 18325 18326 @GuardedBy("mProcLock") processSanityChecksLPr(ProcessRecord process, IApplicationThread thread)18327 private boolean processSanityChecksLPr(ProcessRecord process, IApplicationThread thread) { 18328 if (process == null || thread == null) { 18329 return false; 18330 } 18331 18332 return Build.IS_DEBUGGABLE || process.isDebuggable(); 18333 } 18334 startBinderTracking()18335 public boolean startBinderTracking() throws RemoteException { 18336 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 18337 // permission (same as profileControl). 18338 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 18339 != PackageManager.PERMISSION_GRANTED) { 18340 throw new SecurityException("Requires permission " 18341 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 18342 } 18343 18344 synchronized (mProcLock) { 18345 mBinderTransactionTrackingEnabled = true; 18346 mProcessList.forEachLruProcessesLOSP(true, process -> { 18347 final IApplicationThread thread = process.getThread(); 18348 if (!processSanityChecksLPr(process, thread)) { 18349 return; 18350 } 18351 try { 18352 thread.startBinderTracking(); 18353 } catch (RemoteException e) { 18354 Log.v(TAG, "Process disappared"); 18355 } 18356 }); 18357 } 18358 return true; 18359 } 18360 18361 @Override stopBinderTrackingAndDump(final ParcelFileDescriptor fd)18362 public boolean stopBinderTrackingAndDump(final ParcelFileDescriptor fd) throws RemoteException { 18363 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 18364 // permission (same as profileControl). 18365 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 18366 != PackageManager.PERMISSION_GRANTED) { 18367 throw new SecurityException("Requires permission " 18368 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 18369 } 18370 18371 boolean closeFd = true; 18372 try { 18373 synchronized (mProcLock) { 18374 if (fd == null) { 18375 throw new IllegalArgumentException("null fd"); 18376 } 18377 mBinderTransactionTrackingEnabled = false; 18378 18379 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor())); 18380 pw.println("Binder transaction traces for all processes.\n"); 18381 mProcessList.forEachLruProcessesLOSP(true, process -> { 18382 final IApplicationThread thread = process.getThread(); 18383 if (!processSanityChecksLPr(process, thread)) { 18384 return; 18385 } 18386 18387 pw.println("Traces for process: " + process.processName); 18388 pw.flush(); 18389 try { 18390 TransferPipe tp = new TransferPipe(); 18391 try { 18392 thread.stopBinderTrackingAndDump(tp.getWriteFd()); 18393 tp.go(fd.getFileDescriptor()); 18394 } finally { 18395 tp.kill(); 18396 } 18397 } catch (IOException e) { 18398 pw.println("Failure while dumping IPC traces from " + process + 18399 ". Exception: " + e); 18400 pw.flush(); 18401 } catch (RemoteException e) { 18402 pw.println("Got a RemoteException while dumping IPC traces from " + 18403 process + ". Exception: " + e); 18404 pw.flush(); 18405 } 18406 }); 18407 closeFd = false; 18408 return true; 18409 } 18410 } finally { 18411 if (fd != null && closeFd) { 18412 try { 18413 fd.close(); 18414 } catch (IOException e) { 18415 } 18416 } 18417 } 18418 } 18419 onProcessFreezableChangedLocked(ProcessRecord app)18420 void onProcessFreezableChangedLocked(ProcessRecord app) { 18421 mBroadcastQueue.onProcessFreezableChangedLocked(app); 18422 } 18423 18424 @VisibleForTesting 18425 public final class LocalService extends ActivityManagerInternal 18426 implements ActivityManagerLocal { 18427 18428 @Override getPendingIntentStats()18429 public List<PendingIntentStats> getPendingIntentStats() { 18430 return mPendingIntentController.dumpPendingIntentStatsForStatsd(); 18431 } 18432 18433 @Override getAppProfileStatsForDebugging(long time, int lines)18434 public Pair<String, String> getAppProfileStatsForDebugging(long time, int lines) { 18435 return mAppProfiler.getAppProfileStatsForDebugging(time, lines); 18436 } 18437 18438 @Override checkContentProviderAccess(String authority, int userId)18439 public String checkContentProviderAccess(String authority, int userId) { 18440 return mCpHelper.checkContentProviderAccess(authority, userId); 18441 } 18442 18443 @Override checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)18444 public int checkContentProviderUriPermission(Uri uri, int userId, 18445 int callingUid, int modeFlags) { 18446 return mCpHelper.checkContentProviderUriPermission(uri, userId, callingUid, modeFlags); 18447 } 18448 18449 @Override onWakefulnessChanged(int wakefulness)18450 public void onWakefulnessChanged(int wakefulness) { 18451 ActivityManagerService.this.onWakefulnessChanged(wakefulness); 18452 } 18453 18454 @Override startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)18455 public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 18456 String processName, String abiOverride, int uid, Runnable crashHandler) { 18457 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 18458 processName, abiOverride, uid, crashHandler); 18459 } 18460 18461 @Override startSdkSandboxService(Intent service, int clientAppUid, String clientAppPackage, String processName)18462 public ComponentName startSdkSandboxService(Intent service, int clientAppUid, 18463 String clientAppPackage, String processName) throws RemoteException { 18464 validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName); 18465 if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) 18466 != AppOpsManager.MODE_ALLOWED) { 18467 throw new IllegalArgumentException("uid does not belong to provided package"); 18468 } 18469 // TODO(b/269598719): Is passing the application thread of the system_server alright? 18470 // e.g. the sandbox getting privileged access due to this. 18471 ComponentName cn = ActivityManagerService.this.startService( 18472 mContext.getIApplicationThread(), service, 18473 service.resolveTypeIfNeeded(mContext.getContentResolver()), false, 18474 mContext.getOpPackageName(), mContext.getAttributionTag(), 18475 UserHandle.getUserId(clientAppUid), true, clientAppUid, clientAppPackage, 18476 processName); 18477 if (cn != null) { 18478 if (cn.getPackageName().equals("!")) { 18479 throw new SecurityException( 18480 "Not allowed to start service " + service 18481 + " without permission " + cn.getClassName()); 18482 } else if (cn.getPackageName().equals("!!")) { 18483 throw new SecurityException( 18484 "Unable to start service " + service 18485 + ": " + cn.getClassName()); 18486 } else if (cn.getPackageName().equals("?")) { 18487 throw ServiceStartNotAllowedException.newInstance(false, 18488 "Not allowed to start service " + service + ": " 18489 + cn.getClassName()); 18490 } 18491 } 18492 18493 return cn; 18494 } 18495 18496 @Override stopSdkSandboxService(Intent service, int clientAppUid, String clientAppPackage, String processName)18497 public boolean stopSdkSandboxService(Intent service, int clientAppUid, 18498 String clientAppPackage, String processName) { 18499 validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName); 18500 int res = ActivityManagerService.this.stopService( 18501 mContext.getIApplicationThread(), service, 18502 service.resolveTypeIfNeeded(mContext.getContentResolver()), 18503 UserHandle.getUserId(clientAppUid), true, clientAppUid, clientAppPackage, 18504 processName); 18505 if (res < 0) { 18506 throw new SecurityException( 18507 "Not allowed to stop service " + service); 18508 } 18509 return res != 0; 18510 } 18511 18512 @Override bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, int flags)18513 public boolean bindSdkSandboxService(Intent service, ServiceConnection conn, 18514 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, 18515 String processName, int flags) 18516 throws RemoteException { 18517 return bindSdkSandboxServiceInternal(service, conn, clientAppUid, 18518 clientApplicationThread, clientAppPackage, processName, 18519 Integer.toUnsignedLong(flags)); 18520 } 18521 18522 @Override bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, BindServiceFlags flags)18523 public boolean bindSdkSandboxService(Intent service, ServiceConnection conn, 18524 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, 18525 String processName, BindServiceFlags flags) throws RemoteException { 18526 return bindSdkSandboxServiceInternal(service, conn, clientAppUid, 18527 clientApplicationThread, clientAppPackage, processName, flags.getValue()); 18528 } 18529 bindSdkSandboxServiceInternal(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, long flags)18530 private boolean bindSdkSandboxServiceInternal(Intent service, ServiceConnection conn, 18531 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, 18532 String processName, long flags) 18533 throws RemoteException { 18534 validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName); 18535 if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) 18536 != AppOpsManager.MODE_ALLOWED) { 18537 throw new IllegalArgumentException("uid does not belong to provided package"); 18538 } 18539 if (conn == null) { 18540 throw new IllegalArgumentException("connection is null"); 18541 } 18542 18543 Handler handler = mContext.getMainThreadHandler(); 18544 IApplicationThread clientApplicationThreadVerified = null; 18545 if (clientApplicationThread != null) { 18546 // Make sure this is a valid application process 18547 synchronized (this) { 18548 final ProcessRecord rec = getRecordForAppLOSP(clientApplicationThread); 18549 if (rec == null) { 18550 // This could happen if the calling process has disappeared; no need for the 18551 // sandbox to be even started in this case. 18552 Slog.i(TAG, "clientApplicationThread process not found."); 18553 return false; 18554 } 18555 if (rec.info.uid != clientAppUid) { 18556 throw new IllegalArgumentException("clientApplicationThread does not match " 18557 + " client uid"); 18558 } 18559 clientApplicationThreadVerified = rec.getThread(); 18560 } 18561 } 18562 final IServiceConnection sd = mContext.getServiceDispatcher(conn, handler, 18563 flags); 18564 service.prepareToLeaveProcess(mContext); 18565 return ActivityManagerService.this.bindServiceInstance( 18566 mContext.getIApplicationThread(), mContext.getActivityToken(), service, 18567 service.resolveTypeIfNeeded(mContext.getContentResolver()), sd, 18568 flags, 18569 processName, /*isSdkSandboxService*/ true, clientAppUid, clientAppPackage, 18570 clientApplicationThreadVerified, mContext.getOpPackageName(), 18571 UserHandle.getUserId(clientAppUid)) != 0; 18572 } 18573 validateSdkSandboxParams(Intent service, int clientAppUid, String clientAppPackage, String processName)18574 private void validateSdkSandboxParams(Intent service, int clientAppUid, 18575 String clientAppPackage, String processName) { 18576 if (service == null) { 18577 throw new IllegalArgumentException("intent is null"); 18578 } 18579 if (clientAppPackage == null) { 18580 throw new IllegalArgumentException("clientAppPackage is null"); 18581 } 18582 if (processName == null) { 18583 throw new IllegalArgumentException("processName is null"); 18584 } 18585 if (service.getComponent() == null) { 18586 throw new IllegalArgumentException("service must specify explicit component"); 18587 } 18588 if (!UserHandle.isApp(clientAppUid)) { 18589 throw new IllegalArgumentException("uid is not within application range"); 18590 } 18591 } 18592 18593 @Override bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, String clientAppPackage, String processName, int flags)18594 public boolean bindSdkSandboxService(Intent service, ServiceConnection conn, 18595 int clientAppUid, String clientAppPackage, String processName, int flags) 18596 throws RemoteException { 18597 return bindSdkSandboxService(service, conn, clientAppUid, 18598 null /* clientApplicationThread */, clientAppPackage, processName, flags); 18599 } 18600 18601 @Override killSdkSandboxClientAppProcess(IBinder clientApplicationThreadBinder)18602 public void killSdkSandboxClientAppProcess(IBinder clientApplicationThreadBinder) { 18603 synchronized (ActivityManagerService.this) { 18604 ProcessRecord r = getRecordForAppLOSP(clientApplicationThreadBinder); 18605 if (r != null) { 18606 r.killLocked( 18607 "sdk sandbox died", 18608 ApplicationExitInfo.REASON_DEPENDENCY_DIED, 18609 ApplicationExitInfo.SUBREASON_SDK_SANDBOX_DIED, 18610 true); 18611 } 18612 } 18613 } 18614 18615 @Override onUserRemoved(@serIdInt int userId)18616 public void onUserRemoved(@UserIdInt int userId) { 18617 // Clean up any ActivityTaskManager state (by telling it the user is stopped) 18618 mAtmInternal.onUserStopped(userId); 18619 // Clean up various services by removing the user 18620 mBatteryStatsService.onUserRemoved(userId); 18621 18622 if (isHomeLaunchDelayable()) { 18623 synchronized (mThemeOverlayReadyUsers) { 18624 mThemeOverlayReadyUsers.remove(userId); 18625 } 18626 } 18627 } 18628 18629 @Override startUserInBackground(final int userId)18630 public boolean startUserInBackground(final int userId) { 18631 return ActivityManagerService.this.startUserInBackground(userId); 18632 } 18633 18634 @Override killForegroundAppsForUser(@serIdInt int userId)18635 public void killForegroundAppsForUser(@UserIdInt int userId) { 18636 final ArrayList<ProcessRecord> procs = new ArrayList<>(); 18637 synchronized (mProcLock) { 18638 final int numOfProcs = mProcessList.getProcessNamesLOSP().getMap().size(); 18639 for (int ip = 0; ip < numOfProcs; ip++) { 18640 final SparseArray<ProcessRecord> apps = 18641 mProcessList.getProcessNamesLOSP().getMap().valueAt(ip); 18642 final int NA = apps.size(); 18643 for (int ia = 0; ia < NA; ia++) { 18644 final ProcessRecord app = apps.valueAt(ia); 18645 if (app.isPersistent()) { 18646 // We don't kill persistent processes. 18647 continue; 18648 } 18649 if (app.isRemoved() 18650 || (app.userId == userId && app.mState.hasForegroundActivities())) { 18651 procs.add(app); 18652 } 18653 } 18654 } 18655 } 18656 18657 final int numOfProcs = procs.size(); 18658 if (numOfProcs > 0) { 18659 synchronized (ActivityManagerService.this) { 18660 for (int i = 0; i < numOfProcs; i++) { 18661 mProcessList.removeProcessLocked(procs.get(i), false, true, 18662 ApplicationExitInfo.REASON_OTHER, 18663 ApplicationExitInfo.SUBREASON_KILL_ALL_FG, 18664 "kill all fg"); 18665 } 18666 } 18667 } 18668 } 18669 18670 @Override setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, int type, @ReasonCode int reasonCode, @Nullable String reason)18671 public void setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, 18672 long duration, int type, @ReasonCode int reasonCode, @Nullable String reason) { 18673 mPendingIntentController.setPendingIntentAllowlistDuration(target, allowlistToken, 18674 duration, type, reasonCode, reason); 18675 } 18676 18677 @Override getPendingIntentFlags(IIntentSender target)18678 public int getPendingIntentFlags(IIntentSender target) { 18679 return mPendingIntentController.getPendingIntentFlags(target); 18680 } 18681 18682 @Override getStartedUserIds()18683 public int[] getStartedUserIds() { 18684 return mUserController.getStartedUserArray(); 18685 } 18686 18687 @Override setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken, int flags)18688 public void setPendingIntentAllowBgActivityStarts(IIntentSender target, 18689 IBinder allowlistToken, int flags) { 18690 if (!(target instanceof PendingIntentRecord)) { 18691 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():" 18692 + " not a PendingIntentRecord: " + target); 18693 return; 18694 } 18695 synchronized (ActivityManagerService.this) { 18696 ((PendingIntentRecord) target).setAllowBgActivityStarts(allowlistToken, flags); 18697 } 18698 } 18699 18700 @Override clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)18701 public void clearPendingIntentAllowBgActivityStarts(IIntentSender target, 18702 IBinder allowlistToken) { 18703 if (!(target instanceof PendingIntentRecord)) { 18704 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():" 18705 + " not a PendingIntentRecord: " + target); 18706 return; 18707 } 18708 synchronized (ActivityManagerService.this) { 18709 ((PendingIntentRecord) target).clearAllowBgActivityStarts(allowlistToken); 18710 } 18711 } 18712 18713 @Override setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)18714 public void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids) { 18715 synchronized (ActivityManagerService.this) { 18716 synchronized (mProcLock) { 18717 mDeviceIdleAllowlist = allAppids; 18718 mDeviceIdleExceptIdleAllowlist = exceptIdleAppids; 18719 mAppRestrictionController.setDeviceIdleAllowlist(allAppids, exceptIdleAppids); 18720 } 18721 } 18722 } 18723 18724 @Override updateDeviceIdleTempAllowlist(@ullable int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)18725 public void updateDeviceIdleTempAllowlist(@Nullable int[] appids, int changingUid, 18726 boolean adding, long durationMs, @TempAllowListType int type, 18727 @ReasonCode int reasonCode, @Nullable String reason, int callingUid) { 18728 synchronized (ActivityManagerService.this) { 18729 synchronized (mProcLock) { 18730 if (appids != null) { 18731 mDeviceIdleTempAllowlist = appids; 18732 } 18733 if (adding) { 18734 if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) { 18735 // Note, the device idle temp-allowlist are by app-ids, but here 18736 // mFgsStartTempAllowList contains UIDs. 18737 mFgsStartTempAllowList.add(changingUid, durationMs, 18738 new FgsTempAllowListItem(durationMs, reasonCode, reason, 18739 callingUid)); 18740 } 18741 } else { 18742 mFgsStartTempAllowList.removeUid(changingUid); 18743 } 18744 setUidTempAllowlistStateLSP(changingUid, adding); 18745 } 18746 } 18747 } 18748 18749 @Override getUidProcessState(int uid)18750 public int getUidProcessState(int uid) { 18751 return getUidState(uid); 18752 } 18753 18754 @Override getProcessesWithPendingBindMounts(int userId)18755 public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) { 18756 return mProcessList.getProcessesWithPendingBindMounts(userId); 18757 } 18758 18759 @Override isSystemReady()18760 public boolean isSystemReady() { 18761 // no need to synchronize(this) just to read & return the value 18762 return mSystemReady; 18763 } 18764 18765 @Override enforceBroadcastOptionsPermissions(Bundle options, int callingUid)18766 public void enforceBroadcastOptionsPermissions(Bundle options, int callingUid) { 18767 enforceBroadcastOptionPermissionsInternal(options, callingUid); 18768 } 18769 18770 /** 18771 * Returns package name by pid. 18772 */ 18773 @Override 18774 @Nullable getPackageNameByPid(int pid)18775 public String getPackageNameByPid(int pid) { 18776 synchronized (mPidsSelfLocked) { 18777 final ProcessRecord app = mPidsSelfLocked.get(pid); 18778 18779 if (app != null && app.info != null) { 18780 return app.info.packageName; 18781 } 18782 18783 return null; 18784 } 18785 } 18786 18787 /** 18788 * Sets if the given pid has an overlay UI or not. 18789 * 18790 * @param pid The pid we are setting overlay UI for. 18791 * @param hasOverlayUi True if the process has overlay UI. 18792 * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY 18793 */ 18794 @Override setHasOverlayUi(int pid, boolean hasOverlayUi)18795 public void setHasOverlayUi(int pid, boolean hasOverlayUi) { 18796 synchronized (ActivityManagerService.this) { 18797 final ProcessRecord pr; 18798 synchronized (mPidsSelfLocked) { 18799 pr = mPidsSelfLocked.get(pid); 18800 if (pr == null) { 18801 Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid); 18802 return; 18803 } 18804 } 18805 if (pr.mState.hasOverlayUi() == hasOverlayUi) { 18806 return; 18807 } 18808 pr.mState.setHasOverlayUi(hasOverlayUi); 18809 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid); 18810 updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY); 18811 } 18812 } 18813 18814 /** 18815 * Called after the network policy rules are updated by 18816 * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid} 18817 * and {@param procStateSeq}. 18818 */ 18819 @Override notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)18820 public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) { 18821 if (DEBUG_NETWORK) { 18822 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: " 18823 + uid + " seq: " + procStateSeq); 18824 } 18825 UidRecord record; 18826 synchronized (mProcLock) { 18827 record = mProcessList.getUidRecordLOSP(uid); 18828 if (record == null) { 18829 if (DEBUG_NETWORK) { 18830 Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid 18831 + " procStateSeq: " + procStateSeq); 18832 } 18833 return; 18834 } 18835 } 18836 synchronized (record.networkStateLock) { 18837 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 18838 if (DEBUG_NETWORK) { 18839 Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already" 18840 + " been handled for uid: " + uid); 18841 } 18842 return; 18843 } 18844 record.lastNetworkUpdatedProcStateSeq = procStateSeq; 18845 if (record.procStateSeqWaitingForNetwork != 0 18846 && procStateSeq >= record.procStateSeqWaitingForNetwork) { 18847 if (DEBUG_NETWORK) { 18848 Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid 18849 + ", procStateSeq: " + procStateSeq 18850 + ", procStateSeqWaitingForNetwork: " 18851 + record.procStateSeqWaitingForNetwork); 18852 } 18853 record.networkStateLock.notifyAll(); 18854 } 18855 } 18856 } 18857 18858 @Override onUidBlockedReasonsChanged(int uid, int blockedReasons)18859 public void onUidBlockedReasonsChanged(int uid, int blockedReasons) { 18860 synchronized (mUidNetworkBlockedReasons) { 18861 if (blockedReasons == BLOCKED_REASON_NONE) { 18862 mUidNetworkBlockedReasons.delete(uid); 18863 } else { 18864 mUidNetworkBlockedReasons.put(uid, blockedReasons); 18865 } 18866 } 18867 } 18868 18869 @Override isRuntimeRestarted()18870 public boolean isRuntimeRestarted() { 18871 return mSystemServiceManager.isRuntimeRestarted(); 18872 } 18873 18874 @Override canStartMoreUsers()18875 public boolean canStartMoreUsers() { 18876 return mUserController.canStartMoreUsers(); 18877 } 18878 18879 @Override setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)18880 public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) { 18881 mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage); 18882 } 18883 18884 @Override setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)18885 public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) { 18886 mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage); 18887 } 18888 18889 @Override getMaxRunningUsers()18890 public int getMaxRunningUsers() { 18891 return mUserController.getMaxRunningUsers(); 18892 } 18893 18894 @Override isUidActive(int uid)18895 public boolean isUidActive(int uid) { 18896 synchronized (mProcLock) { 18897 return isUidActiveLOSP(uid); 18898 } 18899 } 18900 18901 @Override getMemoryStateForProcesses()18902 public List<ProcessMemoryState> getMemoryStateForProcesses() { 18903 List<ProcessMemoryState> processMemoryStates = new ArrayList<>(); 18904 synchronized (mPidsSelfLocked) { 18905 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 18906 final ProcessRecord r = mPidsSelfLocked.valueAt(i); 18907 processMemoryStates.add(new ProcessMemoryState( 18908 r.uid, r.getPid(), r.processName, r.mState.getCurAdj(), 18909 r.mServices.hasForegroundServices(), 18910 r.mProfile.getCurrentHostingComponentTypes(), 18911 r.mProfile.getHistoricalHostingComponentTypes())); 18912 } 18913 } 18914 return processMemoryStates; 18915 } 18916 18917 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)18918 public int handleIncomingUser(int callingPid, int callingUid, int userId, 18919 boolean allowAll, int allowMode, String name, String callerPackage) { 18920 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 18921 allowMode, name, callerPackage); 18922 } 18923 18924 @Override enforceCallingPermission(String permission, String func)18925 public void enforceCallingPermission(String permission, String func) { 18926 ActivityManagerService.this.enforceCallingPermission(permission, func); 18927 } 18928 18929 @Override getCurrentAndTargetUserIds()18930 public Pair<Integer, Integer> getCurrentAndTargetUserIds() { 18931 return mUserController.getCurrentAndTargetUserIds(); 18932 } 18933 18934 @Override getCurrentUserId()18935 public int getCurrentUserId() { 18936 return mUserController.getCurrentUserId(); 18937 } 18938 18939 @Override isUserRunning(int userId, int flags)18940 public boolean isUserRunning(int userId, int flags) { 18941 // Holding am lock isn't required to call into user controller. 18942 return mUserController.isUserRunning(userId, flags); 18943 } 18944 18945 @Override trimApplications()18946 public void trimApplications() { 18947 ActivityManagerService.this.trimApplications(true, OOM_ADJ_REASON_ACTIVITY); 18948 } 18949 killProcessesForRemovedTask(ArrayList<Object> procsToKill)18950 public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) { 18951 synchronized (ActivityManagerService.this) { 18952 for (int i = 0; i < procsToKill.size(); i++) { 18953 final WindowProcessController wpc = 18954 (WindowProcessController) procsToKill.get(i); 18955 final ProcessRecord pr = (ProcessRecord) wpc.mOwner; 18956 if (ActivityManager.isProcStateBackground(pr.mState.getSetProcState()) 18957 && pr.mReceivers.numberOfCurReceivers() == 0 18958 && !pr.mState.hasStartedServices()) { 18959 pr.killLocked("remove task", ApplicationExitInfo.REASON_USER_REQUESTED, 18960 ApplicationExitInfo.SUBREASON_REMOVE_TASK, true); 18961 } else { 18962 // We delay killing processes that are not in the background or running a 18963 // receiver. 18964 pr.setWaitingToKill("remove task"); 18965 } 18966 } 18967 } 18968 } 18969 18970 @Override killProcess(String processName, int uid, String reason)18971 public void killProcess(String processName, int uid, String reason) { 18972 synchronized (ActivityManagerService.this) { 18973 final ProcessRecord proc = getProcessRecordLocked(processName, uid); 18974 if (proc != null) { 18975 mProcessList.removeProcessLocked(proc, false /* callerWillRestart */, 18976 true /* allowRestart */, ApplicationExitInfo.REASON_OTHER, reason); 18977 } 18978 } 18979 } 18980 18981 @Override hasRunningActivity(int uid, @Nullable String packageName)18982 public boolean hasRunningActivity(int uid, @Nullable String packageName) { 18983 if (packageName == null) return false; 18984 18985 synchronized (mProcLock) { 18986 return mProcessList.searchEachLruProcessesLOSP(true, app -> { 18987 if (app.uid == uid 18988 && app.getWindowProcessController().hasRunningActivity(packageName)) { 18989 return Boolean.TRUE; 18990 } 18991 return null; 18992 }) != null; 18993 } 18994 } 18995 18996 @Override updateOomAdj(@omAdjReason int oomAdjReason)18997 public void updateOomAdj(@OomAdjReason int oomAdjReason) { 18998 synchronized (ActivityManagerService.this) { 18999 ActivityManagerService.this.updateOomAdjLocked(oomAdjReason); 19000 } 19001 } 19002 19003 @Override updateCpuStats()19004 public void updateCpuStats() { 19005 ActivityManagerService.this.updateCpuStats(); 19006 } 19007 19008 @Override updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)19009 public void updateBatteryStats(ComponentName activity, int uid, int userId, 19010 boolean resumed) { 19011 ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed); 19012 } 19013 19014 @Override updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)19015 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 19016 IBinder appToken, ComponentName taskRoot, ActivityId activityId) { 19017 ActivityManagerService.this.updateActivityUsageStats(activity, userId, event, 19018 appToken, taskRoot, activityId); 19019 } 19020 19021 @Override updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)19022 public void updateForegroundTimeIfOnBattery( 19023 String packageName, int uid, long cpuTimeDiff) { 19024 mBatteryStatsService.updateForegroundTimeIfOnBattery(packageName, uid, cpuTimeDiff); 19025 } 19026 19027 @Override sendForegroundProfileChanged(int userId)19028 public void sendForegroundProfileChanged(int userId) { 19029 mUserController.sendForegroundProfileChanged(userId); 19030 } 19031 19032 @Override shouldConfirmCredentials(int userId)19033 public boolean shouldConfirmCredentials(int userId) { 19034 return mUserController.shouldConfirmCredentials(userId); 19035 } 19036 19037 @Override noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)19038 public void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, 19039 String tag) { 19040 ActivityManagerService.this.noteAlarmFinish((ps != null) ? ps.getTarget() : null, 19041 workSource, sourceUid, tag); 19042 } 19043 19044 @Override noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)19045 public void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, 19046 String tag) { 19047 ActivityManagerService.this.noteAlarmStart((ps != null) ? ps.getTarget() : null, 19048 workSource, sourceUid, tag); 19049 } 19050 19051 @Override noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)19052 public void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, 19053 String sourcePkg, String tag) { 19054 ActivityManagerService.this.noteWakeupAlarm((ps != null) ? ps.getTarget() : null, 19055 workSource, sourceUid, sourcePkg, tag); 19056 } 19057 19058 @Override isAppStartModeDisabled(int uid, String packageName)19059 public boolean isAppStartModeDisabled(int uid, String packageName) { 19060 return ActivityManagerService.this.isAppStartModeDisabled(uid, packageName); 19061 } 19062 19063 @Override getCurrentProfileIds()19064 public int[] getCurrentProfileIds() { 19065 return mUserController.getCurrentProfileIds(); 19066 } 19067 19068 @Override getCurrentUser()19069 public UserInfo getCurrentUser() { 19070 return mUserController.getCurrentUser(); 19071 } 19072 19073 @Override ensureNotSpecialUser(int userId)19074 public void ensureNotSpecialUser(int userId) { 19075 mUserController.ensureNotSpecialUser(userId); 19076 } 19077 19078 @Override isCurrentProfile(int userId)19079 public boolean isCurrentProfile(int userId) { 19080 return mUserController.isCurrentProfile(userId); 19081 } 19082 19083 @Override hasStartedUserState(int userId)19084 public boolean hasStartedUserState(int userId) { 19085 return mUserController.hasStartedUserState(userId); 19086 } 19087 19088 @Override finishUserSwitch(Object uss)19089 public void finishUserSwitch(Object uss) { 19090 mUserController.finishUserSwitch((UserState) uss); 19091 } 19092 19093 @Override scheduleAppGcs()19094 public void scheduleAppGcs() { 19095 synchronized (mAppProfiler.mProfilerLock) { 19096 mAppProfiler.scheduleAppGcsLPf(); 19097 } 19098 } 19099 19100 @Override getTaskIdForActivity(IBinder token, boolean onlyRoot)19101 public int getTaskIdForActivity(IBinder token, boolean onlyRoot) { 19102 return ActivityManagerService.this.getTaskForActivity(token, onlyRoot); 19103 } 19104 19105 @Override getActivityPresentationInfo(IBinder token)19106 public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) { 19107 final ActivityClient ac = ActivityClient.getInstance(); 19108 return new ActivityPresentationInfo(ac.getTaskForActivity(token, 19109 /*onlyRoot=*/ false), ac.getDisplayId(token), 19110 mAtmInternal.getActivityName(token)); 19111 } 19112 19113 @Override setBooting(boolean booting)19114 public void setBooting(boolean booting) { 19115 mBooting = booting; 19116 } 19117 19118 @Override isBooting()19119 public boolean isBooting() { 19120 return mBooting; 19121 } 19122 19123 @Override setBooted(boolean booted)19124 public void setBooted(boolean booted) { 19125 mBooted = booted; 19126 } 19127 19128 @Override isBooted()19129 public boolean isBooted() { 19130 return mBooted; 19131 } 19132 19133 @Override finishBooting()19134 public void finishBooting() { 19135 ActivityManagerService.this.finishBooting(); 19136 } 19137 19138 @Override tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)19139 public void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, 19140 long duration, int type, @ReasonCode int reasonCode, String reason) { 19141 synchronized (ActivityManagerService.this) { 19142 ActivityManagerService.this.tempAllowlistForPendingIntentLocked( 19143 callerPid, callerUid, targetUid, duration, type, reasonCode, reason); 19144 } 19145 } 19146 19147 @Override broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList)19148 public int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, 19149 int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 19150 IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode, 19151 String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, 19152 boolean serialized, boolean sticky, int userId, 19153 BackgroundStartPrivileges backgroundStartPrivileges, 19154 @Nullable int[] broadcastAllowList) { 19155 synchronized (ActivityManagerService.this) { 19156 final ProcessRecord resultToApp = getRecordForAppLOSP(resultToThread); 19157 return ActivityManagerService.this.broadcastIntentInPackage(packageName, featureId, 19158 uid, realCallingUid, realCallingPid, intent, resolvedType, resultToApp, 19159 resultTo, resultCode, resultData, resultExtras, requiredPermission, 19160 bOptions, serialized, sticky, userId, 19161 backgroundStartPrivileges, 19162 broadcastAllowList); 19163 } 19164 } 19165 19166 @Override broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)19167 public int broadcastIntent(Intent intent, 19168 IIntentReceiver resultTo, 19169 String[] requiredPermissions, 19170 boolean serialized, int userId, int[] appIdAllowList, 19171 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 19172 @Nullable Bundle bOptions) { 19173 synchronized (ActivityManagerService.this) { 19174 intent = verifyBroadcastLocked(intent); 19175 19176 final int callingPid = Binder.getCallingPid(); 19177 final int callingUid = Binder.getCallingUid(); 19178 final long origId = Binder.clearCallingIdentity(); 19179 try { 19180 return ActivityManagerService.this.broadcastIntentLocked(null /*callerApp*/, 19181 null /*callerPackage*/, null /*callingFeatureId*/, intent, 19182 null /* resolvedType */, null /* resultToApp */, resultTo, 19183 0 /* resultCode */, null /* resultData */, 19184 null /* resultExtras */, requiredPermissions, 19185 null /*excludedPermissions*/, null /*excludedPackages*/, 19186 AppOpsManager.OP_NONE, bOptions /*options*/, serialized, 19187 false /*sticky*/, callingPid, callingUid, callingUid, callingPid, 19188 userId, BackgroundStartPrivileges.NONE, 19189 appIdAllowList, filterExtrasForReceiver); 19190 } finally { 19191 Binder.restoreCallingIdentity(origId); 19192 } 19193 } 19194 } 19195 19196 @Override broadcastIntentWithCallback(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)19197 public int broadcastIntentWithCallback(Intent intent, 19198 IIntentReceiver resultTo, 19199 String[] requiredPermissions, 19200 int userId, int[] appIdAllowList, 19201 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 19202 @Nullable Bundle bOptions) { 19203 return broadcastIntent(intent, resultTo, requiredPermissions, false /* serialized */, 19204 userId, appIdAllowList, filterExtrasForReceiver, bOptions); 19205 } 19206 19207 @Override startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, int userId, BackgroundStartPrivileges backgroundStartPrivileges)19208 public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType, 19209 boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, 19210 int userId, BackgroundStartPrivileges backgroundStartPrivileges) 19211 throws TransactionTooLargeException { 19212 if (DEBUG_SERVICE) { 19213 Slog.v(TAG_SERVICE, 19214 "startServiceInPackage: " + service + " type=" + resolvedType); 19215 } 19216 final long origId = Binder.clearCallingIdentity(); 19217 ComponentName res; 19218 try { 19219 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 19220 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startServiceInPackage: " 19221 + "intent=" + service + ", caller=" + callingPackage 19222 + ", fgRequired=" + fgRequired); 19223 } 19224 synchronized (ActivityManagerService.this) { 19225 res = mServices.startServiceLocked(null, service, 19226 resolvedType, -1, uid, fgRequired, callingPackage, 19227 callingFeatureId, userId, 19228 backgroundStartPrivileges); 19229 } 19230 } finally { 19231 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 19232 Binder.restoreCallingIdentity(origId); 19233 } 19234 return res; 19235 } 19236 19237 // The arguments here are untyped because the base ActivityManagerInternal class 19238 // doesn't have compile-time visibility into ActivityServiceConnectionHolder or 19239 // ConnectionRecord. 19240 @Override disconnectActivityFromServices(Object connectionHolder)19241 public void disconnectActivityFromServices(Object connectionHolder) { 19242 // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder 19243 final ActivityServiceConnectionsHolder holder = 19244 (ActivityServiceConnectionsHolder) connectionHolder; 19245 synchronized (ActivityManagerService.this) { 19246 synchronized (mProcLock) { 19247 holder.forEachConnection(cr -> mServices.removeConnectionLocked( 19248 (ConnectionRecord) cr, null /* skipApp */, holder /* skipAct */, 19249 false /* enqueueOomAdj */)); 19250 } 19251 } 19252 } 19253 cleanUpServices(int userId, ComponentName component, Intent baseIntent)19254 public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) { 19255 synchronized(ActivityManagerService.this) { 19256 mServices.cleanUpServices(userId, component, baseIntent); 19257 } 19258 } 19259 getActivityInfoForUser(ActivityInfo aInfo, int userId)19260 public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 19261 // Locked intentionally not held as it isn't needed for this case. 19262 return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId); 19263 } 19264 ensureBootCompleted()19265 public void ensureBootCompleted() { 19266 // Locked intentionally not held as it isn't needed for this case. 19267 ActivityManagerService.this.ensureBootCompleted(); 19268 } 19269 updateOomLevelsForDisplay(int displayId)19270 public void updateOomLevelsForDisplay(int displayId) { 19271 synchronized(ActivityManagerService.this) { 19272 if (mWindowManager != null) { 19273 mProcessList.applyDisplaySize(mWindowManager); 19274 } 19275 } 19276 } 19277 isActivityStartsLoggingEnabled()19278 public boolean isActivityStartsLoggingEnabled() { 19279 return mConstants.mFlagActivityStartsLoggingEnabled; 19280 } 19281 isBackgroundActivityStartsEnabled()19282 public boolean isBackgroundActivityStartsEnabled() { 19283 return mConstants.mFlagBackgroundActivityStartsEnabled; 19284 } 19285 19286 @Override getBackgroundStartPrivileges(int uid)19287 public BackgroundStartPrivileges getBackgroundStartPrivileges(int uid) { 19288 return ActivityManagerService.this.getBackgroundStartPrivileges(uid); 19289 } 19290 19291 @Override canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)19292 public boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName) { 19293 return ActivityManagerService.this.canScheduleUserInitiatedJobs(uid, pid, pkgName); 19294 } 19295 reportCurKeyguardUsageEvent(boolean keyguardShowing)19296 public void reportCurKeyguardUsageEvent(boolean keyguardShowing) { 19297 ActivityManagerService.this.reportGlobalUsageEvent(keyguardShowing 19298 ? UsageEvents.Event.KEYGUARD_SHOWN 19299 : UsageEvents.Event.KEYGUARD_HIDDEN); 19300 } 19301 19302 @Override monitor()19303 public void monitor() { 19304 ActivityManagerService.this.monitor(); 19305 } 19306 19307 @Override inputDispatchingTimedOut(int pid, boolean aboveSystem, TimeoutRecord timeoutRecord)19308 public long inputDispatchingTimedOut(int pid, boolean aboveSystem, 19309 TimeoutRecord timeoutRecord) { 19310 return ActivityManagerService.this.inputDispatchingTimedOut(pid, aboveSystem, 19311 timeoutRecord); 19312 } 19313 19314 @Override inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, TimeoutRecord timeoutRecord)19315 public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName, 19316 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, 19317 boolean aboveSystem, TimeoutRecord timeoutRecord) { 19318 return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc, 19319 activityShortComponentName, aInfo, parentShortComponentName, 19320 (WindowProcessController) parentProc, aboveSystem, timeoutRecord); 19321 } 19322 19323 @Override inputDispatchingResumed(int pid)19324 public void inputDispatchingResumed(int pid) { 19325 final ProcessRecord proc; 19326 synchronized (mPidsSelfLocked) { 19327 proc = mPidsSelfLocked.get(pid); 19328 } 19329 if (proc != null) { 19330 mAppErrors.handleDismissAnrDialogs(proc); 19331 } 19332 } 19333 19334 @Override rescheduleAnrDialog(Object data)19335 public void rescheduleAnrDialog(Object data) { 19336 Message msg = Message.obtain(); 19337 msg.what = SHOW_NOT_RESPONDING_UI_MSG; 19338 msg.obj = (AppNotRespondingDialog.Data) data; 19339 19340 mUiHandler.sendMessageDelayed(msg, InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS); 19341 } 19342 19343 @Override broadcastGlobalConfigurationChanged(int changes, boolean initLocale)19344 public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) { 19345 synchronized (ActivityManagerService.this) { 19346 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 19347 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 19348 | Intent.FLAG_RECEIVER_REPLACE_PENDING 19349 | Intent.FLAG_RECEIVER_FOREGROUND 19350 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 19351 final Bundle configChangedOptions = new BroadcastOptions() 19352 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT) 19353 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE) 19354 .toBundle(); 19355 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 19356 null, null, OP_NONE, configChangedOptions, false, false, MY_PID, SYSTEM_UID, 19357 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 19358 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) { 19359 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 19360 intent.addFlags(Intent.FLAG_RECEIVER_OFFLOAD_FOREGROUND 19361 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND 19362 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 19363 if (initLocale || !mProcessesReady) { 19364 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 19365 } 19366 final BroadcastOptions bOptions = BroadcastOptions.makeBasic(); 19367 bOptions.setTemporaryAppAllowlist(mInternal.getBootTimeTempAllowListDuration(), 19368 TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED, 19369 PowerExemptionManager.REASON_LOCALE_CHANGED, ""); 19370 bOptions.setDeliveryGroupPolicy( 19371 BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT); 19372 bOptions.setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE); 19373 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 19374 null, null, OP_NONE, bOptions.toBundle(), false, false, MY_PID, 19375 SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(), 19376 UserHandle.USER_ALL); 19377 } 19378 19379 // Send a broadcast to PackageInstallers if the configuration change is interesting 19380 // for the purposes of installing additional splits. 19381 if (!initLocale && isSplitConfigurationChange(changes)) { 19382 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED); 19383 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING 19384 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 19385 19386 // Typically only app stores will have this permission. 19387 String[] permissions = 19388 new String[] { android.Manifest.permission.INSTALL_PACKAGES }; 19389 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, 19390 permissions, null, null, OP_NONE, null, false, false, MY_PID, 19391 SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(), 19392 UserHandle.USER_ALL); 19393 } 19394 } 19395 } 19396 19397 /** 19398 * Returns true if this configuration change is interesting enough to send an 19399 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast. 19400 */ isSplitConfigurationChange(int configDiff)19401 private boolean isSplitConfigurationChange(int configDiff) { 19402 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0; 19403 } 19404 19405 @Override broadcastCloseSystemDialogs(String reason)19406 public void broadcastCloseSystemDialogs(String reason) { 19407 synchronized (ActivityManagerService.this) { 19408 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 19409 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 19410 | Intent.FLAG_RECEIVER_FOREGROUND); 19411 if (reason != null) { 19412 intent.putExtra("reason", reason); 19413 } 19414 19415 final BroadcastOptions options = new BroadcastOptions() 19416 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT) 19417 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE); 19418 if (reason != null) { 19419 options.setDeliveryGroupMatchingKey(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, reason); 19420 } 19421 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 19422 null, null, OP_NONE, options.toBundle(), false, false, -1, SYSTEM_UID, 19423 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 19424 } 19425 } 19426 19427 @Override appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)19428 public void appNotResponding(@NonNull String processName, int uid, 19429 @NonNull TimeoutRecord timeoutRecord) { 19430 ActivityManagerService.this.appNotResponding(processName, uid, timeoutRecord); 19431 } 19432 19433 @Override killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)19434 public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 19435 synchronized (ActivityManagerService.this) { 19436 ActivityManagerService.this.killAllBackgroundProcessesExcept( 19437 minTargetSdk, maxProcState); 19438 } 19439 } 19440 19441 @Override startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)19442 public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, 19443 boolean isTop, String hostingType, ComponentName hostingName) { 19444 try { 19445 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 19446 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:" 19447 + processName); 19448 } 19449 synchronized (ActivityManagerService.this) { 19450 // If the process is known as top app, set a hint so when the process is 19451 // started, the top priority can be applied immediately to avoid cpu being 19452 // preempted by other processes before attaching the process of top app. 19453 HostingRecord hostingRecord = 19454 new HostingRecord(hostingType, hostingName, isTop); 19455 ProcessRecord rec = getProcessRecordLocked(processName, info.uid); 19456 ProcessRecord app = startProcessLocked(processName, info, knownToBeDead, 19457 0 /* intentFlags */, hostingRecord, 19458 ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */, 19459 false /* isolated */); 19460 } 19461 } finally { 19462 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 19463 } 19464 } 19465 19466 @Override setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)19467 public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, 19468 ProfilerInfo profilerInfo, Object wmLock) { 19469 synchronized (ActivityManagerService.this) { 19470 /** 19471 * This function is called from the window manager context and needs to be executed 19472 * synchronously. To avoid deadlock, we pass a message to AMS to execute the 19473 * function and notify the passed in lock when it has been completed. 19474 */ 19475 synchronized (wmLock) { 19476 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) { 19477 boolean suspend = 19478 (startFlags & ActivityManager.START_FLAG_DEBUG_SUSPEND) != 0; 19479 setDebugApp(aInfo.processName, true, false, suspend); 19480 } 19481 19482 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) { 19483 setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName); 19484 } 19485 19486 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) { 19487 setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName); 19488 } 19489 19490 if (profilerInfo != null) { 19491 setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo, null); 19492 } 19493 wmLock.notify(); 19494 } 19495 } 19496 } 19497 19498 @Override getStorageMountMode(int pid, int uid)19499 public int getStorageMountMode(int pid, int uid) { 19500 if (uid == SHELL_UID || uid == ROOT_UID) { 19501 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19502 } 19503 synchronized (mPidsSelfLocked) { 19504 final ProcessRecord pr = mPidsSelfLocked.get(pid); 19505 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.getMountMode(); 19506 } 19507 } 19508 19509 @Override isAppForeground(int uid)19510 public boolean isAppForeground(int uid) { 19511 return ActivityManagerService.this.isAppForeground(uid); 19512 } 19513 19514 @Override isAppBad(final String processName, final int uid)19515 public boolean isAppBad(final String processName, final int uid) { 19516 return ActivityManagerService.this.isAppBad(processName, uid); 19517 } 19518 19519 @Override clearPendingBackup(int userId)19520 public void clearPendingBackup(int userId) { 19521 ActivityManagerService.this.clearPendingBackup(userId); 19522 } 19523 19524 /** 19525 * When power button is very long pressed, call this interface to do some pre-shutdown work 19526 * like persisting database etc. 19527 */ 19528 @Override prepareForPossibleShutdown()19529 public void prepareForPossibleShutdown() { 19530 ActivityManagerService.this.prepareForPossibleShutdown(); 19531 } 19532 19533 @Override hasRunningForegroundService(int uid, int foregroundServicetype)19534 public boolean hasRunningForegroundService(int uid, int foregroundServicetype) { 19535 synchronized (ActivityManagerService.this) { 19536 final UidRecord uidRec = mProcessList.mActiveUids.get(uid); 19537 if (uidRec == null) { 19538 return false; 19539 } 19540 for (int i = uidRec.getNumOfProcs() - 1; i >= 0; i--) { 19541 final ProcessRecord app = uidRec.getProcessRecordByIndex(i); 19542 if ((app.mServices.containsAnyForegroundServiceTypes(foregroundServicetype))) { 19543 return true; 19544 } 19545 } 19546 return false; 19547 } 19548 } 19549 19550 @Override hasForegroundServiceNotification(String pkg, int userId, String channelId)19551 public boolean hasForegroundServiceNotification(String pkg, int userId, 19552 String channelId) { 19553 synchronized (ActivityManagerService.this) { 19554 return mServices.hasForegroundServiceNotificationLocked(pkg, userId, channelId); 19555 } 19556 } 19557 19558 @Override applyForegroundServiceNotification( Notification notification, String tag, int id, String pkg, int userId)19559 public ServiceNotificationPolicy applyForegroundServiceNotification( 19560 Notification notification, String tag, int id, String pkg, int userId) { 19561 synchronized (ActivityManagerService.this) { 19562 return mServices.applyForegroundServiceNotificationLocked(notification, 19563 tag, id, pkg, userId); 19564 } 19565 } 19566 19567 @Override onForegroundServiceNotificationUpdate(boolean shown, Notification notification, int id, String pkg, @UserIdInt int userId)19568 public void onForegroundServiceNotificationUpdate(boolean shown, 19569 Notification notification, int id, String pkg, @UserIdInt int userId) { 19570 synchronized (ActivityManagerService.this) { 19571 mServices.onForegroundServiceNotificationUpdateLocked(shown, 19572 notification, id, pkg, userId); 19573 } 19574 } 19575 19576 @Override stopAppForUser(String pkg, @UserIdInt int userId)19577 public void stopAppForUser(String pkg, @UserIdInt int userId) { 19578 ActivityManagerService.this.stopAppForUserInternal(pkg, userId); 19579 } 19580 19581 @Override registerProcessObserver(IProcessObserver processObserver)19582 public void registerProcessObserver(IProcessObserver processObserver) { 19583 ActivityManagerService.this.registerProcessObserver(processObserver); 19584 } 19585 19586 @Override unregisterProcessObserver(IProcessObserver processObserver)19587 public void unregisterProcessObserver(IProcessObserver processObserver) { 19588 ActivityManagerService.this.unregisterProcessObserver(processObserver); 19589 } 19590 19591 @Override getInstrumentationSourceUid(int uid)19592 public int getInstrumentationSourceUid(int uid) { 19593 synchronized (mProcLock) { 19594 for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) { 19595 ActiveInstrumentation activeInst = mActiveInstrumentation.get(i); 19596 if (!activeInst.mFinished && activeInst.mTargetInfo != null 19597 && activeInst.mTargetInfo.uid == uid) { 19598 return activeInst.mSourceUid; 19599 } 19600 } 19601 } 19602 return INVALID_UID; 19603 } 19604 19605 @Override setDeviceOwnerUid(int uid)19606 public void setDeviceOwnerUid(int uid) { 19607 mDeviceOwnerUid = uid; 19608 } 19609 19610 @Override isDeviceOwner(int uid)19611 public boolean isDeviceOwner(int uid) { 19612 int cachedUid = mDeviceOwnerUid; 19613 return uid >= 0 && cachedUid == uid; 19614 } 19615 19616 19617 @Override setProfileOwnerUid(ArraySet<Integer> profileOwnerUids)19618 public void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids) { 19619 synchronized (ActivityManagerService.this) { 19620 mProfileOwnerUids = profileOwnerUids; 19621 } 19622 } 19623 19624 @Override isProfileOwner(int uid)19625 public boolean isProfileOwner(int uid) { 19626 synchronized (ActivityManagerService.this) { 19627 return mProfileOwnerUids != null && mProfileOwnerUids.indexOf(uid) >= 0; 19628 } 19629 } 19630 19631 @Override setCompanionAppUids(int userId, Set<Integer> companionAppUids)19632 public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) { 19633 synchronized (ActivityManagerService.this) { 19634 mCompanionAppUidsMap.put(userId, companionAppUids); 19635 } 19636 } 19637 19638 @Override isAssociatedCompanionApp(int userId, int uid)19639 public boolean isAssociatedCompanionApp(int userId, int uid) { 19640 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId); 19641 if (allUids == null) { 19642 return false; 19643 } 19644 return allUids.contains(uid); 19645 } 19646 19647 @Override addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread)19648 public void addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread) { 19649 final boolean isNewPending = mPendingStartActivityUids.add(uid, pid); 19650 // If the next top activity is in cached and frozen mode, WM should raise its priority 19651 // to unfreeze it. This is done by calling AMS.updateOomAdj that will lower its oom adj. 19652 // However, WM cannot hold the AMS clock here so the updateOomAdj operation is performed 19653 // in a separate thread asynchronously. Therefore WM can't guarantee AMS will unfreeze 19654 // next top activity on time. This race will fail the following binder transactions WM 19655 // sends to the activity. After this race issue between WM/ATMS and AMS is solved, this 19656 // workaround can be removed. (b/213288355) 19657 if (isNewPending) { 19658 mOomAdjuster.mCachedAppOptimizer.unfreezeProcess(pid, OOM_ADJ_REASON_ACTIVITY); 19659 } 19660 // We need to update the network rules for the app coming to the top state so that 19661 // it can access network when the device or the app is in a restricted state 19662 // (e.g. battery/data saver) but since waiting for updateOomAdj to complete and then 19663 // informing NetworkPolicyManager might get delayed, informing the state change as soon 19664 // as we know app is going to come to the top state. 19665 if (isNewPending && mNetworkPolicyUidObserver != null) { 19666 try { 19667 final long procStateSeq = mProcessList.getNextProcStateSeq(); 19668 mNetworkPolicyUidObserver.onUidStateChanged(uid, PROCESS_STATE_TOP, 19669 procStateSeq, PROCESS_CAPABILITY_ALL); 19670 if (thread != null && shouldWaitForNetworkRulesUpdate(uid)) { 19671 thread.setNetworkBlockSeq(procStateSeq); 19672 } 19673 } catch (RemoteException e) { 19674 Slog.d(TAG, "Error calling setNetworkBlockSeq", e); 19675 } 19676 } 19677 } 19678 shouldWaitForNetworkRulesUpdate(int uid)19679 private boolean shouldWaitForNetworkRulesUpdate(int uid) { 19680 synchronized (mUidNetworkBlockedReasons) { 19681 // TODO: We can reuse this data in 19682 // ProcessList#incrementProcStateSeqAndNotifyAppsLOSP instead of calling into 19683 // NetworkManagementService. 19684 final int uidBlockedReasons = mUidNetworkBlockedReasons.get( 19685 uid, BLOCKED_REASON_NONE); 19686 // We should only inform the uid to block if it is currently blocked but will be 19687 // unblocked once it comes to the TOP state. 19688 return uidBlockedReasons != BLOCKED_REASON_NONE 19689 && updateBlockedReasonsWithProcState(uidBlockedReasons, PROCESS_STATE_TOP) 19690 == BLOCKED_REASON_NONE; 19691 } 19692 } 19693 19694 @Override deletePendingTopUid(int uid, long nowElapsed)19695 public void deletePendingTopUid(int uid, long nowElapsed) { 19696 mPendingStartActivityUids.delete(uid, nowElapsed); 19697 } 19698 19699 @Override isPendingTopUid(int uid)19700 public boolean isPendingTopUid(int uid) { 19701 return mPendingStartActivityUids.isPendingTopUid(uid); 19702 } 19703 19704 @Override getIntentForIntentSender(IIntentSender sender)19705 public Intent getIntentForIntentSender(IIntentSender sender) { 19706 return ActivityManagerService.this.getIntentForIntentSender(sender); 19707 } 19708 19709 @Override getPendingIntentActivityAsApp( int requestCode, @NonNull Intent intent, int flags, Bundle options, String ownerPkg, int ownerUid)19710 public PendingIntent getPendingIntentActivityAsApp( 19711 int requestCode, @NonNull Intent intent, int flags, Bundle options, 19712 String ownerPkg, int ownerUid) { 19713 return getPendingIntentActivityAsApp(requestCode, new Intent[] { intent }, flags, 19714 options, ownerPkg, ownerUid); 19715 } 19716 19717 @Override getPendingIntentActivityAsApp( int requestCode, @NonNull Intent[] intents, int flags, Bundle options, String ownerPkg, int ownerUid)19718 public PendingIntent getPendingIntentActivityAsApp( 19719 int requestCode, @NonNull Intent[] intents, int flags, Bundle options, 19720 String ownerPkg, int ownerUid) { 19721 // system callers must explicitly set mutability state 19722 final boolean flagImmutableSet = (flags & PendingIntent.FLAG_IMMUTABLE) != 0; 19723 final boolean flagMutableSet = (flags & PendingIntent.FLAG_MUTABLE) != 0; 19724 if (flagImmutableSet == flagMutableSet) { 19725 throw new IllegalArgumentException( 19726 "Must set exactly one of FLAG_IMMUTABLE or FLAG_MUTABLE"); 19727 } 19728 19729 final Context context = ActivityManagerService.this.mContext; 19730 final ContentResolver resolver = context.getContentResolver(); 19731 final int len = intents.length; 19732 final String[] resolvedTypes = new String[len]; 19733 for (int i = 0; i < len; i++) { 19734 final Intent intent = intents[i]; 19735 resolvedTypes[i] = intent.resolveTypeIfNeeded(resolver); 19736 intent.migrateExtraStreamToClipData(context); 19737 intent.prepareToLeaveProcess(context); 19738 } 19739 IIntentSender target = 19740 ActivityManagerService.this.getIntentSenderWithFeatureAsApp( 19741 INTENT_SENDER_ACTIVITY, ownerPkg, 19742 context.getAttributionTag(), null, null, requestCode, 19743 intents, 19744 resolvedTypes, 19745 flags, options, UserHandle.getUserId(ownerUid), ownerUid); 19746 return target != null ? new PendingIntent(target) : null; 19747 } 19748 19749 @Override getBootTimeTempAllowListDuration()19750 public long getBootTimeTempAllowListDuration() { 19751 // Do not lock ActivityManagerService.this here, this API is called by 19752 // PackageManagerService. 19753 return mConstants.mBootTimeTempAllowlistDuration; 19754 } 19755 19756 @Override registerAnrController(AnrController controller)19757 public void registerAnrController(AnrController controller) { 19758 mActivityTaskManager.registerAnrController(controller); 19759 } 19760 19761 @Override unregisterAnrController(AnrController controller)19762 public void unregisterAnrController(AnrController controller) { 19763 mActivityTaskManager.unregisterAnrController(controller); 19764 } 19765 19766 @Override canStartForegroundService(int pid, int uid, @NonNull String packageName)19767 public boolean canStartForegroundService(int pid, int uid, @NonNull String packageName) { 19768 synchronized (ActivityManagerService.this) { 19769 return mServices.canStartForegroundServiceLocked(pid, uid, packageName); 19770 } 19771 } 19772 19773 @Override tempAllowWhileInUsePermissionInFgs(int uid, long durationMs)19774 public void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs) { 19775 mFgsWhileInUseTempAllowList.add(uid, durationMs, ""); 19776 } 19777 19778 @Override isTempAllowlistedForFgsWhileInUse(int uid)19779 public boolean isTempAllowlistedForFgsWhileInUse(int uid) { 19780 return mFgsWhileInUseTempAllowList.isAllowed(uid); 19781 } 19782 19783 @Override canAllowWhileInUsePermissionInFgs(int pid, int uid, @NonNull String packageName)19784 public boolean canAllowWhileInUsePermissionInFgs(int pid, int uid, 19785 @NonNull String packageName) { 19786 synchronized (ActivityManagerService.this) { 19787 return mServices.canAllowWhileInUsePermissionInFgsLocked(pid, uid, packageName); 19788 } 19789 } 19790 19791 @Override getPushMessagingOverQuotaBehavior()19792 public @TempAllowListType int getPushMessagingOverQuotaBehavior() { 19793 synchronized (ActivityManagerService.this) { 19794 return mConstants.mPushMessagingOverQuotaBehavior; 19795 } 19796 } 19797 19798 @Override getServiceStartForegroundTimeout()19799 public int getServiceStartForegroundTimeout() { 19800 return mConstants.mServiceStartForegroundTimeoutMs; 19801 } 19802 19803 @Override getUidCapability(int uid)19804 public int getUidCapability(int uid) { 19805 synchronized (ActivityManagerService.this) { 19806 UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 19807 if (uidRecord == null) { 19808 throw new IllegalArgumentException("uid record for " + uid + " not found"); 19809 } 19810 return uidRecord.getCurCapability(); 19811 } 19812 } 19813 19814 /** 19815 * @return The PID list of the isolated process with packages matching the given uid. 19816 */ 19817 @Nullable getIsolatedProcesses(int uid)19818 public List<Integer> getIsolatedProcesses(int uid) { 19819 synchronized (ActivityManagerService.this) { 19820 return mProcessList.getIsolatedProcessesLocked(uid); 19821 } 19822 } 19823 19824 /** @see ActivityManagerService#sendIntentSender */ 19825 @Override sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)19826 public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, 19827 Intent intent, String resolvedType, 19828 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 19829 return ActivityManagerService.this.sendIntentSender(null, target, allowlistToken, code, 19830 intent, resolvedType, finishedReceiver, requiredPermission, options); 19831 } 19832 19833 @Override setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)19834 public void setVoiceInteractionManagerProvider( 19835 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) { 19836 ActivityManagerService.this.setVoiceInteractionManagerProvider(provider); 19837 } 19838 19839 @Override setStopUserOnSwitch(int value)19840 public void setStopUserOnSwitch(int value) { 19841 ActivityManagerService.this.setStopUserOnSwitch(value); 19842 } 19843 19844 @Override getRestrictionLevel(int uid)19845 public @RestrictionLevel int getRestrictionLevel(int uid) { 19846 return mAppRestrictionController.getRestrictionLevel(uid); 19847 } 19848 19849 @Override getRestrictionLevel(String pkg, @UserIdInt int userId)19850 public @RestrictionLevel int getRestrictionLevel(String pkg, @UserIdInt int userId) { 19851 return mAppRestrictionController.getRestrictionLevel(pkg, userId); 19852 } 19853 19854 @Override isBgAutoRestrictedBucketFeatureFlagEnabled()19855 public boolean isBgAutoRestrictedBucketFeatureFlagEnabled() { 19856 return mAppRestrictionController.isBgAutoRestrictedBucketFeatureFlagEnabled(); 19857 } 19858 19859 @Override addAppBackgroundRestrictionListener( @onNull ActivityManagerInternal.AppBackgroundRestrictionListener listener)19860 public void addAppBackgroundRestrictionListener( 19861 @NonNull ActivityManagerInternal.AppBackgroundRestrictionListener listener) { 19862 mAppRestrictionController.addAppBackgroundRestrictionListener(listener); 19863 } 19864 19865 @Override addForegroundServiceStateListener( @onNull ForegroundServiceStateListener listener)19866 public void addForegroundServiceStateListener( 19867 @NonNull ForegroundServiceStateListener listener) { 19868 synchronized (ActivityManagerService.this) { 19869 mForegroundServiceStateListeners.add(listener); 19870 } 19871 } 19872 19873 @Override addBroadcastEventListener(@onNull BroadcastEventListener listener)19874 public void addBroadcastEventListener(@NonNull BroadcastEventListener listener) { 19875 // It's a CopyOnWriteArrayList, so no lock is needed. 19876 mBroadcastEventListeners.add(listener); 19877 } 19878 19879 @Override addBindServiceEventListener(@onNull BindServiceEventListener listener)19880 public void addBindServiceEventListener(@NonNull BindServiceEventListener listener) { 19881 // It's a CopyOnWriteArrayList, so no lock is needed. 19882 mBindServiceEventListeners.add(listener); 19883 } 19884 19885 @Override restart()19886 public void restart() { 19887 ActivityManagerService.this.restart(); 19888 } 19889 19890 @Override registerNetworkPolicyUidObserver(@onNull IUidObserver observer, int which, int cutpoint, @NonNull String callingPackage)19891 public void registerNetworkPolicyUidObserver(@NonNull IUidObserver observer, 19892 int which, int cutpoint, @NonNull String callingPackage) { 19893 mNetworkPolicyUidObserver = observer; 19894 mUidObserverController.register(observer, which, cutpoint, callingPackage, 19895 Binder.getCallingUid(), /*uids*/null); 19896 } 19897 19898 @Override startForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options, @Nullable ServiceConnection connection)19899 public boolean startForegroundServiceDelegate( 19900 @NonNull ForegroundServiceDelegationOptions options, 19901 @Nullable ServiceConnection connection) { 19902 synchronized (ActivityManagerService.this) { 19903 return mServices.startForegroundServiceDelegateLocked(options, connection); 19904 } 19905 } 19906 19907 @Override stopForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options)19908 public void stopForegroundServiceDelegate( 19909 @NonNull ForegroundServiceDelegationOptions options) { 19910 synchronized (ActivityManagerService.this) { 19911 mServices.stopForegroundServiceDelegateLocked(options); 19912 } 19913 } 19914 19915 @Override stopForegroundServiceDelegate(@onNull ServiceConnection connection)19916 public void stopForegroundServiceDelegate(@NonNull ServiceConnection connection) { 19917 synchronized (ActivityManagerService.this) { 19918 mServices.stopForegroundServiceDelegateLocked(connection); 19919 } 19920 } 19921 19922 @Override getClientPackages(String servicePackageName)19923 public ArraySet<String> getClientPackages(String servicePackageName) { 19924 synchronized (ActivityManagerService.this) { 19925 return mServices.getClientPackagesLocked(servicePackageName); 19926 } 19927 } 19928 19929 @Override triggerUnsafeIntentStrictMode(int callingPid, int type, Intent intent)19930 public void triggerUnsafeIntentStrictMode(int callingPid, int type, Intent intent) { 19931 final IUnsafeIntentStrictModeCallback callback; 19932 final Intent i = intent.cloneFilter(); 19933 synchronized (ActivityManagerService.this) { 19934 callback = mStrictModeCallbacks.get(callingPid); 19935 } 19936 if (callback != null) { 19937 BackgroundThread.getExecutor().execute(() -> { 19938 try { 19939 callback.onUnsafeIntent(type, i); 19940 } catch (RemoteException e) { 19941 synchronized (ActivityManagerService.this) { 19942 mStrictModeCallbacks.remove(callingPid); 19943 } 19944 } 19945 }); 19946 } 19947 } 19948 19949 @Override startProfileEvenWhenDisabled(@serIdInt int userId)19950 public boolean startProfileEvenWhenDisabled(@UserIdInt int userId) { 19951 return mUserController.startProfile(userId, /* evenWhenDisabled= */ true, 19952 /* unlockListener= */ null); 19953 } 19954 19955 @Override logFgsApiBegin(@oregroundServiceApiType int apiType, int uid, int pid)19956 public void logFgsApiBegin(@ForegroundServiceApiType int apiType, 19957 int uid, int pid) { 19958 synchronized (this) { 19959 mServices.logFgsApiBeginLocked(apiType, uid, pid); 19960 } 19961 } 19962 19963 @Override logFgsApiEnd(@oregroundServiceApiType int apiType, int uid, int pid)19964 public void logFgsApiEnd(@ForegroundServiceApiType int apiType, 19965 int uid, int pid) { 19966 synchronized (this) { 19967 mServices.logFgsApiEndLocked(apiType, uid, pid); 19968 } 19969 } 19970 19971 @Override notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, @MediaProjectionTokenEvent int event)19972 public void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, 19973 @MediaProjectionTokenEvent int event) { 19974 ActivityManagerService.this.notifyMediaProjectionEvent(uid, projectionToken, event); 19975 } 19976 19977 @Override 19978 @NonNull getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull)19979 public StatsEvent getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull) { 19980 return mAppProfiler.mCachedAppsWatermarkData.getCachedAppsHighWatermarkStats( 19981 atomTag, resetAfterPull); 19982 } 19983 19984 @Override clearApplicationUserData(final String packageName, boolean keepState, boolean isRestore, final IPackageDataObserver observer, int userId)19985 public boolean clearApplicationUserData(final String packageName, boolean keepState, 19986 boolean isRestore, final IPackageDataObserver observer, int userId) { 19987 return ActivityManagerService.this.clearApplicationUserData(packageName, keepState, 19988 isRestore, observer, userId); 19989 } 19990 19991 @Override shouldDelayHomeLaunch(int userId)19992 public boolean shouldDelayHomeLaunch(int userId) { 19993 if (!isHomeLaunchDelayable()) return false; 19994 19995 synchronized (mThemeOverlayReadyUsers) { 19996 return !ActivityManagerService.this.mThemeOverlayReadyUsers.contains(userId); 19997 } 19998 } 19999 20000 @Override addStartInfoTimestamp(int key, long timestampNs, int uid, int pid, int userId)20001 public void addStartInfoTimestamp(int key, long timestampNs, int uid, int pid, 20002 int userId) { 20003 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 20004 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 20005 throw new IllegalArgumentException("Unsupported userId"); 20006 } 20007 20008 mUserController.handleIncomingUser(pid, uid, userId, true, 20009 ALLOW_NON_FULL, "addStartInfoTimestampSystem", null); 20010 20011 addStartInfoTimestampInternal(key, timestampNs, userId, uid); 20012 } 20013 20014 @Override killApplicationSync(String pkgName, int appId, int userId, String reason, int exitInfoReason)20015 public void killApplicationSync(String pkgName, int appId, int userId, 20016 String reason, int exitInfoReason) { 20017 if (pkgName == null) { 20018 return; 20019 } 20020 // Make sure the uid is valid. 20021 if (appId < 0) { 20022 Slog.w(TAG, "Invalid appid specified for pkg : " + pkgName); 20023 return; 20024 } 20025 synchronized (ActivityManagerService.this) { 20026 ActivityManagerService.this.forceStopPackageLocked(pkgName, appId, 20027 /* callerWillRestart= */ false, /*purgeCache= */ false, 20028 /* doit= */ true, /* evenPersistent= */ false, 20029 /* uninstalling= */ false, /* packageStateStopped= */ false, 20030 userId, reason, exitInfoReason); 20031 } 20032 } 20033 } 20034 20035 long inputDispatchingTimedOut(int pid, final boolean aboveSystem, TimeoutRecord timeoutRecord) { 20036 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 20037 throw new SecurityException("Requires permission " + FILTER_EVENTS); 20038 } 20039 ProcessRecord proc; 20040 timeoutRecord.mLatencyTracker.waitingOnPidLockStarted(); 20041 synchronized (mPidsSelfLocked) { 20042 timeoutRecord.mLatencyTracker.waitingOnPidLockEnded(); 20043 proc = mPidsSelfLocked.get(pid); 20044 } 20045 final long timeoutMillis = proc != null ? proc.getInputDispatchingTimeoutMillis() : 20046 DEFAULT_DISPATCHING_TIMEOUT_MILLIS; 20047 20048 if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, timeoutRecord)) { 20049 return 0; 20050 } 20051 20052 return timeoutMillis; 20053 } 20054 20055 /** 20056 * Handle input dispatching timeouts. 20057 * @return whether input dispatching should be aborted or not. 20058 */ 20059 boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, 20060 ApplicationInfo aInfo, String parentShortComponentName, 20061 WindowProcessController parentProcess, boolean aboveSystem, 20062 TimeoutRecord timeoutRecord) { 20063 try { 20064 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "inputDispatchingTimedOut()"); 20065 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 20066 throw new SecurityException("Requires permission " + FILTER_EVENTS); 20067 } 20068 20069 if (proc != null) { 20070 timeoutRecord.mLatencyTracker.waitingOnAMSLockStarted(); 20071 synchronized (this) { 20072 timeoutRecord.mLatencyTracker.waitingOnAMSLockEnded(); 20073 if (proc.isDebugging()) { 20074 return false; 20075 } 20076 20077 if (proc.getActiveInstrumentation() != null) { 20078 Bundle info = new Bundle(); 20079 info.putString("shortMsg", "keyDispatchingTimedOut"); 20080 info.putString("longMsg", timeoutRecord.mReason); 20081 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 20082 return true; 20083 } 20084 } 20085 mAnrHelper.appNotResponding(proc, activityShortComponentName, aInfo, 20086 parentShortComponentName, parentProcess, aboveSystem, timeoutRecord, 20087 /*isContinuousAnr*/ true); 20088 } 20089 20090 return true; 20091 } finally { 20092 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 20093 } 20094 } 20095 20096 /** 20097 * Called by app main thread to wait for the network policy rules to get updated. 20098 * 20099 * @param procStateSeq The sequence number indicating the process state change that the main 20100 * thread is interested in. 20101 */ 20102 @Override 20103 public void waitForNetworkStateUpdate(long procStateSeq) { 20104 final int callingUid = Binder.getCallingUid(); 20105 if (DEBUG_NETWORK) { 20106 Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq); 20107 } 20108 UidRecord record; 20109 synchronized (mProcLock) { 20110 record = mProcessList.getUidRecordLOSP(callingUid); 20111 if (record == null) { 20112 return; 20113 } 20114 } 20115 synchronized (record.networkStateLock) { 20116 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 20117 if (DEBUG_NETWORK) { 20118 Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. " 20119 + procStateSeq + ", so no need to wait. Uid: " 20120 + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: " 20121 + record.lastNetworkUpdatedProcStateSeq); 20122 } 20123 return; 20124 } 20125 try { 20126 if (DEBUG_NETWORK) { 20127 Slog.d(TAG_NETWORK, "Starting to wait for the network rules update." 20128 + " Uid: " + callingUid + " procStateSeq: " + procStateSeq); 20129 } 20130 final long startTime = SystemClock.uptimeMillis(); 20131 record.procStateSeqWaitingForNetwork = procStateSeq; 20132 record.networkStateLock.wait(mConstants.mNetworkAccessTimeoutMs); 20133 record.procStateSeqWaitingForNetwork = 0; 20134 final long totalTime = SystemClock.uptimeMillis() - startTime; 20135 if (totalTime >= mConstants.mNetworkAccessTimeoutMs || DEBUG_NETWORK) { 20136 Slog.wtf(TAG_NETWORK, "Total time waited for network rules to get updated: " 20137 + totalTime + ". Uid: " + callingUid + " procStateSeq: " 20138 + procStateSeq + " UidRec: " + record 20139 + " validateUidRec: " 20140 + mUidObserverController.getValidateUidRecord(callingUid)); 20141 } 20142 } catch (InterruptedException e) { 20143 Thread.currentThread().interrupt(); 20144 } 20145 } 20146 } 20147 20148 @Override 20149 public void waitForBroadcastIdle() { 20150 waitForBroadcastIdle(LOG_WRITER_INFO, false); 20151 } 20152 20153 void waitForBroadcastIdle(@NonNull PrintWriter pw, boolean flushBroadcastLoopers) { 20154 enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()"); 20155 if (flushBroadcastLoopers) { 20156 BroadcastLoopers.waitForIdle(pw); 20157 } 20158 mBroadcastQueue.waitForIdle(pw); 20159 pw.println("All broadcast queues are idle!"); 20160 pw.flush(); 20161 } 20162 20163 @Override 20164 public void waitForBroadcastBarrier() { 20165 waitForBroadcastBarrier(LOG_WRITER_INFO, false, false); 20166 } 20167 20168 void waitForBroadcastBarrier(@NonNull PrintWriter pw, 20169 boolean flushBroadcastLoopers, boolean flushApplicationThreads) { 20170 enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()"); 20171 if (flushBroadcastLoopers) { 20172 BroadcastLoopers.waitForBarrier(pw); 20173 } 20174 mBroadcastQueue.waitForBarrier(pw); 20175 if (flushApplicationThreads) { 20176 waitForApplicationBarrier(pw); 20177 } 20178 } 20179 20180 /** 20181 * Wait for all pending {@link IApplicationThread} events to be processed in 20182 * all currently running apps. 20183 */ 20184 void waitForApplicationBarrier(@NonNull PrintWriter pw) { 20185 final CountDownLatch finishedLatch = new CountDownLatch(1); 20186 final AtomicInteger pingCount = new AtomicInteger(0); 20187 final AtomicInteger pongCount = new AtomicInteger(0); 20188 final RemoteCallback pongCallback = new RemoteCallback((result) -> { 20189 if (pongCount.incrementAndGet() == pingCount.get()) { 20190 finishedLatch.countDown(); 20191 } 20192 }); 20193 20194 // Insert an extra "ping" as a sentinel value to guard us from finishing 20195 // too quickly in parallel below 20196 pingCount.incrementAndGet(); 20197 20198 synchronized (ActivityManagerService.this) { 20199 synchronized (mProcLock) { 20200 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 20201 mProcessList.getProcessNamesLOSP().getMap(); 20202 final int numProc = pmap.size(); 20203 for (int iProc = 0; iProc < numProc; iProc++) { 20204 final SparseArray<ProcessRecord> apps = pmap.valueAt(iProc); 20205 for (int iApp = 0, numApps = apps.size(); iApp < numApps; iApp++) { 20206 final ProcessRecord app = apps.valueAt(iApp); 20207 final IApplicationThread thread = app.getOnewayThread(); 20208 if (thread != null) { 20209 mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(app, 20210 CachedAppOptimizer.UNFREEZE_REASON_PING); 20211 pingCount.incrementAndGet(); 20212 try { 20213 thread.schedulePing(pongCallback); 20214 } catch (RemoteException ignored) { 20215 // When we failed to ping remote process, pretend as 20216 // if we received the expected pong 20217 pongCallback.sendResult(null); 20218 } 20219 } 20220 } 20221 } 20222 } 20223 } 20224 20225 // Now that we've dispatched all "ping" events above, we can send our 20226 // "pong" sentinel value 20227 pongCallback.sendResult(null); 20228 20229 // Wait for any remaining "pong" events to trickle in 20230 for (int i = 0; i < 30; i++) { 20231 try { 20232 if (finishedLatch.await(1, TimeUnit.SECONDS)) { 20233 pw.println("Finished application barriers!"); 20234 pw.flush(); 20235 return; 20236 } else { 20237 pw.println("Waiting for application barriers, at " + pongCount.get() + " of " 20238 + pingCount.get() + "..."); 20239 pw.flush(); 20240 } 20241 } catch (InterruptedException ignored) { 20242 } 20243 } 20244 pw.println("Gave up waiting for application barriers!"); 20245 pw.flush(); 20246 } 20247 20248 void waitForBroadcastDispatch(@NonNull PrintWriter pw, @NonNull Intent intent) { 20249 enforceCallingPermission(permission.DUMP, "waitForBroadcastDispatch"); 20250 mBroadcastQueue.waitForDispatched(intent, pw); 20251 } 20252 20253 void setIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) { 20254 Objects.requireNonNull(broadcastAction); 20255 enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()"); 20256 synchronized (mDeliveryGroupPolicyIgnoredActions) { 20257 mDeliveryGroupPolicyIgnoredActions.add(broadcastAction); 20258 } 20259 } 20260 20261 void clearIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) { 20262 Objects.requireNonNull(broadcastAction); 20263 enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()"); 20264 synchronized (mDeliveryGroupPolicyIgnoredActions) { 20265 mDeliveryGroupPolicyIgnoredActions.remove(broadcastAction); 20266 } 20267 } 20268 20269 boolean shouldIgnoreDeliveryGroupPolicy(@Nullable String broadcastAction) { 20270 if (broadcastAction == null) { 20271 return false; 20272 } 20273 synchronized (mDeliveryGroupPolicyIgnoredActions) { 20274 return mDeliveryGroupPolicyIgnoredActions.contains(broadcastAction); 20275 } 20276 } 20277 20278 void dumpDeliveryGroupPolicyIgnoredActions(IndentingPrintWriter ipw) { 20279 synchronized (mDeliveryGroupPolicyIgnoredActions) { 20280 ipw.println(mDeliveryGroupPolicyIgnoredActions); 20281 } 20282 } 20283 20284 @Override 20285 public void forceDelayBroadcastDelivery(@NonNull String targetPackage, 20286 long delayedDurationMs) { 20287 Objects.requireNonNull(targetPackage); 20288 Preconditions.checkArgumentNonnegative(delayedDurationMs); 20289 enforceCallingPermission(permission.DUMP, "forceDelayBroadcastDelivery()"); 20290 20291 mBroadcastQueue.forceDelayBroadcastDelivery(targetPackage, delayedDurationMs); 20292 } 20293 20294 @Override 20295 public boolean isProcessFrozen(int pid) { 20296 enforceCallingPermission(permission.DUMP, "isProcessFrozen()"); 20297 return mOomAdjuster.mCachedAppOptimizer.isProcessFrozen(pid); 20298 } 20299 20300 @Override 20301 @ReasonCode 20302 public int getBackgroundRestrictionExemptionReason(int uid) { 20303 enforceCallingPermission(android.Manifest.permission.DEVICE_POWER, 20304 "getBackgroundRestrictionExemptionReason()"); 20305 return mAppRestrictionController.getBackgroundRestrictionExemptionReason(uid); 20306 } 20307 20308 /** 20309 * Set an app's background restriction level. 20310 * This interface is intended for the shell command to use. 20311 */ 20312 void setBackgroundRestrictionLevel(String packageName, int uid, int userId, 20313 @RestrictionLevel int level, int reason, int subReason) { 20314 final int callingUid = Binder.getCallingUid(); 20315 if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) { 20316 throw new SecurityException( 20317 "No permission to change app restriction level"); 20318 } 20319 final long callingId = Binder.clearCallingIdentity(); 20320 try { 20321 final int curBucket = mUsageStatsService.getAppStandbyBucket(packageName, userId, 20322 SystemClock.elapsedRealtime()); 20323 mAppRestrictionController.applyRestrictionLevel(packageName, uid, level, 20324 null /* trackerInfo */, curBucket, true /* allowUpdateBucket */, 20325 reason, subReason); 20326 } finally { 20327 Binder.restoreCallingIdentity(callingId); 20328 } 20329 } 20330 20331 /** 20332 * Log the reason for changing an app restriction. Purely used for logging purposes and does not 20333 * cause any change to app state. 20334 * 20335 * @see ActivityManager#noteAppRestrictionEnabled(String, int, int, boolean, int, 20336 * String, int, long) 20337 */ 20338 @Override 20339 public void noteAppRestrictionEnabled(String packageName, int uid, 20340 @RestrictionLevel int restrictionType, boolean enabled, 20341 @ActivityManager.RestrictionReason int reason, String subReason, 20342 @ActivityManager.RestrictionSource int source, long threshold) { 20343 if (!android.app.Flags.appRestrictionsApi()) return; 20344 20345 enforceCallingPermission(android.Manifest.permission.DEVICE_POWER, 20346 "noteAppRestrictionEnabled()"); 20347 20348 final int userId = UserHandle.getCallingUserId(); 20349 final long callingId = Binder.clearCallingIdentity(); 20350 try { 20351 if (uid == INVALID_UID) { 20352 uid = mPackageManagerInt.getPackageUid(packageName, 0, userId); 20353 } 20354 mAppRestrictionController.noteAppRestrictionEnabled(packageName, uid, restrictionType, 20355 enabled, reason, subReason, source, threshold); 20356 } finally { 20357 Binder.restoreCallingIdentity(callingId); 20358 } 20359 } 20360 20361 /** 20362 * Get an app's background restriction level. 20363 * This interface is intended for the shell command to use. 20364 */ 20365 @RestrictionLevel int getBackgroundRestrictionLevel(String packageName, int userId) { 20366 final int callingUid = Binder.getCallingUid(); 20367 if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) { 20368 throw new SecurityException( 20369 "Don't have permission to query app background restriction level"); 20370 } 20371 final long callingId = Binder.clearCallingIdentity(); 20372 try { 20373 return mInternal.getRestrictionLevel(packageName, userId); 20374 } finally { 20375 Binder.restoreCallingIdentity(callingId); 20376 } 20377 } 20378 20379 /** 20380 * Start/stop foreground service delegate on a app's process. 20381 * This interface is intended for the shell command to use. 20382 */ 20383 void setForegroundServiceDelegate(String packageName, int uid, boolean isStart, 20384 @ForegroundServiceDelegationOptions.DelegationService int delegateService, 20385 String clientInstanceName) { 20386 final int callingUid = Binder.getCallingUid(); 20387 if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) { 20388 throw new SecurityException( 20389 "No permission to start/stop foreground service delegate"); 20390 } 20391 final long callingId = Binder.clearCallingIdentity(); 20392 try { 20393 boolean foundPid = false; 20394 synchronized (this) { 20395 ArrayList<ForegroundServiceDelegationOptions> delegates = new ArrayList<>(); 20396 synchronized (mPidsSelfLocked) { 20397 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 20398 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 20399 final IApplicationThread thread = p.getThread(); 20400 if (p.uid == uid && thread != null) { 20401 foundPid = true; 20402 int pid = mPidsSelfLocked.keyAt(i); 20403 ForegroundServiceDelegationOptions options = 20404 new ForegroundServiceDelegationOptions(pid, uid, packageName, 20405 null /* clientAppThread */, 20406 false /* isSticky */, 20407 clientInstanceName, 0 /* foregroundServiceType */, 20408 delegateService); 20409 delegates.add(options); 20410 } 20411 } 20412 } 20413 for (int i = delegates.size() - 1; i >= 0; i--) { 20414 final ForegroundServiceDelegationOptions options = delegates.get(i); 20415 if (isStart) { 20416 mInternal.startForegroundServiceDelegate(options, 20417 null /* connection */); 20418 } else { 20419 mInternal.stopForegroundServiceDelegate(options); 20420 } 20421 } 20422 } 20423 if (!foundPid) { 20424 Slog.e(TAG, "setForegroundServiceDelegate can not find process for packageName:" 20425 + packageName + " uid:" + uid); 20426 } 20427 } finally { 20428 Binder.restoreCallingIdentity(callingId); 20429 } 20430 } 20431 20432 /** 20433 * Force the settings cache to be loaded 20434 */ 20435 void refreshSettingsCache() { 20436 mCoreSettingsObserver.onChange(true); 20437 } 20438 20439 /** 20440 * Reset the dropbox rate limiter here and in BootReceiver 20441 */ 20442 void resetDropboxRateLimiter() { 20443 mDropboxRateLimiter.reset(); 20444 BootReceiver.resetDropboxRateLimiter(); 20445 } 20446 20447 /** 20448 * Kill processes for the user with id userId and that depend on the package named packageName 20449 */ 20450 @Override 20451 public void killPackageDependents(String packageName, int userId) { 20452 enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()"); 20453 if (packageName == null) { 20454 throw new NullPointerException( 20455 "Cannot kill the dependents of a package without its name."); 20456 } 20457 20458 final long callingId = Binder.clearCallingIdentity(); 20459 IPackageManager pm = AppGlobals.getPackageManager(); 20460 int pkgUid = -1; 20461 try { 20462 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 20463 } catch (RemoteException e) { 20464 } 20465 if (userId != UserHandle.USER_ALL && pkgUid == -1) { 20466 throw new IllegalArgumentException( 20467 "Cannot kill dependents of non-existing package " + packageName); 20468 } 20469 try { 20470 synchronized(this) { 20471 synchronized (mProcLock) { 20472 mProcessList.killPackageProcessesLSP(packageName, UserHandle.getAppId(pkgUid), 20473 userId, ProcessList.FOREGROUND_APP_ADJ, 20474 ApplicationExitInfo.REASON_DEPENDENCY_DIED, 20475 ApplicationExitInfo.SUBREASON_UNKNOWN, 20476 "dep: " + packageName); 20477 } 20478 } 20479 } finally { 20480 Binder.restoreCallingIdentity(callingId); 20481 } 20482 } 20483 20484 @Override 20485 public int restartUserInBackground(int userId, int userStartMode) { 20486 return mUserController.restartUser(userId, userStartMode); 20487 } 20488 20489 @Override 20490 public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) { 20491 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 20492 "scheduleApplicationInfoChanged()"); 20493 20494 final long origId = Binder.clearCallingIdentity(); 20495 try { 20496 final boolean updateFrameworkRes = packageNames.contains("android"); 20497 synchronized (mProcLock) { 20498 updateApplicationInfoLOSP(packageNames, updateFrameworkRes, userId); 20499 } 20500 20501 AppWidgetManagerInternal widgets = LocalServices.getService( 20502 AppWidgetManagerInternal.class); 20503 if (widgets != null) { 20504 widgets.applyResourceOverlaysToWidgets(new HashSet<>(packageNames), userId, 20505 updateFrameworkRes); 20506 } 20507 } finally { 20508 Binder.restoreCallingIdentity(origId); 20509 } 20510 } 20511 20512 /** 20513 * Synchronously update the system ActivityThread, bypassing any deferred threading so any 20514 * resources and overlaid values are available immediately. 20515 */ 20516 public void updateSystemUiContext() { 20517 final PackageManagerInternal packageManagerInternal = getPackageManagerInternal(); 20518 20519 ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android", 20520 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM); 20521 ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai); 20522 } 20523 20524 @GuardedBy(anyOf = {"this", "mProcLock"}) 20525 private void updateApplicationInfoLOSP(@NonNull List<String> packagesToUpdate, 20526 boolean updateFrameworkRes, int userId) { 20527 if (updateFrameworkRes) { 20528 ParsingPackageUtils.readConfigUseRoundIcon(null); 20529 } 20530 20531 mProcessList.updateApplicationInfoLOSP(packagesToUpdate, userId, updateFrameworkRes); 20532 20533 if (updateFrameworkRes) { 20534 // Update system server components that need to know about changed overlays. Because the 20535 // overlay is applied in ActivityThread, we need to serialize through its thread too. 20536 final Executor executor = ActivityThread.currentActivityThread().getExecutor(); 20537 final DisplayManagerInternal display = 20538 LocalServices.getService(DisplayManagerInternal.class); 20539 if (display != null) { 20540 executor.execute(display::onOverlayChanged); 20541 } 20542 if (mWindowManager != null) { 20543 executor.execute(mWindowManager::onOverlayChanged); 20544 } 20545 } 20546 } 20547 20548 /** 20549 * Update the binder call heavy hitter watcher per the new configuration 20550 */ 20551 void scheduleUpdateBinderHeavyHitterWatcherConfig() { 20552 // There are two sets of configs: the default watcher and the auto sampler, 20553 // the default one takes precedence. System would kick off auto sampler when there is 20554 // an anomaly (i.e., consecutive ANRs), but it'll be stopped automatically after a while. 20555 mHandler.post(() -> { 20556 final boolean enabled; 20557 final int batchSize; 20558 final float threshold; 20559 final BinderCallHeavyHitterListener listener; 20560 synchronized (mProcLock) { 20561 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 20562 // Default watcher takes precedence, ignore the auto sampler. 20563 mHandler.removeMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG); 20564 // Set the watcher with the default watcher's config 20565 enabled = true; 20566 batchSize = mConstants.BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE; 20567 threshold = mConstants.BINDER_HEAVY_HITTER_WATCHER_THRESHOLD; 20568 listener = (a, b, c, d) -> mHandler.post( 20569 () -> handleBinderHeavyHitters(a, b, c, d)); 20570 } else if (mHandler.hasMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG)) { 20571 // There is an ongoing auto sampler session, update it 20572 enabled = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED; 20573 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE; 20574 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD; 20575 listener = (a, b, c, d) -> mHandler.post( 20576 () -> handleBinderHeavyHitters(a, b, c, d)); 20577 } else { 20578 // Stop it 20579 enabled = false; 20580 batchSize = 0; 20581 threshold = 0.0f; 20582 listener = null; 20583 } 20584 } 20585 Binder.setHeavyHitterWatcherConfig(enabled, batchSize, threshold, listener); 20586 }); 20587 } 20588 20589 /** 20590 * Kick off the watcher to run for given timeout, it could be throttled however. 20591 */ 20592 void scheduleBinderHeavyHitterAutoSampler() { 20593 mHandler.post(() -> { 20594 final int batchSize; 20595 final float threshold; 20596 final long now; 20597 synchronized (mProcLock) { 20598 if (!mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED) { 20599 // It's configured OFF 20600 return; 20601 } 20602 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 20603 // If the default watcher is active already, don't start the auto sampler 20604 return; 20605 } 20606 now = SystemClock.uptimeMillis(); 20607 if (mLastBinderHeavyHitterAutoSamplerStart 20608 + BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS > now) { 20609 // Too frequent, throttle it 20610 return; 20611 } 20612 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE; 20613 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD; 20614 } 20615 // No lock is needed because we are accessing these variables in handle thread only. 20616 mLastBinderHeavyHitterAutoSamplerStart = now; 20617 // Start the watcher with the auto sampler's config. 20618 Binder.setHeavyHitterWatcherConfig(true, batchSize, threshold, 20619 (a, b, c, d) -> mHandler.post(() -> handleBinderHeavyHitters(a, b, c, d))); 20620 // Schedule to stop it after given timeout. 20621 mHandler.sendMessageDelayed(mHandler.obtainMessage( 20622 BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG), 20623 BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS); 20624 }); 20625 } 20626 20627 /** 20628 * Stop the binder heavy hitter auto sampler after given timeout. 20629 */ 20630 private void handleBinderHeavyHitterAutoSamplerTimeOut() { 20631 synchronized (mProcLock) { 20632 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 20633 // The default watcher is ON, don't bother to stop it. 20634 return; 20635 } 20636 } 20637 Binder.setHeavyHitterWatcherConfig(false, 0, 0.0f, null); 20638 } 20639 20640 /** 20641 * Handle the heavy hitters 20642 */ 20643 private void handleBinderHeavyHitters(@NonNull final List<HeavyHitterContainer> hitters, 20644 final int totalBinderCalls, final float threshold, final long timeSpan) { 20645 final int size = hitters.size(); 20646 if (size == 0) { 20647 return; 20648 } 20649 // Simply log it for now 20650 final String pfmt = "%.1f%%"; 20651 final BinderTransactionNameResolver resolver = new BinderTransactionNameResolver(); 20652 final StringBuilder sb = new StringBuilder("Excessive incoming binder calls(>") 20653 .append(String.format(pfmt, threshold * 100)) 20654 .append(',').append(totalBinderCalls) 20655 .append(',').append(timeSpan) 20656 .append("ms): "); 20657 for (int i = 0; i < size; i++) { 20658 if (i > 0) { 20659 sb.append(", "); 20660 } 20661 final HeavyHitterContainer container = hitters.get(i); 20662 sb.append('[').append(container.mUid) 20663 .append(',').append(container.mClass.getName()) 20664 .append(',').append(resolver.getMethodName(container.mClass, container.mCode)) 20665 .append(',').append(container.mCode) 20666 .append(',').append(String.format(pfmt, container.mFrequency * 100)) 20667 .append(']'); 20668 } 20669 Slog.w(TAG, sb.toString()); 20670 } 20671 20672 /** 20673 * Attach an agent to the specified process (proces name or PID) 20674 */ 20675 public void attachAgent(String process, String path) { 20676 try { 20677 synchronized (mProcLock) { 20678 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_SYSTEM, 20679 "attachAgent"); 20680 IApplicationThread thread; 20681 if (proc == null || (thread = proc.getThread()) == null) { 20682 throw new IllegalArgumentException("Unknown process: " + process); 20683 } 20684 20685 enforceDebuggable(proc); 20686 20687 thread.attachAgent(path); 20688 } 20689 } catch (RemoteException e) { 20690 throw new IllegalStateException("Process disappeared"); 20691 } 20692 } 20693 20694 /** 20695 * When power button is very long pressed, call this interface to do some pre-shutdown work 20696 * like persisting database etc. 20697 */ 20698 public void prepareForPossibleShutdown() { 20699 if (mUsageStatsService != null) { 20700 mUsageStatsService.prepareForPossibleShutdown(); 20701 } 20702 } 20703 20704 @VisibleForTesting 20705 public static class Injector { 20706 private final Context mContext; 20707 private NetworkManagementInternal mNmi; 20708 20709 private UserController mUserController; 20710 20711 public Injector(Context context) { 20712 mContext = context; 20713 } 20714 20715 public Context getContext() { 20716 return mContext; 20717 } 20718 20719 public AppOpsService getAppOpsService(File recentAccessesFile, File storageFile, 20720 Handler handler) { 20721 return new AppOpsService(recentAccessesFile, storageFile, handler, getContext()); 20722 } 20723 20724 public Handler getUiHandler(ActivityManagerService service) { 20725 return service.new UiHandler(); 20726 } 20727 20728 public boolean isNetworkRestrictedForUid(int uid) { 20729 if (ensureHasNetworkManagementInternal()) { 20730 return mNmi.isNetworkRestrictedForUid(uid); 20731 } 20732 return false; 20733 } 20734 20735 /** 20736 * Called by {@code AMS.getDisplayIdsForStartingVisibleBackgroundUsers()}. 20737 */ 20738 // NOTE: ideally Injector should have no complex logic, but if this logic was moved to AMS, 20739 // it could not be tested with the existing ActivityManagerServiceTest (as DisplayManager, 20740 // DisplayInfo, etc... are final and UserManager.isUsersOnSecondaryDisplaysEnabled is 20741 // static). 20742 // So, the logic was added here, and tested on ActivityManagerServiceInjectorTest (which 20743 // was added on FrameworksMockingServicesTests and hence uses Extended Mockito to mock 20744 // final and static stuff) 20745 @Nullable 20746 public int[] getDisplayIdsForStartingVisibleBackgroundUsers() { 20747 if (!UserManager.isVisibleBackgroundUsersEnabled()) { 20748 Slogf.w(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): not supported"); 20749 return null; 20750 } 20751 20752 // NOTE: DisplayManagerInternal doesn't have a method to list all displays 20753 DisplayManager displayManager = mContext.getSystemService(DisplayManager.class); 20754 20755 Display[] allDisplays = displayManager.getDisplays(); 20756 20757 // allDisplays should contain at least Display.DEFAULT_DISPLAY, but it's better to 20758 // double check, just in case... 20759 if (allDisplays == null || allDisplays.length == 0) { 20760 Slogf.wtf(TAG, "displayManager (%s) returned no displays", displayManager); 20761 return null; 20762 } 20763 boolean hasDefaultDisplay = false; 20764 for (Display display : allDisplays) { 20765 if (display.getDisplayId() == Display.DEFAULT_DISPLAY) { 20766 hasDefaultDisplay = true; 20767 break; 20768 } 20769 } 20770 if (!hasDefaultDisplay) { 20771 Slogf.wtf(TAG, "displayManager (%s) has %d displays (%s), but none has id " 20772 + "DEFAULT_DISPLAY (%d)", displayManager, allDisplays.length, 20773 Arrays.toString(allDisplays), Display.DEFAULT_DISPLAY); 20774 return null; 20775 } 20776 20777 boolean allowOnDefaultDisplay = UserManager 20778 .isVisibleBackgroundUsersOnDefaultDisplayEnabled(); 20779 int displaysSize = allDisplays.length; 20780 if (!allowOnDefaultDisplay) { 20781 displaysSize--; 20782 } 20783 int[] displayIds = new int[displaysSize]; 20784 20785 int numberValidDisplays = 0; 20786 for (Display display : allDisplays) { 20787 int displayId = display.getDisplayId(); 20788 // TODO(b/247592632): check other properties like isSecure or proper display type 20789 if (display.isValid() && ((display.getFlags() & Display.FLAG_PRIVATE) == 0) 20790 && (allowOnDefaultDisplay || displayId != Display.DEFAULT_DISPLAY)) { 20791 displayIds[numberValidDisplays++] = displayId; 20792 } 20793 } 20794 20795 if (numberValidDisplays == 0) { 20796 // TODO(b/247580038): remove this workaround once a virtual display on Car's 20797 // KitchenSink (or other app) can be used while running CTS tests on devices that 20798 // don't have a real display. 20799 // STOPSHIP: if not removed, it should at least be unit tested 20800 String testingProp = "fw.display_ids_for_starting_users_for_testing_purposes"; 20801 int displayId = SystemProperties.getInt(testingProp, Display.DEFAULT_DISPLAY); 20802 if (allowOnDefaultDisplay && displayId == Display.DEFAULT_DISPLAY 20803 || displayId > 0) { 20804 Slogf.w(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): no valid " 20805 + "display found, but returning %d as set by property %s", displayId, 20806 testingProp); 20807 return new int[] { displayId }; 20808 } 20809 Slogf.e(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): no valid display" 20810 + " on %s", Arrays.toString(allDisplays)); 20811 return null; 20812 } 20813 20814 if (numberValidDisplays != displayIds.length) { 20815 int[] validDisplayIds = new int[numberValidDisplays]; 20816 System.arraycopy(displayIds, 0, validDisplayIds, 0, numberValidDisplays); 20817 if (DEBUG_MU) { 20818 Slogf.d(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): returning " 20819 + "only valid displays (%d instead of %d): %s", numberValidDisplays, 20820 displayIds.length, Arrays.toString(validDisplayIds)); 20821 } 20822 return validDisplayIds; 20823 } 20824 20825 if (DEBUG_MU) { 20826 Slogf.d(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): returning all (but " 20827 + "DEFAULT_DISPLAY) displays : %s", Arrays.toString(displayIds)); 20828 } 20829 return displayIds; 20830 } 20831 20832 /** 20833 * Called by {@code AMS.startUserInBackgroundVisibleOnDisplay()}. 20834 */ 20835 public boolean startUserInBackgroundVisibleOnDisplay(int userId, int displayId, 20836 @Nullable IProgressListener unlockProgressListener) { 20837 return mUserController.startUserVisibleOnDisplay(userId, displayId, 20838 unlockProgressListener); 20839 } 20840 20841 /** 20842 * Return the process list instance 20843 */ 20844 public ProcessList getProcessList(ActivityManagerService service) { 20845 return new ProcessList(); 20846 } 20847 20848 /** 20849 * Returns the {@link BatteryStatsService} instance 20850 */ 20851 public BatteryStatsService getBatteryStatsService() { 20852 return new BatteryStatsService(mContext, SystemServiceManager.ensureSystemDir()); 20853 } 20854 20855 /** 20856 * Returns the {@link ActiveServices} instance 20857 */ 20858 public ActiveServices getActiveServices(ActivityManagerService service) { 20859 return new ActiveServices(service); 20860 } 20861 20862 private boolean ensureHasNetworkManagementInternal() { 20863 if (mNmi == null) { 20864 mNmi = LocalServices.getService(NetworkManagementInternal.class); 20865 } 20866 return mNmi != null; 20867 } 20868 20869 public BroadcastQueue getBroadcastQueue(ActivityManagerService service) { 20870 // Broadcast policy parameters 20871 final BroadcastConstants foreConstants = new BroadcastConstants( 20872 Settings.Global.BROADCAST_FG_CONSTANTS); 20873 foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT; 20874 20875 final BroadcastConstants backConstants = new BroadcastConstants( 20876 Settings.Global.BROADCAST_BG_CONSTANTS); 20877 backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; 20878 20879 return new BroadcastQueueModernImpl(service, service.mHandler, 20880 foreConstants, backConstants); 20881 } 20882 20883 /** @see Binder#getCallingUid */ 20884 public int getCallingUid() { 20885 return Binder.getCallingUid(); 20886 } 20887 20888 /** @see Binder#getCallingPid */ 20889 public int getCallingPid() { 20890 return Binder.getCallingPid(); 20891 } 20892 20893 /** @see Binder#clearCallingIdentity */ 20894 public long clearCallingIdentity() { 20895 return Binder.clearCallingIdentity(); 20896 } 20897 20898 /** @see Binder#clearCallingIdentity */ 20899 public void restoreCallingIdentity(long ident) { 20900 Binder.restoreCallingIdentity(ident); 20901 } 20902 20903 /** @return the default instance of AppErrors */ 20904 public AppErrors getAppErrors() { 20905 return null; 20906 } 20907 20908 /** @return the default instance of intent firewall */ 20909 public IntentFirewall getIntentFirewall() { 20910 return null; 20911 } 20912 } 20913 20914 @Override 20915 public void startDelegateShellPermissionIdentity(int delegateUid, 20916 @Nullable String[] permissions) { 20917 getAccessCheckDelegateHelper() 20918 .startDelegateShellPermissionIdentity(delegateUid, permissions); 20919 } 20920 20921 @Override 20922 public void stopDelegateShellPermissionIdentity() { 20923 getAccessCheckDelegateHelper().stopDelegateShellPermissionIdentity(); 20924 } 20925 20926 @Override 20927 public List<String> getDelegatedShellPermissions() { 20928 return getAccessCheckDelegateHelper().getDelegatedShellPermissions(); 20929 } 20930 20931 @Override 20932 public void addOverridePermissionState(int originatingUid, int uid, String permission, 20933 int result) { 20934 getAccessCheckDelegateHelper() 20935 .addOverridePermissionState(originatingUid, uid, permission, result); 20936 } 20937 20938 @Override 20939 public void removeOverridePermissionState(int originatingUid, int uid, String permission) { 20940 getAccessCheckDelegateHelper() 20941 .removeOverridePermissionState(originatingUid, uid, permission); 20942 } 20943 20944 @Override 20945 public void clearOverridePermissionStates(int originatingUid, int uid) { 20946 getAccessCheckDelegateHelper().clearOverridePermissionStates(originatingUid, uid); 20947 } 20948 20949 @Override 20950 public void clearAllOverridePermissionStates(int originatingUid) { 20951 getAccessCheckDelegateHelper().clearAllOverridePermissionStates(originatingUid); 20952 } 20953 20954 /** 20955 * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would 20956 * cause a watchdog kill. 20957 */ 20958 void maybeTriggerWatchdog() { 20959 final String key = "debug.trigger.watchdog"; 20960 if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) { 20961 Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!"); 20962 20963 // Clear the property; otherwise the system would hang again after a watchdog restart. 20964 SystemProperties.set(key, ""); 20965 synchronized (ActivityManagerService.this) { 20966 try { 20967 // Arbitrary long sleep for watchdog to catch. 20968 Thread.sleep(60 * 60 * 1000); 20969 } catch (InterruptedException e) { 20970 } 20971 } 20972 } 20973 } 20974 20975 @Override 20976 public ParcelFileDescriptor getLifeMonitor() { 20977 if (!isCallerShell()) { 20978 throw new SecurityException("Only shell can call it"); 20979 } 20980 synchronized (mProcLock) { 20981 try { 20982 if (mLifeMonitorFds == null) { 20983 mLifeMonitorFds = ParcelFileDescriptor.createPipe(); 20984 } 20985 // The returned FD will be closed, but we want to keep our reader open, 20986 // so return a dup instead. 20987 return mLifeMonitorFds[0].dup(); 20988 } catch (IOException e) { 20989 Slog.w(TAG, "Unable to create pipe", e); 20990 return null; 20991 } 20992 } 20993 } 20994 20995 @Override 20996 public void setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken) { 20997 final int callingUid = Binder.getCallingUid(); 20998 final int userId = UserHandle.getCallingUserId(); 20999 if (getPackageManagerInternal().getPackageUid(activity.getPackageName(), 21000 /*flags=*/ 0, userId) != callingUid) { 21001 throw new SecurityException("Calling uid " + callingUid + " cannot set locusId" 21002 + "for package " + activity.getPackageName()); 21003 } 21004 mActivityTaskManager.setLocusId(locusId, appToken); 21005 if (mUsageStatsService != null) { 21006 mUsageStatsService.reportLocusUpdate(activity, userId, locusId, appToken); 21007 } 21008 } 21009 21010 @Override 21011 public boolean isAppFreezerSupported() { 21012 final long token = Binder.clearCallingIdentity(); 21013 21014 try { 21015 return CachedAppOptimizer.isFreezerSupported(); 21016 } finally { 21017 Binder.restoreCallingIdentity(token); 21018 } 21019 } 21020 21021 @Override 21022 public boolean isAppFreezerEnabled() { 21023 return mOomAdjuster.mCachedAppOptimizer.useFreezer(); 21024 } 21025 21026 public boolean isAppFreezerExemptInstPkg() { 21027 return mOomAdjuster.mCachedAppOptimizer.freezerExemptInstPkg(); 21028 } 21029 21030 /** 21031 * Resets the state of the {@link com.android.server.am.AppErrors} instance. 21032 * This is intended for testing within the CTS only and is protected by 21033 * android.permission.RESET_APP_ERRORS. 21034 */ 21035 @Override 21036 public void resetAppErrors() { 21037 enforceCallingPermission(Manifest.permission.RESET_APP_ERRORS, "resetAppErrors"); 21038 mAppErrors.resetState(); 21039 } 21040 21041 @Override 21042 public boolean enableAppFreezer(boolean enable) { 21043 int callerUid = Binder.getCallingUid(); 21044 21045 // Only system can toggle the freezer state 21046 if (callerUid == SYSTEM_UID || Build.IS_DEBUGGABLE) { 21047 return mOomAdjuster.mCachedAppOptimizer.enableFreezer(enable); 21048 } else { 21049 throw new SecurityException("Caller uid " + callerUid + " cannot set freezer state "); 21050 } 21051 } 21052 21053 /** 21054 * Suppress or reenable the rate limit on foreground service notification deferral. 21055 * @param enable false to suppress rate-limit policy; true to reenable it. 21056 */ 21057 @Override 21058 public boolean enableFgsNotificationRateLimit(boolean enable) { 21059 enforceCallingPermission(permission.WRITE_DEVICE_CONFIG, 21060 "enableFgsNotificationRateLimit"); 21061 synchronized (this) { 21062 return mServices.enableFgsNotificationRateLimitLocked(enable); 21063 } 21064 } 21065 21066 /** 21067 * Holds the AM lock for the specified amount of milliseconds. 21068 * Intended for use by the tests that need to imitate lock contention. 21069 * The token should be obtained by 21070 * {@link android.content.pm.PackageManager#getHoldLockToken()}. 21071 */ 21072 @Override 21073 public void holdLock(IBinder token, int durationMs) { 21074 getTestUtilityServiceLocked().verifyHoldLockToken(token); 21075 21076 synchronized (this) { 21077 SystemClock.sleep(durationMs); 21078 } 21079 } 21080 21081 static void traceBegin(long traceTag, String methodName, String subInfo) { 21082 if (Trace.isTagEnabled(traceTag)) { 21083 Trace.traceBegin(traceTag, methodName + subInfo); 21084 } 21085 } 21086 21087 /** 21088 * Gets an {@code int} argument from the given {@code index} on {@code args}, logging an error 21089 * message on {@code pw} when it cannot be parsed. 21090 * 21091 * Returns {@code int} argument or {@code invalidValue} if it could not be parsed. 21092 */ 21093 private static int getIntArg(PrintWriter pw, String[] args, int index, int invalidValue) { 21094 if (index > args.length) { 21095 pw.println("Missing argument"); 21096 return invalidValue; 21097 } 21098 String arg = args[index]; 21099 try { 21100 return Integer.parseInt(arg); 21101 } catch (Exception e) { 21102 pw.printf("Non-numeric argument at index %d: %s\n", index, arg); 21103 return invalidValue; 21104 } 21105 } 21106 21107 private void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, 21108 @MediaProjectionTokenEvent int event) { 21109 synchronized (mMediaProjectionTokenMap) { 21110 final int index = mMediaProjectionTokenMap.indexOfKey(uid); 21111 ArraySet<IBinder> tokens; 21112 if (event == MEDIA_PROJECTION_TOKEN_EVENT_CREATED) { 21113 if (index < 0) { 21114 tokens = new ArraySet(); 21115 mMediaProjectionTokenMap.put(uid, tokens); 21116 } else { 21117 tokens = mMediaProjectionTokenMap.valueAt(index); 21118 } 21119 tokens.add(projectionToken); 21120 } else if (event == MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED && index >= 0) { 21121 tokens = mMediaProjectionTokenMap.valueAt(index); 21122 tokens.remove(projectionToken); 21123 if (tokens.isEmpty()) { 21124 mMediaProjectionTokenMap.removeAt(index); 21125 } 21126 } 21127 } 21128 } 21129 21130 /** 21131 * @return {@code true} if the MediaProjectionManagerService has created a media projection 21132 * for the given {@code uid} because the user has granted the permission; 21133 * it doesn't necessarily mean it has started the projection. 21134 * 21135 * <p>It doesn't check the {@link AppOpsManager#OP_PROJECT_MEDIA}.</p> 21136 */ 21137 boolean isAllowedMediaProjectionNoOpCheck(int uid) { 21138 synchronized (mMediaProjectionTokenMap) { 21139 final int index = mMediaProjectionTokenMap.indexOfKey(uid); 21140 return index >= 0 && !mMediaProjectionTokenMap.valueAt(index).isEmpty(); 21141 } 21142 } 21143 21144 /** 21145 * Deal with binder transactions to frozen apps. 21146 * 21147 * @param debugPid The binder transaction sender 21148 * @param code The binder transaction code 21149 * @param flags The binder transaction flags 21150 * @param err The binder transaction error 21151 */ 21152 @Override 21153 public void frozenBinderTransactionDetected(int debugPid, int code, int flags, int err) { 21154 final ProcessRecord app; 21155 synchronized (mPidsSelfLocked) { 21156 app = mPidsSelfLocked.get(debugPid); 21157 } 21158 mOomAdjuster.mCachedAppOptimizer.binderError(debugPid, app, code, flags, err); 21159 } 21160 21161 @GuardedBy("this") 21162 void enqueuePendingTopAppIfNecessaryLocked() { 21163 mPendingStartActivityUids.enqueuePendingTopAppIfNecessaryLocked(this); 21164 } 21165 21166 @GuardedBy("this") 21167 void clearPendingTopAppLocked() { 21168 mPendingStartActivityUids.clear(); 21169 } 21170 } 21171