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_PROCESS_BEGIN; 54 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_PROCESS_END; 55 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_SHELL; 56 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_SYSTEM_INIT; 57 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_UI_VISIBILITY; 58 import static android.app.AppOpsManager.OP_NONE; 59 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_BACKUP; 60 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_INSTRUMENTATION; 61 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_PERSISTENT; 62 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_SYSTEM; 63 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 64 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES; 65 import static android.content.pm.PackageManager.MATCH_ALL; 66 import static android.content.pm.PackageManager.MATCH_ANY_USER; 67 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 71 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 72 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 73 import static android.content.pm.PackageManager.SIGNATURE_NO_MATCH; 74 import static android.crashrecovery.flags.Flags.refactorCrashrecovery; 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.PHONE_UID; 104 import static android.os.Process.PROC_OUT_LONG; 105 import static android.os.Process.PROC_SPACE_TERM; 106 import static android.os.Process.ROOT_UID; 107 import static android.os.Process.SCHED_FIFO; 108 import static android.os.Process.SCHED_RESET_ON_FORK; 109 import static android.os.Process.SHELL_UID; 110 import static android.os.Process.SIGNAL_USR1; 111 import static android.os.Process.SYSTEM_UID; 112 import static android.os.Process.THREAD_PRIORITY_FOREGROUND; 113 import static android.os.Process.THREAD_PRIORITY_TOP_APP_BOOST; 114 import static android.os.Process.ZYGOTE_POLICY_FLAG_BATCH_LAUNCH; 115 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY; 116 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE; 117 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS; 118 import static android.os.Process.ZYGOTE_PROCESS; 119 import static android.os.Process.getTotalMemory; 120 import static android.os.Process.isThreadInProcess; 121 import static android.os.Process.killProcess; 122 import static android.os.Process.killProcessGroup; 123 import static android.os.Process.killProcessQuiet; 124 import static android.os.Process.myPid; 125 import static android.os.Process.myUid; 126 import static android.os.Process.readProcFile; 127 import static android.os.Process.sendSignal; 128 import static android.os.Process.setThreadPriority; 129 import static android.os.Process.setThreadScheduler; 130 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES; 131 import static android.provider.Settings.Global.DEBUG_APP; 132 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER; 133 import static android.security.Flags.preventIntentRedirect; 134 import static android.security.Flags.preventIntentRedirectCollectNestedKeysOnServerIfNotCollected; 135 import static android.security.Flags.preventIntentRedirectShowToastIfNestedKeysNotCollectedRW; 136 import static android.security.Flags.preventIntentRedirectThrowExceptionIfNestedKeysNotCollected; 137 import static android.util.FeatureFlagUtils.SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS; 138 import static android.view.Display.INVALID_DISPLAY; 139 140 import static com.android.internal.util.FrameworkStatsLog.EXTRA_INTENT_KEYS_COLLECTED_ON_SERVER; 141 import static com.android.internal.util.FrameworkStatsLog.INTENT_CREATOR_TOKEN_ADDED; 142 import static com.android.internal.util.FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__NEW_MUTABLE_IMPLICIT_PENDING_INTENT_RETRIEVED; 143 import static com.android.sdksandbox.flags.Flags.sdkSandboxInstrumentationInfo; 144 import static com.android.server.am.ActiveServices.FGS_SAW_RESTRICTIONS; 145 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL; 146 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALLOWLISTS; 147 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK; 148 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP; 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_CLEANUP; 158 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU; 159 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; 160 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK; 161 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ; 162 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER; 163 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES; 164 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE; 165 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS; 166 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 167 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 168 import static com.android.server.am.MemoryStatUtil.hasMemcg; 169 import static com.android.server.am.ProcessList.ProcStartHandler; 170 import static com.android.server.flags.Flags.disableSystemCompaction; 171 import static com.android.server.net.NetworkPolicyManagerInternal.updateBlockedReasonsWithProcState; 172 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 173 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND; 174 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND; 175 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP; 176 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH; 177 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION; 178 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK; 179 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH; 180 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD; 181 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD; 182 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD; 183 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD; 184 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD; 185 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD; 186 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD; 187 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD; 188 import static com.android.server.wm.ActivityTaskManagerService.DUMP_TOP_RESUMED_ACTIVITY; 189 import static com.android.server.wm.ActivityTaskManagerService.DUMP_VISIBLE_ACTIVITIES; 190 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE; 191 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString; 192 import static com.android.systemui.shared.Flags.enableHomeDelay; 193 194 import android.Manifest; 195 import android.Manifest.permission; 196 import android.annotation.EnforcePermission; 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.SpecialUsers.CanBeALL; 203 import android.annotation.UserIdInt; 204 import android.app.Activity; 205 import android.app.ActivityClient; 206 import android.app.ActivityManager; 207 import android.app.ActivityManager.ForegroundServiceApiType; 208 import android.app.ActivityManager.PendingIntentInfo; 209 import android.app.ActivityManager.ProcessCapability; 210 import android.app.ActivityManager.RestrictionLevel; 211 import android.app.ActivityManager.RunningTaskInfo; 212 import android.app.ActivityManager.UidFrozenStateChangedCallback.UidFrozenState; 213 import android.app.ActivityManagerInternal; 214 import android.app.ActivityManagerInternal.BindServiceEventListener; 215 import android.app.ActivityManagerInternal.BroadcastEventListener; 216 import android.app.ActivityManagerInternal.ForegroundServiceStateListener; 217 import android.app.ActivityManagerInternal.MediaProjectionTokenEvent; 218 import android.app.ActivityManagerInternal.OomAdjReason; 219 import android.app.ActivityTaskManager.RootTaskInfo; 220 import android.app.ActivityThread; 221 import android.app.AnrController; 222 import android.app.AppGlobals; 223 import android.app.AppOpsManager; 224 import android.app.AppOpsManager.AttributionFlags; 225 import android.app.AppOpsManagerInternal.CheckOpsDelegate; 226 import android.app.ApplicationErrorReport; 227 import android.app.ApplicationExitInfo; 228 import android.app.ApplicationStartInfo; 229 import android.app.ApplicationThreadConstants; 230 import android.app.BackgroundStartPrivileges; 231 import android.app.BroadcastOptions; 232 import android.app.ContentProviderHolder; 233 import android.app.ForegroundServiceDelegationOptions; 234 import android.app.IActivityController; 235 import android.app.IActivityManager; 236 import android.app.IApplicationStartInfoCompleteListener; 237 import android.app.IApplicationThread; 238 import android.app.IForegroundServiceObserver; 239 import android.app.IInstrumentationWatcher; 240 import android.app.INotificationManager; 241 import android.app.IProcessObserver; 242 import android.app.IServiceConnection; 243 import android.app.IStopUserCallback; 244 import android.app.ITaskStackListener; 245 import android.app.IUiAutomationConnection; 246 import android.app.IUidFrozenStateChangedCallback; 247 import android.app.IUidObserver; 248 import android.app.IUnsafeIntentStrictModeCallback; 249 import android.app.IUserSwitchObserver; 250 import android.app.Instrumentation; 251 import android.app.Notification; 252 import android.app.NotificationManager; 253 import android.app.PendingIntent; 254 import android.app.PendingIntentStats; 255 import android.app.ProcessMemoryState; 256 import android.app.ProfilerInfo; 257 import android.app.ServiceStartNotAllowedException; 258 import android.app.WaitResult; 259 import android.app.assist.ActivityId; 260 import android.app.backup.BackupAnnotations.BackupDestination; 261 import android.app.backup.BackupManagerInternal; 262 import android.app.compat.CompatChanges; 263 import android.app.job.JobParameters; 264 import android.app.usage.UsageEvents; 265 import android.app.usage.UsageEvents.Event; 266 import android.app.usage.UsageStatsManager; 267 import android.app.usage.UsageStatsManagerInternal; 268 import android.appwidget.AppWidgetManagerInternal; 269 import android.content.AttributionSource; 270 import android.content.AutofillOptions; 271 import android.content.BroadcastReceiver; 272 import android.content.ClipData; 273 import android.content.ComponentCallbacks2; 274 import android.content.ComponentName; 275 import android.content.ContentCaptureOptions; 276 import android.content.ContentProvider; 277 import android.content.ContentResolver; 278 import android.content.Context; 279 import android.content.Context.BindServiceFlags; 280 import android.content.IIntentReceiver; 281 import android.content.IIntentSender; 282 import android.content.Intent; 283 import android.content.IntentFilter; 284 import android.content.LocusId; 285 import android.content.ServiceConnection; 286 import android.content.pm.ActivityInfo; 287 import android.content.pm.ActivityPresentationInfo; 288 import android.content.pm.ApplicationInfo; 289 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy; 290 import android.content.pm.IPackageDataObserver; 291 import android.content.pm.IPackageManager; 292 import android.content.pm.IncrementalStatesInfo; 293 import android.content.pm.InstrumentationInfo; 294 import android.content.pm.PackageInfo; 295 import android.content.pm.PackageManager; 296 import android.content.pm.PackageManager.NameNotFoundException; 297 import android.content.pm.PackageManagerInternal; 298 import android.content.pm.ParceledListSlice; 299 import android.content.pm.PermissionInfo; 300 import android.content.pm.ProcessInfo; 301 import android.content.pm.ProviderInfo; 302 import android.content.pm.ProviderInfoList; 303 import android.content.pm.ResolveInfo; 304 import android.content.pm.ServiceInfo; 305 import android.content.pm.SharedLibraryInfo; 306 import android.content.pm.SystemFeaturesCache; 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.Configuration; 312 import android.content.res.Resources; 313 import android.database.ContentObserver; 314 import android.graphics.Rect; 315 import android.hardware.display.DisplayManager; 316 import android.hardware.display.DisplayManagerInternal; 317 import android.net.Uri; 318 import android.os.AppZygote; 319 import android.os.BatteryStats; 320 import android.os.Binder; 321 import android.os.BinderProxy; 322 import android.os.BugreportParams; 323 import android.os.Build; 324 import android.os.Bundle; 325 import android.os.Debug; 326 import android.os.DropBoxManager; 327 import android.os.FactoryTest; 328 import android.os.FileUtils; 329 import android.os.Handler; 330 import android.os.IBinder; 331 import android.os.IDeviceIdentifiersPolicyService; 332 import android.os.IPermissionController; 333 import android.os.IProcessInfoService; 334 import android.os.IProgressListener; 335 import android.os.InputConstants; 336 import android.os.Looper; 337 import android.os.Message; 338 import android.os.Parcel; 339 import android.os.ParcelFileDescriptor; 340 import android.os.PowerExemptionManager; 341 import android.os.PowerExemptionManager.ReasonCode; 342 import android.os.PowerExemptionManager.TempAllowListType; 343 import android.os.PowerManager; 344 import android.os.PowerManager.ServiceType; 345 import android.os.PowerManagerInternal; 346 import android.os.Process; 347 import android.os.ProfilingServiceHelper; 348 import android.os.ProfilingTrigger; 349 import android.os.RemoteCallback; 350 import android.os.RemoteCallbackList; 351 import android.os.RemoteException; 352 import android.os.ResultReceiver; 353 import android.os.ServiceManager; 354 import android.os.SharedMemory; 355 import android.os.ShellCallback; 356 import android.os.StrictMode; 357 import android.os.SystemClock; 358 import android.os.SystemProperties; 359 import android.os.Trace; 360 import android.os.TransactionTooLargeException; 361 import android.os.UserHandle; 362 import android.os.UserManager; 363 import android.os.WorkSource; 364 import android.os.incremental.IIncrementalService; 365 import android.os.incremental.IncrementalManager; 366 import android.os.incremental.IncrementalMetrics; 367 import android.os.instrumentation.IOffsetCallback; 368 import android.os.instrumentation.MethodDescriptor; 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.system.Os; 375 import android.system.OsConstants; 376 import android.text.TextUtils; 377 import android.util.ArrayMap; 378 import android.util.ArraySet; 379 import android.util.EventLog; 380 import android.util.FeatureFlagUtils; 381 import android.util.IndentingPrintWriter; 382 import android.util.IntArray; 383 import android.util.Log; 384 import android.util.MathUtils; 385 import android.util.Pair; 386 import android.util.Slog; 387 import android.util.SparseArray; 388 import android.util.SparseIntArray; 389 import android.util.StatsEvent; 390 import android.util.TimeUtils; 391 import android.util.proto.ProtoOutputStream; 392 import android.util.proto.ProtoUtils; 393 import android.view.Display; 394 import android.view.Gravity; 395 import android.view.LayoutInflater; 396 import android.view.View; 397 import android.view.WindowManager; 398 import android.view.autofill.AutofillManagerInternal; 399 import android.widget.Toast; 400 401 import com.android.internal.annotations.CompositeRWLock; 402 import com.android.internal.annotations.GuardedBy; 403 import com.android.internal.annotations.VisibleForTesting; 404 import com.android.internal.app.IAppOpsActiveCallback; 405 import com.android.internal.app.IAppOpsCallback; 406 import com.android.internal.app.IAppOpsService; 407 import com.android.internal.app.ProcessMap; 408 import com.android.internal.app.SystemUserHomeActivity; 409 import com.android.internal.app.procstats.ProcessState; 410 import com.android.internal.app.procstats.ProcessStats; 411 import com.android.internal.content.InstallLocationUtils; 412 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 413 import com.android.internal.notification.SystemNotificationChannels; 414 import com.android.internal.os.ApplicationSharedMemory; 415 import com.android.internal.os.BackgroundThread; 416 import com.android.internal.os.BinderCallHeavyHitterWatcher.BinderCallHeavyHitterListener; 417 import com.android.internal.os.BinderCallHeavyHitterWatcher.HeavyHitterContainer; 418 import com.android.internal.os.BinderInternal; 419 import com.android.internal.os.BinderInternal.BinderProxyCountEventListener; 420 import com.android.internal.os.BinderTransactionNameResolver; 421 import com.android.internal.os.ByteTransferPipe; 422 import com.android.internal.os.IResultReceiver; 423 import com.android.internal.os.ProcessCpuTracker; 424 import com.android.internal.os.SomeArgs; 425 import com.android.internal.os.TimeoutRecord; 426 import com.android.internal.os.TransferPipe; 427 import com.android.internal.os.Zygote; 428 import com.android.internal.pm.pkg.parsing.ParsingPackageUtils; 429 import com.android.internal.policy.AttributeCache; 430 import com.android.internal.util.DumpUtils; 431 import com.android.internal.util.FastPrintWriter; 432 import com.android.internal.util.FrameworkStatsLog; 433 import com.android.internal.util.MemInfoReader; 434 import com.android.internal.util.Preconditions; 435 import com.android.internal.util.function.pooled.PooledLambda; 436 import com.android.server.AlarmManagerInternal; 437 import com.android.server.BootReceiver; 438 import com.android.server.DeviceIdleInternal; 439 import com.android.server.DisplayThread; 440 import com.android.server.IoThread; 441 import com.android.server.LocalManagerRegistry; 442 import com.android.server.LocalServices; 443 import com.android.server.LockGuard; 444 import com.android.server.PackageWatchdog; 445 import com.android.server.ServiceThread; 446 import com.android.server.SystemConfig; 447 import com.android.server.SystemService; 448 import com.android.server.SystemServiceManager; 449 import com.android.server.ThreadPriorityBooster; 450 import com.android.server.UiThread; 451 import com.android.server.Watchdog; 452 import com.android.server.am.LowMemDetector.MemFactor; 453 import com.android.server.appop.AppOpsService; 454 import com.android.server.compat.PlatformCompat; 455 import com.android.server.contentcapture.ContentCaptureManagerInternal; 456 import com.android.server.crashrecovery.CrashRecoveryAdaptor; 457 import com.android.server.crashrecovery.CrashRecoveryHelper; 458 import com.android.server.criticalevents.CriticalEventLog; 459 import com.android.server.firewall.IntentFirewall; 460 import com.android.server.graphics.fonts.FontManagerInternal; 461 import com.android.server.job.JobSchedulerInternal; 462 import com.android.server.net.NetworkManagementInternal; 463 import com.android.server.os.NativeTombstoneManager; 464 import com.android.server.pm.Installer; 465 import com.android.server.pm.SaferIntentUtils; 466 import com.android.server.pm.UserManagerInternal; 467 import com.android.server.pm.permission.PermissionManagerServiceInternal; 468 import com.android.server.pm.pkg.AndroidPackage; 469 import com.android.server.pm.pkg.SELinuxUtil; 470 import com.android.server.power.stats.BatteryStatsImpl; 471 import com.android.server.sdksandbox.SdkSandboxManagerLocal; 472 import com.android.server.stats.pull.StatsPullAtomService; 473 import com.android.server.stats.pull.StatsPullAtomServiceInternal; 474 import com.android.server.uri.GrantUri; 475 import com.android.server.uri.NeededUriGrants; 476 import com.android.server.uri.UriGrantsManagerInternal; 477 import com.android.server.utils.AnrTimer; 478 import com.android.server.utils.PriorityDump; 479 import com.android.server.utils.Slogf; 480 import com.android.server.utils.TimingsTraceAndSlog; 481 import com.android.server.vr.VrManagerInternal; 482 import com.android.server.wm.ActivityMetricsLaunchObserver; 483 import com.android.server.wm.ActivityServiceConnectionsHolder; 484 import com.android.server.wm.ActivityTaskManagerInternal; 485 import com.android.server.wm.ActivityTaskManagerService; 486 import com.android.server.wm.WindowManagerInternal; 487 import com.android.server.wm.WindowManagerService; 488 import com.android.server.wm.WindowProcessController; 489 490 import dalvik.annotation.optimization.NeverCompile; 491 import dalvik.system.VMRuntime; 492 493 import libcore.util.EmptyArray; 494 495 import java.io.File; 496 import java.io.FileDescriptor; 497 import java.io.FileNotFoundException; 498 import java.io.FileOutputStream; 499 import java.io.IOException; 500 import java.io.InputStreamReader; 501 import java.io.PrintWriter; 502 import java.lang.ref.WeakReference; 503 import java.time.Instant; 504 import java.time.ZoneId; 505 import java.time.ZonedDateTime; 506 import java.time.format.DateTimeFormatter; 507 import java.util.ArrayList; 508 import java.util.Arrays; 509 import java.util.Collections; 510 import java.util.Comparator; 511 import java.util.HashMap; 512 import java.util.HashSet; 513 import java.util.LinkedList; 514 import java.util.List; 515 import java.util.Locale; 516 import java.util.Map; 517 import java.util.NoSuchElementException; 518 import java.util.Objects; 519 import java.util.Set; 520 import java.util.UUID; 521 import java.util.concurrent.ConcurrentHashMap; 522 import java.util.concurrent.CopyOnWriteArrayList; 523 import java.util.concurrent.CountDownLatch; 524 import java.util.concurrent.Executor; 525 import java.util.concurrent.TimeUnit; 526 import java.util.concurrent.atomic.AtomicBoolean; 527 import java.util.concurrent.atomic.AtomicInteger; 528 import java.util.function.BiFunction; 529 import java.util.function.Consumer; 530 531 public class ActivityManagerService extends IActivityManager.Stub 532 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock { 533 534 private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED = 535 "persist.sys.device_provisioned"; 536 537 static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM; 538 static final String TAG_BACKUP = TAG + POSTFIX_BACKUP; 539 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 540 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION; 541 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; 542 static final String TAG_LRU = TAG + POSTFIX_LRU; 543 static final String TAG_MU = TAG + POSTFIX_MU; 544 static final String TAG_NETWORK = TAG + POSTFIX_NETWORK; 545 static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ; 546 private static final String TAG_POWER = TAG + POSTFIX_POWER; 547 static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES; 548 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 549 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 550 static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS; 551 552 // Mock "pretend we're idle now" broadcast action to the job scheduler; declared 553 // here so that while the job scheduler can depend on AMS, the other way around 554 // need not be the case. 555 public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE"; 556 557 private static final String INTENT_BUGREPORT_REQUESTED = 558 "com.android.internal.intent.action.BUGREPORT_REQUESTED"; 559 private static final String SHELL_APP_PACKAGE = "com.android.shell"; 560 561 // The flags that are set for all calls we make to the package manager. 562 public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 563 564 static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed"; 565 566 // How long we wait for a launched process to attach to the activity manager 567 // before we decide it's never going to come up for real. 568 static final int PROC_START_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 569 570 // How long we wait for a launched process to complete its app startup before we ANR. 571 static final int BIND_APPLICATION_TIMEOUT = 15 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 572 573 // How long we wait to kill an application zygote, after the last process using 574 // it has gone away. 575 static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000; 576 577 // How long we wait for a launched process to attach to the activity manager 578 // before we decide it's never going to come up for real, when the process was 579 // started with a wrapper for instrumentation (such as Valgrind) because it 580 // could take much longer than usual. 581 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 582 583 // How long we allow a receiver to run before giving up on it. 584 static final int BROADCAST_FG_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 585 static final int BROADCAST_BG_TIMEOUT = 60 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 586 587 public static final int MY_PID = myPid(); 588 589 static final String[] EMPTY_STRING_ARRAY = new String[0]; 590 591 // How many bytes to write into the dropbox log before truncating 592 static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024; 593 // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count 594 // as one line, but close enough for now. 595 static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100; 596 597 // How many seconds should the system wait before terminating the spawned logcat process. 598 static final int LOGCAT_TIMEOUT_SEC = Flags.logcatLongerTimeout() ? 15 : 10; 599 600 // Necessary ApplicationInfo flags to mark an app as persistent 601 static final int PERSISTENT_MASK = 602 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT; 603 604 // Intent sent when remote bugreport collection has been completed 605 private static final String INTENT_REMOTE_BUGREPORT_FINISHED = 606 "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED"; 607 608 public static final String DATA_FILE_PATH_HEADER = "Data File: "; 609 public static final String DATA_FILE_PATH_FOOTER = "End Data File\n"; 610 611 // If set, we will push process association information in to procstats. 612 static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true; 613 614 // The minimum memory growth threshold (in KB) for low RAM devices. 615 private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB 616 617 /** 618 * The number of binder proxies we need to have before we start dumping debug info 619 * and kill the offenders. 620 */ 621 private static final int BINDER_PROXY_HIGH_WATERMARK = 6000; 622 623 /** 624 * Low watermark that needs to be met before we consider dumping info again, 625 * after already hitting the high watermark. 626 */ 627 private static final int BINDER_PROXY_LOW_WATERMARK = 5500; 628 629 /** 630 * The number of binder proxies we need to have before we start warning. 631 */ 632 private static final int BINDER_PROXY_WARNING_WATERMARK = 5750; 633 634 // Max character limit for a notification title. If the notification title is larger than this 635 // the notification will not be legible to the user. 636 private static final int MAX_BUGREPORT_TITLE_SIZE = 100; 637 private static final int MAX_BUGREPORT_DESCRIPTION_SIZE = 150; 638 639 private static final DateTimeFormatter DROPBOX_TIME_FORMATTER = 640 DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSZ"); 641 642 OomAdjuster mOomAdjuster; 643 @GuardedBy("this") 644 ProcessStateController mProcessStateController; 645 646 static final String EXTRA_TITLE = "android.intent.extra.TITLE"; 647 static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION"; 648 static final String EXTRA_BUGREPORT_TYPE = "android.intent.extra.BUGREPORT_TYPE"; 649 static final String EXTRA_BUGREPORT_NONCE = "android.intent.extra.BUGREPORT_NONCE"; 650 static final String EXTRA_EXTRA_ATTACHMENT_URIS = 651 "android.intent.extra.EXTRA_ATTACHMENT_URIS"; 652 653 /** 654 * The maximum number of bytes that {@link #setProcessStateSummary} accepts. 655 * 656 * @see {@link android.app.ActivityManager#setProcessStateSummary(byte[])} 657 */ 658 static final int MAX_STATE_DATA_SIZE = 128; 659 660 /** All system services */ 661 SystemServiceManager mSystemServiceManager; 662 663 private Installer mInstaller; 664 665 final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter(); 666 667 @CompositeRWLock({"this", "mProcLock"}) 668 final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>(); 669 670 public final IntentFirewall mIntentFirewall; 671 672 /** 673 * The global lock for AMS, it's de-facto the ActivityManagerService object as of now. 674 */ 675 final ActivityManagerGlobalLock mGlobalLock = ActivityManagerService.this; 676 677 /** 678 * Whether or not to enable the {@link #mProcLock}. If {@code false}, the {@link #mProcLock} 679 * will be equivalent to the {@link #mGlobalLock}. 680 */ 681 private static final boolean ENABLE_PROC_LOCK = true; 682 683 private static final int DEFAULT_INTENT_CREATOR_UID = -1; 684 685 /** 686 * The lock for process management. 687 * 688 * <p> 689 * This lock is widely used in conjunction with the {@link #mGlobalLock} at present, 690 * where it'll require any of the locks to read from a data class, and both of the locks 691 * to write into that data class. 692 * 693 * For the naming convention of function suffixes: 694 * <ul> 695 * <li>-LOSP: Locked with any Of global am Service or Process lock</li> 696 * <li>-LSP: Locked with both of global am Service and Process lock</li> 697 * <li>-Locked: Locked with global am service lock alone</li> 698 * <li>-LPr: Locked with Process lock alone</li> 699 * </ul> 700 * For the simplicity, the getters/setters of the fields in data classes usually don't end with 701 * the above suffixes even if they're guarded by the locks here. 702 * </p> 703 * 704 * <p> 705 * In terms of locking order, it should be right below to the {@link #mGlobalLock}, 706 * and above everything else which used to be underneath the {@link #mGlobalLock}. 707 * As of today, the core components(services/providers/broadcasts) are still guarded by 708 * the {@link #mGlobalLock} alone, so be cautious, avoid from acquiring the {@link #mGlobalLock} 709 * while holding this lock. 710 * </p> 711 * 712 */ 713 final ActivityManagerGlobalLock mProcLock = ENABLE_PROC_LOCK 714 ? new ActivityManagerProcLock() : mGlobalLock; 715 716 // Whether we should use SCHED_FIFO for UI and RenderThreads. 717 final boolean mUseFifoUiScheduling; 718 719 /** Whether some specified important processes are allowed to use FIFO priority. */ 720 boolean mAllowSpecifiedFifoScheduling = true; 721 722 @GuardedBy("mStrictModeCallbacks") 723 private final SparseArray<IUnsafeIntentStrictModeCallback> 724 mStrictModeCallbacks = new SparseArray<>(); 725 726 // Convenient for easy iteration over the queues. Foreground is first 727 // so that dispatch of foreground broadcasts gets precedence. 728 private BroadcastQueue mBroadcastQueue; 729 730 // TODO: Add a consistent way of accessing the methods within this class. Currently, some 731 // methods require access while holding a lock, while others do not. 732 BroadcastController mBroadcastController; 733 734 TraceErrorLogger mTraceErrorLogger; 735 736 private volatile int mDeviceOwnerUid = INVALID_UID; 737 738 /** 739 * Map userId to its companion app uids. 740 */ 741 @GuardedBy("mCompanionAppUidsMap") 742 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>(); 743 744 /** 745 * The profile owner UIDs. 746 */ 747 @GuardedBy("mProfileOwnerUids") 748 private final ArraySet<Integer> mProfileOwnerUids = new ArraySet<>(); 749 750 final UserController mUserController; 751 @VisibleForTesting 752 public final PendingIntentController mPendingIntentController; 753 754 final AppErrors mAppErrors; 755 final PackageWatchdog mPackageWatchdog; 756 final CrashRecoveryHelper mCrashRecoveryHelper; 757 758 @GuardedBy("mDeliveryGroupPolicyIgnoredActions") 759 private final ArraySet<String> mDeliveryGroupPolicyIgnoredActions = new ArraySet(); 760 761 private AccessCheckDelegateHelper mAccessCheckDelegateHelper; 762 763 /** 764 * Uids of apps with current active camera sessions. Access synchronized on 765 * the IntArray instance itself, and no other locks must be acquired while that 766 * one is held. 767 */ 768 @GuardedBy("mActiveCameraUids") 769 final IntArray mActiveCameraUids = new IntArray(4); 770 771 /** 772 * Helper class which strips out priority and proto arguments then calls the dump function with 773 * the appropriate arguments. If priority arguments are omitted, function calls the legacy 774 * dump command. 775 * If priority arguments are omitted all sections are dumped, otherwise sections are dumped 776 * according to their priority. 777 */ 778 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() { 779 @Override 780 public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args, 781 boolean asProto) { 782 if (asProto) return; 783 doDump(fd, pw, new String[]{"activities"}, asProto); 784 doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto); 785 } 786 787 @Override 788 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 789 doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto); 790 } 791 792 @Override 793 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 794 doDump(fd, pw, args, asProto); 795 } 796 }; 797 798 private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster( 799 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY); 800 boostPriorityForLockedSection()801 static void boostPriorityForLockedSection() { 802 sThreadPriorityBooster.boost(); 803 } 804 resetPriorityAfterLockedSection()805 static void resetPriorityAfterLockedSection() { 806 sThreadPriorityBooster.reset(); 807 } 808 809 private static ThreadPriorityBooster sProcThreadPriorityBooster = new ThreadPriorityBooster( 810 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_PROC); 811 boostPriorityForProcLockedSection()812 static void boostPriorityForProcLockedSection() { 813 if (ENABLE_PROC_LOCK) { 814 sProcThreadPriorityBooster.boost(); 815 } else { 816 sThreadPriorityBooster.boost(); 817 } 818 } 819 resetPriorityAfterProcLockedSection()820 static void resetPriorityAfterProcLockedSection() { 821 if (ENABLE_PROC_LOCK) { 822 sProcThreadPriorityBooster.reset(); 823 } else { 824 sThreadPriorityBooster.reset(); 825 } 826 } 827 828 /** 829 * Process management. 830 */ 831 final ProcessList mProcessList; 832 833 /** 834 * The list of phantom processes. 835 * @see PhantomProcessRecord 836 */ 837 final PhantomProcessList mPhantomProcessList; 838 839 /** 840 * Tracking long-term execution of processes to look for abuse and other 841 * bad app behavior. 842 */ 843 final ProcessStatsService mProcessStats; 844 845 /** 846 * Non-persistent appId allowlist for background restrictions 847 */ 848 @CompositeRWLock({"this", "mProcLock"}) 849 private int[] mBackgroundAppIdAllowlist = new int[] { 850 BLUETOOTH_UID 851 }; 852 853 /** 854 * When an app has restrictions on the other apps that can have associations with it, 855 * it appears here with a set of the allowed apps and also track debuggability of the app. 856 */ 857 @GuardedBy("this") 858 private ArrayMap<String, PackageAssociationInfo> mAllowedAssociations; 859 860 @GuardedBy("this") 861 final ComponentAliasResolver mComponentAliasResolver; 862 863 final FileDescriptor mApplicationSharedMemoryReadOnlyFd; 864 865 private static final long HOME_LAUNCH_TIMEOUT_MS = 15000; 866 private final AtomicBoolean mHasHomeDelay = new AtomicBoolean(false); 867 868 /** 869 * Tracks all users with computed color resources by ThemeOverlaycvontroller 870 */ 871 @GuardedBy("this") 872 private final Set<Integer> mThemeOverlayReadyUsers = new HashSet<>(); 873 874 /** 875 * Tracks association information for a particular package along with debuggability. 876 * <p> Associations for a package A are allowed to package B if B is part of the 877 * allowed associations for A or if A is debuggable. 878 */ 879 private final class PackageAssociationInfo { 880 private final String mSourcePackage; 881 private final ArraySet<String> mAllowedPackageAssociations; 882 private boolean mIsDebuggable; 883 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)884 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, 885 boolean isDebuggable) { 886 mSourcePackage = sourcePackage; 887 mAllowedPackageAssociations = allowedPackages; 888 mIsDebuggable = isDebuggable; 889 } 890 891 /** 892 * Returns true if {@code mSourcePackage} is allowed association with 893 * {@code targetPackage}. 894 */ isPackageAssociationAllowed(String targetPackage)895 boolean isPackageAssociationAllowed(String targetPackage) { 896 return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage); 897 } 898 isDebuggable()899 boolean isDebuggable() { 900 return mIsDebuggable; 901 } 902 setDebuggable(boolean isDebuggable)903 void setDebuggable(boolean isDebuggable) { 904 mIsDebuggable = isDebuggable; 905 } 906 getAllowedPackageAssociations()907 ArraySet<String> getAllowedPackageAssociations() { 908 return mAllowedPackageAssociations; 909 } 910 } 911 912 /** 913 * These are the currently running processes for which we have a ProcessInfo. 914 * Note: needs to be static since the permission checking call chain is static. This 915 * all probably should be refactored into a separate permission checking object. 916 */ 917 @GuardedBy("sActiveProcessInfoSelfLocked") 918 static final SparseArray<ProcessInfo> sActiveProcessInfoSelfLocked = new SparseArray<>(); 919 920 /** 921 * All of the processes we currently have running organized by pid. 922 * The keys are the pid running the application. 923 * 924 * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock! 925 */ 926 final PidMap mPidsSelfLocked = new PidMap(); 927 static final class PidMap { 928 private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>(); 929 get(int pid)930 ProcessRecord get(int pid) { 931 return mPidMap.get(pid); 932 } 933 size()934 int size() { 935 return mPidMap.size(); 936 } 937 valueAt(int index)938 ProcessRecord valueAt(int index) { 939 return mPidMap.valueAt(index); 940 } 941 keyAt(int index)942 int keyAt(int index) { 943 return mPidMap.keyAt(index); 944 } 945 indexOfKey(int key)946 int indexOfKey(int key) { 947 return mPidMap.indexOfKey(key); 948 } 949 doAddInternal(int pid, ProcessRecord app)950 void doAddInternal(int pid, ProcessRecord app) { 951 mPidMap.put(pid, app); 952 } 953 doRemoveInternal(int pid, ProcessRecord app)954 boolean doRemoveInternal(int pid, ProcessRecord app) { 955 final ProcessRecord existingApp = mPidMap.get(pid); 956 if (existingApp != null && existingApp.getStartSeq() == app.getStartSeq()) { 957 mPidMap.remove(pid); 958 return true; 959 } 960 return false; 961 } 962 } 963 964 private final PendingStartActivityUids mPendingStartActivityUids; 965 966 /** 967 * Puts the process record in the map. 968 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 969 * method. 970 */ 971 @GuardedBy("this") addPidLocked(ProcessRecord app)972 void addPidLocked(ProcessRecord app) { 973 final int pid = app.getPid(); 974 synchronized (mPidsSelfLocked) { 975 mPidsSelfLocked.doAddInternal(pid, app); 976 } 977 synchronized (sActiveProcessInfoSelfLocked) { 978 if (app.processInfo != null) { 979 sActiveProcessInfoSelfLocked.put(pid, app.processInfo); 980 } else { 981 sActiveProcessInfoSelfLocked.remove(pid); 982 } 983 } 984 mAtmInternal.onProcessMapped(pid, app.getWindowProcessController()); 985 } 986 987 /** 988 * Removes the process record from the map. 989 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 990 * method. 991 */ 992 @GuardedBy("this") removePidLocked(int pid, ProcessRecord app)993 boolean removePidLocked(int pid, ProcessRecord app) { 994 final boolean removed; 995 synchronized (mPidsSelfLocked) { 996 removed = mPidsSelfLocked.doRemoveInternal(pid, app); 997 } 998 if (removed) { 999 synchronized (sActiveProcessInfoSelfLocked) { 1000 sActiveProcessInfoSelfLocked.remove(pid); 1001 } 1002 mAtmInternal.onProcessUnMapped(pid); 1003 } 1004 return removed; 1005 } 1006 1007 /** 1008 * All of the processes that have been forced to be important. The key 1009 * is the pid of the caller who requested it (we hold a death 1010 * link on it). 1011 */ 1012 abstract class ImportanceToken implements IBinder.DeathRecipient { 1013 final int pid; 1014 final IBinder token; 1015 final String reason; 1016 ImportanceToken(int _pid, IBinder _token, String _reason)1017 ImportanceToken(int _pid, IBinder _token, String _reason) { 1018 pid = _pid; 1019 token = _token; 1020 reason = _reason; 1021 } 1022 1023 @Override toString()1024 public String toString() { 1025 return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this)) 1026 + " " + reason + " " + pid + " " + token + " }"; 1027 } 1028 dumpDebug(ProtoOutputStream proto, long fieldId)1029 void dumpDebug(ProtoOutputStream proto, long fieldId) { 1030 final long pToken = proto.start(fieldId); 1031 proto.write(ImportanceTokenProto.PID, pid); 1032 if (token != null) { 1033 proto.write(ImportanceTokenProto.TOKEN, token.toString()); 1034 } 1035 proto.write(ImportanceTokenProto.REASON, reason); 1036 proto.end(pToken); 1037 } 1038 } 1039 @GuardedBy("this") 1040 final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>(); 1041 1042 /** The processes that are allowed to use SCHED_FIFO prorioty. */ 1043 @GuardedBy("mProcLock") 1044 final ArrayList<ProcessRecord> mSpecifiedFifoProcesses = new ArrayList<>(); 1045 1046 /** 1047 * List of records for processes that someone had tried to start before the 1048 * system was ready. We don't start them at that point, but ensure they 1049 * are started by the time booting is complete. 1050 */ 1051 @GuardedBy("this") 1052 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 1053 1054 /** 1055 * List of persistent applications that are in the process 1056 * of being started. 1057 */ 1058 @GuardedBy("this") 1059 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 1060 1061 private final ActivityMetricsLaunchObserver mActivityLaunchObserver = 1062 new ActivityMetricsLaunchObserver() { 1063 1064 @Override 1065 public void onIntentStarted(@NonNull Intent intent, long timestampNanos) { 1066 synchronized (this) { 1067 mProcessList.getAppStartInfoTracker() 1068 .onActivityIntentStarted(intent, timestampNanos); 1069 } 1070 } 1071 1072 @Override 1073 public void onIntentFailed(long id) { 1074 mProcessList.getAppStartInfoTracker().onActivityIntentFailed(id); 1075 } 1076 1077 @Override 1078 public void onActivityLaunched(long id, ComponentName name, int temperature, int userId) { 1079 mAppProfiler.onActivityLaunched(); 1080 synchronized (ActivityManagerService.this) { 1081 ProcessRecord record = null; 1082 try { 1083 record = getProcessRecordLocked(name.getPackageName(), mContext 1084 .getPackageManager().getPackageUidAsUser(name.getPackageName(), 0, 1085 userId)); 1086 } catch (NameNotFoundException nnfe) { 1087 // Ignore, record will be lost. 1088 } 1089 mProcessList.getAppStartInfoTracker().onActivityLaunched(id, name, temperature, 1090 record); 1091 } 1092 } 1093 1094 @Override 1095 public void onActivityLaunchCancelled(long id) { 1096 mProcessList.getAppStartInfoTracker().onActivityLaunchCancelled(id); 1097 } 1098 1099 @Override 1100 public void onActivityLaunchFinished(long id, ComponentName name, long timestampNanos, 1101 int launchMode) { 1102 mProcessList.getAppStartInfoTracker().onActivityLaunchFinished(id, name, 1103 timestampNanos, launchMode); 1104 } 1105 1106 @Override 1107 public void onReportFullyDrawn(long id, long timestampNanos) { 1108 ApplicationStartInfo startInfo = mProcessList.getAppStartInfoTracker() 1109 .onActivityReportFullyDrawn(id, timestampNanos); 1110 1111 if (android.os.profiling.Flags.systemTriggeredProfilingNew() 1112 && startInfo != null 1113 && startInfo.getStartType() == ApplicationStartInfo.START_TYPE_COLD 1114 && startInfo.getPackageName() != null) { 1115 ProfilingServiceHelper.getInstance().onProfilingTriggerOccurred( 1116 startInfo.getRealUid(), 1117 startInfo.getPackageName(), 1118 ProfilingTrigger.TRIGGER_TYPE_APP_FULLY_DRAWN); 1119 } 1120 } 1121 }; 1122 1123 private volatile boolean mBinderTransactionTrackingEnabled = false; 1124 1125 /** 1126 * Fingerprints (hashCode()) of stack traces that we've 1127 * already logged DropBox entries for. Guarded by itself. If 1128 * something (rogue user app) forces this over 1129 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 1130 */ 1131 @GuardedBy("mAlreadyLoggedViolatedStacks") 1132 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 1133 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 1134 1135 final ActiveServices mServices; 1136 1137 final static class Association { 1138 final int mSourceUid; 1139 final String mSourceProcess; 1140 final int mTargetUid; 1141 final ComponentName mTargetComponent; 1142 final String mTargetProcess; 1143 1144 int mCount; 1145 long mTime; 1146 1147 int mNesting; 1148 long mStartTime; 1149 1150 // states of the source process when the bind occurred. 1151 int mLastState = ActivityManager.MAX_PROCESS_STATE + 1; 1152 long mLastStateUptime; 1153 long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE 1154 - ActivityManager.MIN_PROCESS_STATE+1]; 1155 Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1156 Association(int sourceUid, String sourceProcess, int targetUid, 1157 ComponentName targetComponent, String targetProcess) { 1158 mSourceUid = sourceUid; 1159 mSourceProcess = sourceProcess; 1160 mTargetUid = targetUid; 1161 mTargetComponent = targetComponent; 1162 mTargetProcess = targetProcess; 1163 } 1164 } 1165 1166 /** 1167 * When service association tracking is enabled, this is all of the associations we 1168 * have seen. Mapping is target uid -> target component -> source uid -> source process name 1169 * -> association data. 1170 */ 1171 @GuardedBy("this") 1172 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>> 1173 mAssociations = new SparseArray<>(); 1174 boolean mTrackingAssociations; 1175 1176 /** 1177 * Backup/restore process management 1178 */ 1179 @GuardedBy("this") 1180 final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>(); 1181 1182 final ContentProviderHelper mCpHelper; 1183 1184 CoreSettingsObserver mCoreSettingsObserver; 1185 1186 /** 1187 * All information we have collected about the runtime performance of 1188 * any user id that can impact battery performance. 1189 */ 1190 final BatteryStatsService mBatteryStatsService; 1191 1192 StatsPullAtomServiceInternal mStatsPullAtomServiceInternal; 1193 1194 /** 1195 * Information about component usage 1196 */ 1197 volatile UsageStatsManagerInternal mUsageStatsService; 1198 1199 /** 1200 * Access to DeviceIdleController service. 1201 */ 1202 DeviceIdleInternal mLocalDeviceIdleController; 1203 1204 /** 1205 * Power-save allowlisted app-ids (not including except-idle-allowlisted ones). 1206 */ 1207 @CompositeRWLock({"this", "mProcLock"}) 1208 int[] mDeviceIdleAllowlist = new int[0]; 1209 1210 /** 1211 * Power-save allowlisted app-ids (including except-idle-allowlisted ones). 1212 */ 1213 @CompositeRWLock({"this", "mProcLock"}) 1214 int[] mDeviceIdleExceptIdleAllowlist = new int[0]; 1215 1216 /** 1217 * Set of app ids that are temporarily allowed to escape bg check due to high-pri message 1218 */ 1219 @CompositeRWLock({"this", "mProcLock"}) 1220 int[] mDeviceIdleTempAllowlist = new int[0]; 1221 1222 static final class PendingTempAllowlist { 1223 final int targetUid; 1224 final long duration; 1225 final String tag; 1226 final int type; 1227 final @ReasonCode int reasonCode; 1228 final int callingUid; 1229 PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, int type, int callingUid)1230 PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, 1231 int type, int callingUid) { 1232 this.targetUid = targetUid; 1233 this.duration = duration; 1234 this.tag = tag; 1235 this.type = type; 1236 this.reasonCode = reasonCode; 1237 this.callingUid = callingUid; 1238 } 1239 dumpDebug(ProtoOutputStream proto, long fieldId)1240 void dumpDebug(ProtoOutputStream proto, long fieldId) { 1241 final long token = proto.start(fieldId); 1242 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID, 1243 targetUid); 1244 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS, 1245 duration); 1246 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag); 1247 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TYPE, type); 1248 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.REASON_CODE, 1249 reasonCode); 1250 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.CALLING_UID, 1251 callingUid); 1252 proto.end(token); 1253 } 1254 } 1255 1256 @CompositeRWLock({"this", "mProcLock"}) 1257 final PendingTempAllowlists mPendingTempAllowlist = new PendingTempAllowlists(this); 1258 1259 public static final class FgsTempAllowListItem { 1260 final long mDuration; 1261 final @PowerExemptionManager.ReasonCode int mReasonCode; 1262 final String mReason; 1263 final int mCallingUid; 1264 FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, String reason, int callingUid)1265 FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, 1266 String reason, int callingUid) { 1267 mDuration = duration; 1268 mReasonCode = reasonCode; 1269 mReason = reason; 1270 mCallingUid = callingUid; 1271 } 1272 dump(PrintWriter pw)1273 void dump(PrintWriter pw) { 1274 pw.print(" duration=" + mDuration + 1275 " callingUid=" + UserHandle.formatUid(mCallingUid) + 1276 " reasonCode=" + PowerExemptionManager.reasonCodeToString(mReasonCode) + 1277 " reason=" + mReason); 1278 } 1279 } 1280 1281 /** 1282 * The temp-allowlist that is allowed to start FGS from background. 1283 */ 1284 @CompositeRWLock({"this", "mProcLock"}) 1285 final FgsTempAllowList<FgsTempAllowListItem> mFgsStartTempAllowList = 1286 new FgsTempAllowList(); 1287 1288 static final FgsTempAllowListItem FAKE_TEMP_ALLOW_LIST_ITEM = new FgsTempAllowListItem( 1289 Long.MAX_VALUE, REASON_SYSTEM_ALLOW_LISTED, "", INVALID_UID); 1290 1291 /* 1292 * List of uids that are allowed to have while-in-use permission when FGS is started from 1293 * background. 1294 */ 1295 private final FgsTempAllowList<String> mFgsWhileInUseTempAllowList = 1296 new FgsTempAllowList(); 1297 1298 /** 1299 * Information about and control over application operations 1300 */ 1301 final AppOpsService mAppOpsService; 1302 private AppOpsManager mAppOpsManager; 1303 1304 /** 1305 * List of initialization arguments to pass to all processes when binding applications to them. 1306 * For example, references to the commonly used services. 1307 */ 1308 ArrayMap<String, IBinder> mAppBindArgs; 1309 ArrayMap<String, IBinder> mIsolatedAppBindArgs; 1310 1311 volatile boolean mProcessesReady = false; 1312 volatile boolean mSystemReady = false; 1313 volatile boolean mOnBattery = false; 1314 final int mFactoryTest; 1315 volatile boolean mBooting = false; 1316 1317 @GuardedBy("this") boolean mCallFinishBooting = false; 1318 @GuardedBy("this") boolean mBootAnimationComplete = false; 1319 1320 final Context mContext; 1321 1322 /** 1323 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can 1324 * change at runtime. Use mContext for non-UI purposes. 1325 */ 1326 final Context mUiContext; 1327 1328 /** 1329 * Last time (in uptime) at which we checked for power usage. 1330 */ 1331 @GuardedBy("mProcLock") 1332 long mLastPowerCheckUptime; 1333 1334 /** 1335 * For some direct access we need to power manager. 1336 */ 1337 PowerManagerInternal mLocalPowerManager; 1338 1339 /** 1340 * State of external calls telling us if the device is awake or asleep. 1341 */ 1342 AtomicInteger mWakefulness = new AtomicInteger(PowerManagerInternal.WAKEFULNESS_AWAKE); 1343 1344 /** 1345 * The uptime of the last time we performed idle maintenance. 1346 */ 1347 @GuardedBy("mProcLock") 1348 long mLastIdleTime = SystemClock.uptimeMillis(); 1349 1350 /** 1351 * For reporting to battery stats the current top application. 1352 * 1353 * <p>It has its own lock to avoid from the need of double locking if using the global 1354 * ActivityManagerService lock and proc lock to guard it.</p> 1355 */ 1356 @GuardedBy("mCurResumedAppLock") 1357 private String mCurResumedPackage = null; 1358 1359 @GuardedBy("mCurResumedAppLock") 1360 private int mCurResumedUid = -1; 1361 1362 /** 1363 * Dedicated lock for {@link #mCurResumedPackage} and {@link #mCurResumedUid}. 1364 */ 1365 private final Object mCurResumedAppLock = new Object(); 1366 1367 /** 1368 * For reporting to battery stats the apps currently running foreground 1369 * service. The ProcessMap is package/uid tuples; each of these contain 1370 * an array of the currently foreground processes. 1371 */ 1372 @GuardedBy("this") 1373 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1374 = new ProcessMap<ArrayList<ProcessRecord>>(); 1375 1376 /** 1377 * The list of foreground service state change listeners. 1378 */ 1379 @GuardedBy("this") 1380 final ArrayList<ForegroundServiceStateListener> mForegroundServiceStateListeners = 1381 new ArrayList<>(); 1382 1383 /** 1384 * The list of broadcast event listeners. 1385 */ 1386 final CopyOnWriteArrayList<BroadcastEventListener> mBroadcastEventListeners = 1387 new CopyOnWriteArrayList<>(); 1388 1389 /** 1390 * The list of bind service event listeners. 1391 */ 1392 final CopyOnWriteArrayList<BindServiceEventListener> mBindServiceEventListeners = 1393 new CopyOnWriteArrayList<>(); 1394 1395 /** 1396 * Set if the systemServer made a call to enterSafeMode. 1397 */ 1398 @GuardedBy("this") 1399 boolean mSafeMode; 1400 1401 @GuardedBy("this") 1402 private String mDebugApp = null; 1403 1404 @GuardedBy("this") 1405 private boolean mWaitForDebugger = false; 1406 1407 @GuardedBy("this") 1408 private boolean mSuspendUponWait = false; 1409 1410 @GuardedBy("this") 1411 private boolean mDebugTransient = false; 1412 1413 @GuardedBy("this") 1414 private String mOrigDebugApp = null; 1415 1416 @GuardedBy("this") 1417 private boolean mOrigWaitForDebugger = false; 1418 1419 @GuardedBy("this") 1420 boolean mAlwaysFinishActivities = false; 1421 1422 @GuardedBy("mProcLock") 1423 private String mTrackAllocationApp = null; 1424 1425 @GuardedBy("this") 1426 String mNativeDebuggingApp = null; 1427 1428 final Injector mInjector; 1429 1430 static final class ProcessChangeItem { 1431 static final int CHANGE_ACTIVITIES = 1<<0; 1432 static final int CHANGE_FOREGROUND_SERVICES = 1<<1; 1433 int changes; 1434 int uid; 1435 int pid; 1436 int processState; 1437 boolean foregroundActivities; 1438 int foregroundServiceTypes; 1439 } 1440 1441 @GuardedBy("mOomAdjObserverLock") 1442 OomAdjObserver mCurOomAdjObserver; 1443 1444 @GuardedBy("mOomAdjObserverLock") 1445 int mCurOomAdjUid; 1446 1447 /** 1448 * Dedicated lock for {@link #mCurOomAdjObserver} and {@link #mCurOomAdjUid}. 1449 */ 1450 final Object mOomAdjObserverLock = new Object(); 1451 1452 interface OomAdjObserver { onOomAdjMessage(String msg)1453 void onOomAdjMessage(String msg); 1454 } 1455 1456 final AnrHelper mAnrHelper = new AnrHelper(this); 1457 1458 /** Set to true after the system has finished booting. */ 1459 volatile boolean mBooted = false; 1460 1461 /** 1462 * Current boot phase. 1463 */ 1464 int mBootPhase; 1465 1466 /** 1467 * The time stamp that all apps have received BOOT_COMPLETED. 1468 */ 1469 volatile long mBootCompletedTimestamp; 1470 1471 @GuardedBy("this") 1472 boolean mDeterministicUidIdle = false; 1473 1474 @VisibleForTesting 1475 public WindowManagerService mWindowManager; 1476 WindowManagerInternal mWmInternal; 1477 @VisibleForTesting 1478 public ActivityTaskManagerService mActivityTaskManager; 1479 @VisibleForTesting 1480 public ActivityTaskManagerInternal mAtmInternal; 1481 UriGrantsManagerInternal mUgmInternal; 1482 @VisibleForTesting 1483 public final ActivityManagerInternal mInternal; 1484 final ActivityThread mSystemThread; 1485 1486 final UidObserverController mUidObserverController; 1487 private volatile IUidObserver mNetworkPolicyUidObserver; 1488 1489 @GuardedBy("mUidNetworkBlockedReasons") 1490 private final SparseIntArray mUidNetworkBlockedReasons = new SparseIntArray(); 1491 1492 final AppRestrictionController mAppRestrictionController; 1493 1494 /** 1495 * The collection of the MediaProjection tokens per UID, for the apps that are allowed to 1496 * start FGS with the type "mediaProjection"; this permission is granted via the request over 1497 * the call to {@link android.media.project.MediaProjectionManager#createScreenCaptureIntent()}. 1498 * 1499 * <p>Note, the "token" here is actually an instance of 1500 * {@link android.media.projection.IMediaProjection}.</p> 1501 */ 1502 @GuardedBy("mMediaProjectionTokenMap") 1503 private final SparseArray<ArraySet<IBinder>> mMediaProjectionTokenMap = new SparseArray(); 1504 1505 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1506 final ProcessRecord mApp; 1507 final int mPid; 1508 final IApplicationThread mAppThread; 1509 AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1510 AppDeathRecipient(ProcessRecord app, int pid, 1511 IApplicationThread thread) { 1512 if (DEBUG_ALL) Slog.v( 1513 TAG, "New death recipient " + this 1514 + " for thread " + thread.asBinder()); 1515 mApp = app; 1516 mPid = pid; 1517 mAppThread = thread; 1518 } 1519 1520 @Override binderDied()1521 public void binderDied() { 1522 if (DEBUG_ALL) Slog.v( 1523 TAG, "Death received in " + this 1524 + " for thread " + mAppThread.asBinder()); 1525 synchronized(ActivityManagerService.this) { 1526 appDiedLocked(mApp, mPid, mAppThread, true, null); 1527 } 1528 } 1529 } 1530 1531 static final int SHOW_ERROR_UI_MSG = 1; 1532 static final int SHOW_NOT_RESPONDING_UI_MSG = 2; 1533 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1534 static final int WAIT_FOR_DEBUGGER_UI_MSG = 6; 1535 static final int SERVICE_TIMEOUT_MSG = 12; 1536 static final int UPDATE_TIME_ZONE = 13; 1537 static final int PROC_START_TIMEOUT_MSG = 20; 1538 static final int KILL_APPLICATION_MSG = 22; 1539 static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26; 1540 static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27; 1541 static final int CLEAR_DNS_CACHE_MSG = 28; 1542 static final int UPDATE_HTTP_PROXY_MSG = 29; 1543 static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31; 1544 static final int DISPATCH_PROCESS_DIED_UI_MSG = 32; 1545 static final int REPORT_MEM_USAGE_MSG = 33; 1546 static final int UPDATE_TIME_PREFERENCE_MSG = 41; 1547 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49; 1548 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50; 1549 static final int ABORT_DUMPHEAP_MSG = 51; 1550 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56; 1551 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57; 1552 static final int IDLE_UIDS_MSG = 58; 1553 static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63; 1554 static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66; 1555 static final int SERVICE_FOREGROUND_TIMEOUT_ANR_MSG = 67; 1556 static final int PUSH_TEMP_ALLOWLIST_UI_MSG = 68; 1557 static final int SERVICE_FOREGROUND_CRASH_MSG = 69; 1558 static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70; 1559 static final int KILL_APP_ZYGOTE_MSG = 71; 1560 static final int BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG = 72; 1561 static final int WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG = 73; 1562 static final int DISPATCH_SENDING_BROADCAST_EVENT = 74; 1563 static final int DISPATCH_BINDING_SERVICE_EVENT = 75; 1564 static final int SERVICE_SHORT_FGS_TIMEOUT_MSG = 76; 1565 static final int SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG = 77; 1566 static final int SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG = 78; 1567 static final int UPDATE_CACHED_APP_HIGH_WATERMARK = 79; 1568 static final int ADD_UID_TO_OBSERVER_MSG = 80; 1569 static final int REMOVE_UID_FROM_OBSERVER_MSG = 81; 1570 static final int BIND_APPLICATION_TIMEOUT_SOFT_MSG = 82; 1571 static final int BIND_APPLICATION_TIMEOUT_HARD_MSG = 83; 1572 static final int SERVICE_FGS_TIMEOUT_MSG = 84; 1573 static final int SERVICE_FGS_CRASH_TIMEOUT_MSG = 85; 1574 static final int FOLLOW_UP_OOMADJUSTER_UPDATE_MSG = 86; 1575 1576 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1577 1578 /** 1579 * Flag whether the current user is a "monkey", i.e. whether 1580 * the UI is driven by a UI automation tool. 1581 */ 1582 private volatile boolean mUserIsMonkey; 1583 1584 @VisibleForTesting 1585 public final ServiceThread mHandlerThread; 1586 final MainHandler mHandler; 1587 final Handler mUiHandler; 1588 final ServiceThread mProcStartHandlerThread; 1589 final ProcStartHandler mProcStartHandler; 1590 1591 ActivityManagerConstants mConstants; 1592 1593 // Encapsulates the global setting "hidden_api_blacklist_exemptions" 1594 final HiddenApiSettings mHiddenApiBlacklist; 1595 1596 final PlatformCompat mPlatformCompat; 1597 1598 PackageManagerInternal mPackageManagerInt; 1599 PermissionManagerServiceInternal mPermissionManagerInt; 1600 private TestUtilityService mTestUtilityService; 1601 1602 // Packages which have received a (LOCKED_)BOOT_COMPLETED broadcast since 1603 // the private space profile has been started 1604 @GuardedBy("this") 1605 private final ArraySet<String> mPrivateSpaceBootCompletedPackages = new ArraySet<String>(); 1606 1607 /** 1608 * Whether to force background check on all apps (for battery saver) or not. 1609 */ 1610 @CompositeRWLock({"this", "mProcLock"}) 1611 private boolean mForceBackgroundCheck; 1612 1613 private static String sTheRealBuildSerial = Build.UNKNOWN; 1614 1615 @GuardedBy("mProcLock") 1616 private ParcelFileDescriptor[] mLifeMonitorFds; 1617 1618 static final HostingRecord sNullHostingRecord = 1619 new HostingRecord(HostingRecord.HOSTING_TYPE_EMPTY); 1620 /** 1621 * Used to notify activity lifecycle events. 1622 */ 1623 @Nullable volatile ContentCaptureManagerInternal mContentCaptureService; 1624 1625 /** 1626 * The interface to the freezer. 1627 */ 1628 @NonNull 1629 private final Freezer mFreezer; 1630 1631 /* 1632 * The default duration for the binder heavy hitter auto sampler 1633 */ 1634 private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS = 300000L; 1635 1636 /** 1637 * The default throttling duration for the binder heavy hitter auto sampler 1638 */ 1639 private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS = 3600000L; 1640 1641 /** 1642 * The last time when the binder heavy hitter auto sampler started. 1643 */ 1644 @GuardedBy("mProcLock") 1645 private long mLastBinderHeavyHitterAutoSamplerStart = 0L; 1646 1647 AppProfiler mAppProfiler; 1648 1649 private static final int INDEX_NATIVE_PSS = 0; 1650 private static final int INDEX_NATIVE_SWAP_PSS = 1; 1651 private static final int INDEX_NATIVE_RSS = 2; 1652 private static final int INDEX_NATIVE_PRIVATE_DIRTY = 3; 1653 private static final int INDEX_DALVIK_PSS = 4; 1654 private static final int INDEX_DALVIK_SWAP_PSS = 5; 1655 private static final int INDEX_DALVIK_RSS = 6; 1656 private static final int INDEX_DALVIK_PRIVATE_DIRTY = 7; 1657 private static final int INDEX_OTHER_PSS = 8; 1658 private static final int INDEX_OTHER_SWAP_PSS = 9; 1659 private static final int INDEX_OTHER_RSS = 10; 1660 private static final int INDEX_OTHER_PRIVATE_DIRTY = 11; 1661 private static final int INDEX_TOTAL_PSS = 12; 1662 private static final int INDEX_TOTAL_SWAP_PSS = 13; 1663 private static final int INDEX_TOTAL_RSS = 14; 1664 private static final int INDEX_TOTAL_PRIVATE_DIRTY = 15; 1665 private static final int INDEX_TOTAL_NATIVE_PSS = 16; 1666 private static final int INDEX_TOTAL_MEMTRACK_GRAPHICS = 17; 1667 private static final int INDEX_TOTAL_MEMTRACK_GL = 18; 1668 private static final int INDEX_LAST = 19; 1669 1670 /** 1671 * Used to notify activity lifecycle events. 1672 */ 1673 @Nullable 1674 volatile ActivityManagerInternal.VoiceInteractionManagerProvider 1675 mVoiceInteractionManagerProvider; 1676 1677 final class UiHandler extends Handler { UiHandler()1678 public UiHandler() { 1679 super(com.android.server.UiThread.get().getLooper(), null, true); 1680 } 1681 1682 @Override handleMessage(Message msg)1683 public void handleMessage(Message msg) { 1684 switch (msg.what) { 1685 case SHOW_ERROR_UI_MSG: { 1686 mAppErrors.handleShowAppErrorUi(msg); 1687 ensureBootCompleted(); 1688 } break; 1689 case SHOW_NOT_RESPONDING_UI_MSG: { 1690 mAppErrors.handleShowAnrUi(msg); 1691 ensureBootCompleted(); 1692 } break; 1693 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: { 1694 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1695 synchronized (mProcLock) { 1696 ProcessRecord proc = (ProcessRecord) data.get("app"); 1697 if (proc == null) { 1698 Slog.e(TAG, "App not found when showing strict mode dialog."); 1699 break; 1700 } 1701 if (proc.mErrorState.getDialogController().hasViolationDialogs()) { 1702 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1703 return; 1704 } 1705 AppErrorResult res = (AppErrorResult) data.get("result"); 1706 if (mAtmInternal.showStrictModeViolationDialog()) { 1707 proc.mErrorState.getDialogController().showViolationDialogs(res); 1708 } else { 1709 // The device is asleep, so just pretend that the user 1710 // saw a crash dialog and hit "force quit". 1711 res.set(0); 1712 } 1713 } 1714 ensureBootCompleted(); 1715 } break; 1716 case WAIT_FOR_DEBUGGER_UI_MSG: { 1717 synchronized (mProcLock) { 1718 ProcessRecord app = (ProcessRecord) msg.obj; 1719 if (msg.arg1 != 0) { 1720 if (!app.hasWaitedForDebugger()) { 1721 app.mErrorState.getDialogController().showDebugWaitingDialogs(); 1722 app.setWaitedForDebugger(true); 1723 } 1724 } else { 1725 app.mErrorState.getDialogController().clearWaitingDialog(); 1726 } 1727 } 1728 } break; 1729 case DISPATCH_PROCESSES_CHANGED_UI_MSG: { 1730 mProcessList.dispatchProcessesChanged(); 1731 break; 1732 } 1733 case DISPATCH_PROCESS_DIED_UI_MSG: { 1734 if (false) { // DO NOT SUBMIT WITH TRUE 1735 maybeTriggerWatchdog(); 1736 } 1737 final int pid = msg.arg1; 1738 final int uid = msg.arg2; 1739 mProcessList.dispatchProcessDied(pid, uid); 1740 break; 1741 } 1742 case DISPATCH_OOM_ADJ_OBSERVER_MSG: { 1743 dispatchOomAdjObserver((String) msg.obj); 1744 } break; 1745 case PUSH_TEMP_ALLOWLIST_UI_MSG: { 1746 pushTempAllowlist(); 1747 } break; 1748 case ADD_UID_TO_OBSERVER_MSG: { 1749 mUidObserverController.addUidToObserverImpl((IBinder) msg.obj, msg.arg1); 1750 } break; 1751 case REMOVE_UID_FROM_OBSERVER_MSG: { 1752 mUidObserverController.removeUidFromObserverImpl((IBinder) msg.obj, msg.arg1); 1753 } break; 1754 } 1755 } 1756 } 1757 1758 final class MainHandler extends Handler { MainHandler(Looper looper)1759 public MainHandler(Looper looper) { 1760 super(looper, null, true); 1761 } 1762 1763 @Override handleMessage(Message msg)1764 public void handleMessage(Message msg) { 1765 switch (msg.what) { 1766 case GC_BACKGROUND_PROCESSES_MSG: { 1767 synchronized (ActivityManagerService.this) { 1768 mAppProfiler.performAppGcsIfAppropriateLocked(); 1769 } 1770 } break; 1771 case SERVICE_TIMEOUT_MSG: { 1772 mServices.serviceTimeout((ProcessRecord) msg.obj); 1773 } break; 1774 case SERVICE_FOREGROUND_TIMEOUT_MSG: { 1775 mServices.serviceForegroundTimeout((ServiceRecord) msg.obj); 1776 } break; 1777 case SERVICE_FOREGROUND_TIMEOUT_ANR_MSG: { 1778 SomeArgs args = (SomeArgs) msg.obj; 1779 mServices.serviceForegroundTimeoutANR((ProcessRecord) args.arg1, 1780 (TimeoutRecord) args.arg2); 1781 args.recycle(); 1782 } break; 1783 case SERVICE_FOREGROUND_CRASH_MSG: { 1784 SomeArgs args = (SomeArgs) msg.obj; 1785 mServices.serviceForegroundCrash( 1786 (ProcessRecord) args.arg1, 1787 (String) args.arg2, 1788 (ComponentName) args.arg3); 1789 args.recycle(); 1790 } break; 1791 case UPDATE_TIME_ZONE: { 1792 synchronized (mProcLock) { 1793 mProcessList.forEachLruProcessesLOSP(false, app -> { 1794 final IApplicationThread thread = app.getThread(); 1795 if (thread != null) { 1796 try { 1797 thread.updateTimeZone(); 1798 } catch (RemoteException ex) { 1799 Slog.w(TAG, "Failed to update time zone for: " 1800 + app.info.processName); 1801 } 1802 } 1803 }); 1804 } 1805 } break; 1806 case CLEAR_DNS_CACHE_MSG: { 1807 synchronized (mProcLock) { 1808 mProcessList.clearAllDnsCacheLOSP(); 1809 } 1810 } break; 1811 case UPDATE_HTTP_PROXY_MSG: { 1812 mProcessList.setAllHttpProxy(); 1813 } break; 1814 case PROC_START_TIMEOUT_MSG: { 1815 ProcessRecord app = (ProcessRecord) msg.obj; 1816 synchronized (ActivityManagerService.this) { 1817 handleProcessStartOrKillTimeoutLocked(app, /* isKillTimeout */ false); 1818 } 1819 } break; 1820 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: { 1821 ProcessRecord app = (ProcessRecord) msg.obj; 1822 synchronized (ActivityManagerService.this) { 1823 mCpHelper.processContentProviderPublishTimedOutLocked(app); 1824 } 1825 } break; 1826 case KILL_APPLICATION_MSG: { 1827 synchronized (ActivityManagerService.this) { 1828 final int appId = msg.arg1; 1829 final int userId = msg.arg2; 1830 SomeArgs args = (SomeArgs) msg.obj; 1831 String pkg = (String) args.arg1; 1832 String reason = (String) args.arg2; 1833 int exitInfoReason = (int) args.arg3; 1834 args.recycle(); 1835 forceStopPackageLocked(pkg, appId, false, false, true, false, 1836 false, false, userId, reason, exitInfoReason); 1837 } 1838 } break; 1839 1840 case KILL_APP_ZYGOTE_MSG: { 1841 synchronized (ActivityManagerService.this) { 1842 final AppZygote appZygote = (AppZygote) msg.obj; 1843 mProcessList.killAppZygoteIfNeededLocked(appZygote, false /* force */); 1844 } 1845 } break; 1846 case CHECK_EXCESSIVE_POWER_USE_MSG: { 1847 checkExcessivePowerUsage(); 1848 removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG); 1849 Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 1850 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 1851 } break; 1852 case REPORT_MEM_USAGE_MSG: { 1853 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>) msg.obj; 1854 Thread thread = new Thread() { 1855 @Override public void run() { 1856 mAppProfiler.reportMemUsage(memInfos); 1857 } 1858 }; 1859 thread.start(); 1860 break; 1861 } 1862 case UPDATE_TIME_PREFERENCE_MSG: { 1863 // The user's time format preference might have changed. 1864 // For convenience we re-use the Intent extra values. 1865 synchronized (mProcLock) { 1866 mProcessList.updateAllTimePrefsLOSP(msg.arg1); 1867 } 1868 break; 1869 } 1870 case NOTIFY_CLEARTEXT_NETWORK_MSG: { 1871 final int uid = msg.arg1; 1872 final byte[] firstPacket = (byte[]) msg.obj; 1873 1874 synchronized (mProcLock) { 1875 synchronized (mPidsSelfLocked) { 1876 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 1877 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 1878 final IApplicationThread thread = p.getThread(); 1879 if (p.uid == uid && thread != null) { 1880 try { 1881 thread.notifyCleartextNetwork(firstPacket); 1882 } catch (RemoteException ignored) { 1883 } 1884 } 1885 } 1886 } 1887 } 1888 } break; 1889 case POST_DUMP_HEAP_NOTIFICATION_MSG: { 1890 mAppProfiler.handlePostDumpHeapNotification(); 1891 } break; 1892 case ABORT_DUMPHEAP_MSG: { 1893 mAppProfiler.handleAbortDumpHeap((String) msg.obj); 1894 } break; 1895 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: { 1896 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj; 1897 try { 1898 connection.shutdown(); 1899 } catch (RemoteException e) { 1900 Slog.w(TAG, "Error shutting down UiAutomationConnection"); 1901 } 1902 // Only a UiAutomation can set this flag and now that 1903 // it is finished we make sure it is reset to its default. 1904 mUserIsMonkey = false; 1905 } break; 1906 case IDLE_UIDS_MSG: { 1907 idleUids(); 1908 } break; 1909 case HANDLE_TRUST_STORAGE_UPDATE_MSG: { 1910 synchronized (mProcLock) { 1911 mProcessList.handleAllTrustStorageUpdateLOSP(); 1912 } 1913 } break; 1914 case BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG: { 1915 handleBinderHeavyHitterAutoSamplerTimeOut(); 1916 } break; 1917 case WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG: { 1918 synchronized (ActivityManagerService.this) { 1919 ((ContentProviderRecord) msg.obj).onProviderPublishStatusLocked(false); 1920 } 1921 } break; 1922 case DISPATCH_SENDING_BROADCAST_EVENT: { 1923 mBroadcastEventListeners.forEach(l -> 1924 l.onSendingBroadcast((String) msg.obj, msg.arg1)); 1925 } break; 1926 case DISPATCH_BINDING_SERVICE_EVENT: { 1927 mBindServiceEventListeners.forEach(l -> 1928 l.onBindingService((String) msg.obj, msg.arg1)); 1929 } break; 1930 case SERVICE_SHORT_FGS_TIMEOUT_MSG: { 1931 mServices.onShortFgsTimeout((ServiceRecord) msg.obj); 1932 } break; 1933 case SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG: { 1934 mServices.onShortFgsProcstateTimeout((ServiceRecord) msg.obj); 1935 } break; 1936 case SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG: { 1937 mServices.onShortFgsAnrTimeout((ServiceRecord) msg.obj); 1938 } break; 1939 case UPDATE_CACHED_APP_HIGH_WATERMARK: { 1940 mAppProfiler.mCachedAppsWatermarkData.updateCachedAppsSnapshot((long) msg.obj); 1941 } break; 1942 case BIND_APPLICATION_TIMEOUT_SOFT_MSG: { 1943 handleBindApplicationTimeoutSoft((ProcessRecord) msg.obj, msg.arg1); 1944 } break; 1945 case BIND_APPLICATION_TIMEOUT_HARD_MSG: { 1946 handleBindApplicationTimeoutHard((ProcessRecord) msg.obj); 1947 } break; 1948 case SERVICE_FGS_TIMEOUT_MSG: { 1949 mServices.onFgsTimeout((ServiceRecord) msg.obj); 1950 } break; 1951 case SERVICE_FGS_CRASH_TIMEOUT_MSG: { 1952 mServices.onFgsCrashTimeout((ServiceRecord) msg.obj); 1953 } break; 1954 case FOLLOW_UP_OOMADJUSTER_UPDATE_MSG: { 1955 handleFollowUpOomAdjusterUpdate(); 1956 } break; 1957 } 1958 } 1959 } 1960 1961 setSystemProcess()1962 public void setSystemProcess() { 1963 try { 1964 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, 1965 DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); 1966 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 1967 ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false, 1968 DUMP_FLAG_PRIORITY_HIGH); 1969 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 1970 ServiceManager.addService("dbinfo", new DbBinder(this)); 1971 mAppProfiler.setCpuInfoService(); 1972 ServiceManager.addService("permission", new PermissionController(this)); 1973 ServiceManager.addService("processinfo", new ProcessInfoService(this)); 1974 ServiceManager.addService("cacheinfo", new CacheBinder(this)); 1975 1976 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 1977 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); 1978 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 1979 1980 synchronized (this) { 1981 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName, 1982 false, 1983 0, 1984 false, 1985 0, 1986 null, 1987 new HostingRecord(HostingRecord.HOSTING_TYPE_SYSTEM)); 1988 app.setPersistent(true); 1989 app.setPid(MY_PID); 1990 mProcessStateController.setMaxAdj(app, ProcessList.SYSTEM_ADJ); 1991 app.makeActive(new ApplicationThreadDeferred(mSystemThread.getApplicationThread()), 1992 mProcessStats); 1993 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_SYSTEM); 1994 addPidLocked(app); 1995 updateLruProcessLocked(app, false, null); 1996 updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT); 1997 } 1998 } catch (PackageManager.NameNotFoundException e) { 1999 throw new RuntimeException( 2000 "Unable to find android system package", e); 2001 } 2002 2003 // Start watching app ops after we and the package manager are up and running. 2004 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null, 2005 new IAppOpsCallback.Stub() { 2006 @Override public void opChanged(int op, int uid, String packageName, 2007 String persistentDeviceId) { 2008 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && uid >= 0) { 2009 if (getAppOpsManager().checkOpNoThrow(op, uid, packageName) 2010 != AppOpsManager.MODE_ALLOWED) { 2011 runInBackgroundDisabled(uid); 2012 } 2013 } 2014 } 2015 }); 2016 2017 final int[] cameraOp = {AppOpsManager.OP_CAMERA}; 2018 mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() { 2019 @Override 2020 public void opActiveChanged(int op, int uid, String packageName, String attributionTag, 2021 int virtualDeviceId, boolean active, @AttributionFlags int attributionFlags, 2022 int attributionChainId) { 2023 cameraActiveChanged(uid, active); 2024 } 2025 }); 2026 } 2027 setWindowManager(WindowManagerService wm)2028 public void setWindowManager(WindowManagerService wm) { 2029 synchronized (this) { 2030 mWindowManager = wm; 2031 mWmInternal = LocalServices.getService(WindowManagerInternal.class); 2032 mActivityTaskManager.setWindowManager(wm); 2033 } 2034 } 2035 2036 /** 2037 * @param usageStatsManager shouldn't be null 2038 */ setUsageStatsManager(@onNull UsageStatsManagerInternal usageStatsManager)2039 public void setUsageStatsManager(@NonNull UsageStatsManagerInternal usageStatsManager) { 2040 mUsageStatsService = usageStatsManager; 2041 mActivityTaskManager.setUsageStatsManager(usageStatsManager); 2042 } 2043 2044 /** 2045 * Sets the internal content capture manager service. 2046 * 2047 * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock. 2048 */ setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)2049 public void setContentCaptureManager( 2050 @Nullable ContentCaptureManagerInternal contentCaptureManager) { 2051 mContentCaptureService = contentCaptureManager; 2052 } 2053 startObservingNativeCrashes()2054 public void startObservingNativeCrashes() { 2055 final NativeCrashListener ncl = new NativeCrashListener(this); 2056 ncl.start(); 2057 } 2058 2059 /** 2060 * Sets a policy for handling app ops. 2061 * 2062 * @param appOpsPolicy The policy. 2063 */ setAppOpsPolicy(@ullable CheckOpsDelegate appOpsPolicy)2064 public void setAppOpsPolicy(@Nullable CheckOpsDelegate appOpsPolicy) { 2065 mAppOpsService.setAppOpsPolicy(appOpsPolicy); 2066 } 2067 getAppOpsService()2068 public IAppOpsService getAppOpsService() { 2069 return mAppOpsService; 2070 } 2071 2072 /** 2073 * Sets the internal voice interaction manager service. 2074 */ setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)2075 private void setVoiceInteractionManagerProvider( 2076 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) { 2077 mVoiceInteractionManagerProvider = provider; 2078 } 2079 2080 /** 2081 * Represents volatile states associated with a Dropbox entry. 2082 * <p> 2083 * These states, such as the process frozen state, can change quickly over time and thus 2084 * should be captured as soon as possible to ensure accurate state. If a state is undefined, 2085 * it means that the state was not read early and a fallback value can be used. 2086 * </p> 2087 */ 2088 static class VolatileDropboxEntryStates { 2089 private final Boolean mIsProcessFrozen; 2090 private final ZonedDateTime mTimestamp; 2091 VolatileDropboxEntryStates(Boolean frozenState, ZonedDateTime timestamp)2092 private VolatileDropboxEntryStates(Boolean frozenState, ZonedDateTime timestamp) { 2093 this.mIsProcessFrozen = frozenState; 2094 this.mTimestamp = timestamp; 2095 } 2096 withProcessFrozenStateAndTimestamp( boolean frozenState, ZonedDateTime timestamp)2097 public static VolatileDropboxEntryStates withProcessFrozenStateAndTimestamp( 2098 boolean frozenState, ZonedDateTime timestamp) { 2099 return new VolatileDropboxEntryStates(frozenState, timestamp); 2100 } 2101 isProcessFrozen()2102 public Boolean isProcessFrozen() { 2103 return mIsProcessFrozen; 2104 } 2105 getTimestamp()2106 public ZonedDateTime getTimestamp() { 2107 return mTimestamp; 2108 } 2109 } 2110 2111 static class MemBinder extends Binder { 2112 ActivityManagerService mActivityManagerService; 2113 private final PriorityDump.PriorityDumper mPriorityDumper = 2114 new PriorityDump.PriorityDumper() { 2115 @Override 2116 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, 2117 boolean asProto) { 2118 dump(fd, pw, new String[] {"-a"}, asProto); 2119 } 2120 2121 @Override 2122 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 2123 mActivityManagerService.dumpApplicationMemoryUsage( 2124 fd, pw, " ", args, false, null, asProto); 2125 } 2126 }; 2127 MemBinder(ActivityManagerService activityManagerService)2128 MemBinder(ActivityManagerService activityManagerService) { 2129 mActivityManagerService = activityManagerService; 2130 } 2131 2132 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2133 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2134 try { 2135 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2136 2137 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2138 "meminfo", pw)) return; 2139 PriorityDump.dump(mPriorityDumper, fd, pw, args); 2140 } finally { 2141 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2142 } 2143 } 2144 } 2145 2146 static class GraphicsBinder extends Binder { 2147 ActivityManagerService mActivityManagerService; GraphicsBinder(ActivityManagerService activityManagerService)2148 GraphicsBinder(ActivityManagerService activityManagerService) { 2149 mActivityManagerService = activityManagerService; 2150 } 2151 2152 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2153 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2154 try { 2155 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2156 2157 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2158 "gfxinfo", pw)) return; 2159 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 2160 } finally { 2161 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2162 } 2163 } 2164 } 2165 2166 static class DbBinder extends Binder { 2167 ActivityManagerService mActivityManagerService; DbBinder(ActivityManagerService activityManagerService)2168 DbBinder(ActivityManagerService activityManagerService) { 2169 mActivityManagerService = activityManagerService; 2170 } 2171 2172 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2173 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2174 try { 2175 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2176 2177 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2178 "dbinfo", pw)) return; 2179 mActivityManagerService.dumpDbInfo(fd, pw, args); 2180 } finally { 2181 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2182 } 2183 } 2184 } 2185 2186 static class CacheBinder extends Binder { 2187 ActivityManagerService mActivityManagerService; 2188 CacheBinder(ActivityManagerService activityManagerService)2189 CacheBinder(ActivityManagerService activityManagerService) { 2190 mActivityManagerService = activityManagerService; 2191 } 2192 2193 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2194 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2195 try { 2196 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2197 2198 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2199 "cacheinfo", pw)) { 2200 return; 2201 } 2202 2203 mActivityManagerService.dumpBinderCacheContents(fd, pw, args); 2204 } finally { 2205 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2206 } 2207 } 2208 } 2209 2210 public static final class Lifecycle extends SystemService { 2211 private final ActivityManagerService mService; 2212 private static ActivityTaskManagerService sAtm; 2213 Lifecycle(Context context)2214 public Lifecycle(Context context) { 2215 super(context); 2216 mService = new ActivityManagerService(context, sAtm); 2217 } 2218 startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2219 public static ActivityManagerService startService( 2220 SystemServiceManager ssm, ActivityTaskManagerService atm) { 2221 sAtm = atm; 2222 return ssm.startService(ActivityManagerService.Lifecycle.class).getService(); 2223 } 2224 2225 @Override onStart()2226 public void onStart() { 2227 mService.start(); 2228 } 2229 2230 @Override onBootPhase(int phase)2231 public void onBootPhase(int phase) { 2232 mService.mBootPhase = phase; 2233 if (phase == PHASE_SYSTEM_SERVICES_READY) { 2234 mService.mBatteryStatsService.systemServicesReady(); 2235 mService.mServices.systemServicesReady(); 2236 } else if (phase == PHASE_ACTIVITY_MANAGER_READY) { 2237 mService.mBroadcastController.startBroadcastObservers(); 2238 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { 2239 if (!refactorCrashrecovery()) { 2240 CrashRecoveryAdaptor.packageWatchdogOnPackagesReady(mService.mPackageWatchdog); 2241 } else { 2242 mService.mCrashRecoveryHelper.registerConnectivityModuleHealthListener(); 2243 } 2244 mService.scheduleHomeTimeout(); 2245 } 2246 } 2247 2248 @Override onUserStopped(@onNull TargetUser user)2249 public void onUserStopped(@NonNull TargetUser user) { 2250 mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier()); 2251 2252 if (android.os.Flags.allowPrivateProfile() 2253 && android.multiuser.Flags.enablePrivateSpaceFeatures()) { 2254 final UserManagerInternal umInternal = 2255 LocalServices.getService(UserManagerInternal.class); 2256 UserInfo userInfo = umInternal.getUserInfo(user.getUserIdentifier()); 2257 2258 if (userInfo != null && userInfo.isPrivateProfile()) { 2259 synchronized (mService) { 2260 mService.mPrivateSpaceBootCompletedPackages.clear(); 2261 } 2262 } 2263 } 2264 } 2265 getService()2266 public ActivityManagerService getService() { 2267 return mService; 2268 } 2269 } 2270 2271 /** 2272 * Encapsulates global settings related to hidden API enforcement behaviour, including tracking 2273 * the latest value via a content observer. 2274 */ 2275 static class HiddenApiSettings extends ContentObserver 2276 implements DeviceConfig.OnPropertiesChangedListener { 2277 2278 private final Context mContext; 2279 private boolean mBlacklistDisabled; 2280 private String mExemptionsStr; 2281 private List<String> mExemptions = Collections.emptyList(); 2282 private int mLogSampleRate = -1; 2283 private int mStatslogSampleRate = -1; 2284 @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT; 2285 2286 /** 2287 * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in 2288 * the range 0 to 0x10000 inclusive. 2289 * 2290 * @hide 2291 */ 2292 public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE = 2293 "hidden_api_access_log_sampling_rate"; 2294 2295 /** 2296 * Sampling rate for hidden API access event logging with statslog, as an integer in the 2297 * range 0 to 0x10000 inclusive. 2298 * 2299 * @hide 2300 */ 2301 public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE = 2302 "hidden_api_access_statslog_sampling_rate"; 2303 onPropertiesChanged(DeviceConfig.Properties properties)2304 public void onPropertiesChanged(DeviceConfig.Properties properties) { 2305 int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0x0); 2306 if (logSampleRate < 0 || logSampleRate > 0x10000) { 2307 logSampleRate = -1; 2308 } 2309 if (logSampleRate != -1 && logSampleRate != mLogSampleRate) { 2310 mLogSampleRate = logSampleRate; 2311 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate); 2312 } 2313 2314 int statslogSampleRate = 2315 properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0); 2316 if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) { 2317 statslogSampleRate = -1; 2318 } 2319 if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) { 2320 mStatslogSampleRate = statslogSampleRate; 2321 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate); 2322 } 2323 } 2324 HiddenApiSettings(Handler handler, Context context)2325 public HiddenApiSettings(Handler handler, Context context) { 2326 super(handler); 2327 mContext = context; 2328 } 2329 registerObserver()2330 public void registerObserver() { 2331 mContext.getContentResolver().registerContentObserver( 2332 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS), 2333 false, 2334 this); 2335 mContext.getContentResolver().registerContentObserver( 2336 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY), 2337 false, 2338 this); 2339 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT, 2340 mContext.getMainExecutor(), this); 2341 update(); 2342 } 2343 update()2344 private void update() { 2345 String exemptions = Settings.Global.getString(mContext.getContentResolver(), 2346 Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS); 2347 if (!TextUtils.equals(exemptions, mExemptionsStr)) { 2348 mExemptionsStr = exemptions; 2349 if ("*".equals(exemptions)) { 2350 mBlacklistDisabled = true; 2351 mExemptions = Collections.emptyList(); 2352 } else { 2353 mBlacklistDisabled = false; 2354 mExemptions = TextUtils.isEmpty(exemptions) 2355 ? Collections.emptyList() 2356 : Arrays.asList(exemptions.split(",")); 2357 } 2358 if (!ZYGOTE_PROCESS.setApiDenylistExemptions(mExemptions)) { 2359 Slog.e(TAG, "Failed to set API blacklist exemptions!"); 2360 // leave mExemptionsStr as is, so we don't try to send the same list again. 2361 mExemptions = Collections.emptyList(); 2362 } 2363 } 2364 mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY); 2365 } 2366 getValidEnforcementPolicy(String settingsKey)2367 private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) { 2368 int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey, 2369 ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT); 2370 if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) { 2371 return policy; 2372 } else { 2373 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 2374 } 2375 } 2376 isDisabled()2377 boolean isDisabled() { 2378 return mBlacklistDisabled; 2379 } 2380 getPolicy()2381 @HiddenApiEnforcementPolicy int getPolicy() { 2382 return mPolicy; 2383 } 2384 onChange(boolean selfChange)2385 public void onChange(boolean selfChange) { 2386 update(); 2387 } 2388 } 2389 getAppOpsManager()2390 AppOpsManager getAppOpsManager() { 2391 if (mAppOpsManager == null) { 2392 mAppOpsManager = mContext.getSystemService(AppOpsManager.class); 2393 } 2394 return mAppOpsManager; 2395 } 2396 2397 /** Provides the basic functionality for unit tests. */ 2398 @VisibleForTesting ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread)2399 ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread) { 2400 this(injector, handlerThread, null); 2401 } 2402 2403 /** Provides the basic functionality for unit tests. */ 2404 @VisibleForTesting ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread, @Nullable UserController userController)2405 ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread, 2406 @Nullable UserController userController) { 2407 mInjector = injector; 2408 mContext = mInjector.getContext(); 2409 mFreezer = injector.getFreezer(); 2410 mUiContext = null; 2411 mAppErrors = injector.getAppErrors(); 2412 mPackageWatchdog = null; 2413 mCrashRecoveryHelper = null; 2414 mAppOpsService = mInjector.getAppOpsService(null /* recentAccessesFile */, 2415 null /* storageFile */, null /* handler */); 2416 mBatteryStatsService = mInjector.getBatteryStatsService(); 2417 mHandler = new MainHandler(handlerThread.getLooper()); 2418 mHandlerThread = handlerThread; 2419 mConstants = new ActivityManagerConstants(mContext, this, mHandler); 2420 final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */); 2421 mPlatformCompat = null; 2422 mProcessList = injector.getProcessList(this); 2423 mProcessList.init(this, activeUids, mPlatformCompat); 2424 mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), null); 2425 mPhantomProcessList = new PhantomProcessList(this); 2426 mProcessStateController = new ProcessStateController.Builder(this, mProcessList, activeUids) 2427 .setHandlerThread(handlerThread) 2428 .useModernOomAdjuster(mConstants.ENABLE_NEW_OOMADJ) 2429 .build(); 2430 mOomAdjuster = mProcessStateController.getOomAdjuster(); 2431 2432 mIntentFirewall = injector.getIntentFirewall(); 2433 mProcessStats = new ProcessStatsService(this, mContext.getCacheDir()); 2434 mCpHelper = new ContentProviderHelper(this, false); 2435 mServices = mInjector.getActiveServices(this); 2436 mSystemThread = null; 2437 mUiHandler = injector.getUiHandler(null /* service */); 2438 mUidObserverController = new UidObserverController(mUiHandler); 2439 mUserController = userController == null ? new UserController(this) : userController; 2440 mInjector.mUserController = mUserController; 2441 mPendingIntentController = 2442 new PendingIntentController(handlerThread.getLooper(), mUserController, mConstants); 2443 mAppRestrictionController = new AppRestrictionController(mContext, this); 2444 mProcStartHandlerThread = null; 2445 mProcStartHandler = null; 2446 mHiddenApiBlacklist = null; 2447 mFactoryTest = FACTORY_TEST_OFF; 2448 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2449 mInternal = new LocalService(); 2450 mPendingStartActivityUids = new PendingStartActivityUids(); 2451 mUseFifoUiScheduling = false; 2452 mBroadcastQueue = injector.getBroadcastQueue(this); 2453 mBroadcastController = new BroadcastController(mContext, this, mBroadcastQueue); 2454 mComponentAliasResolver = new ComponentAliasResolver(this); 2455 mApplicationSharedMemoryReadOnlyFd = null; 2456 sCreatorTokenCacheCleaner = new Handler(mHandlerThread.getLooper()); 2457 } 2458 2459 // Note: This method is invoked on the main thread but may need to attach various 2460 // handlers to other threads. So take care to be explicit about the looper. ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2461 public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) { 2462 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); 2463 mInjector = new Injector(systemContext); 2464 mContext = systemContext; 2465 mFreezer = mInjector.getFreezer(); 2466 2467 mFactoryTest = FactoryTest.getMode(); 2468 mSystemThread = ActivityThread.currentActivityThread(); 2469 mUiContext = mSystemThread.getSystemUiContext(); 2470 2471 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2472 2473 mHandlerThread = new ServiceThread(TAG, 2474 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2475 mHandlerThread.start(); 2476 mHandler = new MainHandler(mHandlerThread.getLooper()); 2477 mUiHandler = mInjector.getUiHandler(this); 2478 2479 mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", 2480 THREAD_PRIORITY_FOREGROUND, false /* allowIo */); 2481 mProcStartHandlerThread.start(); 2482 mProcStartHandler = new ProcStartHandler(this, mProcStartHandlerThread.getLooper()); 2483 2484 mConstants = new ActivityManagerConstants(mContext, this, mHandler); 2485 final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */); 2486 mPlatformCompat = (PlatformCompat) ServiceManager.getService( 2487 Context.PLATFORM_COMPAT_SERVICE); 2488 mProcessList = mInjector.getProcessList(this); 2489 mProcessList.init(this, activeUids, mPlatformCompat); 2490 mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), 2491 new LowMemDetector(this)); 2492 mPhantomProcessList = new PhantomProcessList(this); 2493 mProcessStateController = new ProcessStateController.Builder(this, mProcessList, activeUids) 2494 .useModernOomAdjuster(mConstants.ENABLE_NEW_OOMADJ) 2495 .build(); 2496 mOomAdjuster = mProcessStateController.getOomAdjuster(); 2497 2498 mBroadcastQueue = mInjector.getBroadcastQueue(this); 2499 mBroadcastController = new BroadcastController(mContext, this, mBroadcastQueue); 2500 2501 mServices = new ActiveServices(this); 2502 mCpHelper = new ContentProviderHelper(this, true); 2503 mCrashRecoveryHelper = new CrashRecoveryHelper(mUiContext); 2504 mPackageWatchdog = PackageWatchdog.getInstance(mUiContext); 2505 mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog); 2506 mUidObserverController = new UidObserverController(mUiHandler); 2507 2508 final File systemDir = SystemServiceManager.ensureSystemDir(); 2509 2510 // TODO: Move creation of battery stats service outside of activity manager service. 2511 mBatteryStatsService = BatteryStatsService.create(systemContext, systemDir, 2512 BackgroundThread.getHandler(), this); 2513 mOnBattery = DEBUG_POWER ? true 2514 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2515 2516 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2517 2518 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops_accesses.xml"), 2519 new File(systemDir, "appops.xml"), mHandler); 2520 2521 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2522 2523 mUserController = new UserController(this); 2524 mInjector.mUserController = mUserController; 2525 2526 mPendingIntentController = new PendingIntentController( 2527 mHandlerThread.getLooper(), mUserController, mConstants); 2528 2529 mAppRestrictionController = new AppRestrictionController(mContext, this); 2530 2531 mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0; 2532 2533 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations")); 2534 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2535 2536 mActivityTaskManager = atm; 2537 mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, 2538 DisplayThread.get().getLooper()); 2539 mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class); 2540 2541 mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext); 2542 2543 Watchdog.getInstance().addMonitor(this); 2544 Watchdog.getInstance().addThread(mHandler); 2545 2546 // bind background threads to little cores 2547 // this is expected to fail inside of framework tests because apps can't touch cpusets directly 2548 // make sure we've already adjusted system_server's internal view of itself first 2549 updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT); 2550 try { 2551 Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(), 2552 Process.THREAD_GROUP_SYSTEM); 2553 Process.setThreadGroupAndCpuset( 2554 mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(), 2555 Process.THREAD_GROUP_SYSTEM); 2556 } catch (Exception e) { 2557 Slog.w(TAG, "Setting background thread cpuset failed"); 2558 } 2559 2560 mInternal = new LocalService(); 2561 mPendingStartActivityUids = new PendingStartActivityUids(); 2562 mTraceErrorLogger = new TraceErrorLogger(); 2563 mComponentAliasResolver = new ComponentAliasResolver(this); 2564 sCreatorTokenCacheCleaner = new Handler(mHandlerThread.getLooper()); 2565 2566 ApplicationSharedMemory applicationSharedMemory = ApplicationSharedMemory.getInstance(); 2567 if (android.content.pm.Flags.cacheSdkSystemFeatures()) { 2568 // Install the cache into the process-wide singleton for in-proc queries, as well as 2569 // shared memory. Apps will inflate the cache from shared memory in bindApplication. 2570 SystemFeaturesCache systemFeaturesCache = 2571 new SystemFeaturesCache(SystemConfig.getInstance().getAvailableFeatures()); 2572 SystemFeaturesCache.setInstance(systemFeaturesCache); 2573 applicationSharedMemory.writeSystemFeaturesCache( 2574 systemFeaturesCache.getSdkFeatureVersions()); 2575 } 2576 try { 2577 mApplicationSharedMemoryReadOnlyFd = 2578 applicationSharedMemory.getReadOnlyFileDescriptor(); 2579 } catch (IOException e) { 2580 Slog.e(TAG, "Failed to get read only fd for shared memory", e); 2581 throw new RuntimeException(e); 2582 } 2583 } 2584 setBroadcastQueueForTest(BroadcastQueue broadcastQueue)2585 void setBroadcastQueueForTest(BroadcastQueue broadcastQueue) { 2586 mBroadcastQueue = broadcastQueue; 2587 mBroadcastController.setBroadcastQueueForTest(broadcastQueue); 2588 } 2589 getBroadcastQueue()2590 BroadcastQueue getBroadcastQueue() { 2591 return mBroadcastQueue; 2592 } 2593 setSystemServiceManager(SystemServiceManager mgr)2594 public void setSystemServiceManager(SystemServiceManager mgr) { 2595 mSystemServiceManager = mgr; 2596 } 2597 setInstaller(Installer installer)2598 public void setInstaller(Installer installer) { 2599 mInstaller = installer; 2600 } 2601 start()2602 private void start() { 2603 mBatteryStatsService.publish(); 2604 mAppOpsService.publish(); 2605 mProcessStats.publish(); 2606 Slog.d("AppOps", "AppOpsService published"); 2607 LocalServices.addService(ActivityManagerInternal.class, mInternal); 2608 LocalManagerRegistry.addManager(ActivityManagerLocal.class, 2609 (ActivityManagerLocal) mInternal); 2610 mActivityTaskManager.onActivityManagerInternalAdded(); 2611 mPendingIntentController.onActivityManagerInternalAdded(); 2612 mAppProfiler.onActivityManagerInternalAdded(); 2613 CriticalEventLog.init(); 2614 } 2615 initPowerManagement()2616 public void initPowerManagement() { 2617 mActivityTaskManager.onInitPowerManagement(); 2618 mBatteryStatsService.initPowerManagement(); 2619 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); 2620 } 2621 2622 /** 2623 * Ensures that the given package name has an explicit set of allowed associations. 2624 * If it does not, give it an empty set. 2625 */ requireAllowedAssociationsLocked(String packageName)2626 void requireAllowedAssociationsLocked(String packageName) { 2627 ensureAllowedAssociations(); 2628 if (mAllowedAssociations.get(packageName) == null) { 2629 mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName, 2630 new ArraySet<>(), /* isDebuggable = */ false)); 2631 } 2632 } 2633 2634 /** 2635 * Returns true if the package {@code pkg1} running under user handle {@code uid1} is 2636 * allowed association with the package {@code pkg2} running under user handle {@code uid2}. 2637 * <p> If either of the packages are running as part of the core system, then the 2638 * association is implicitly allowed. 2639 */ validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2640 boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) { 2641 ensureAllowedAssociations(); 2642 // Interactions with the system uid are always allowed, since that is the core system 2643 // that everyone needs to be able to interact with. Also allow reflexive associations 2644 // within the same uid. 2645 if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID 2646 || UserHandle.getAppId(uid2) == SYSTEM_UID) { 2647 return true; 2648 } 2649 2650 // Check for association on both source and target packages. 2651 PackageAssociationInfo pai = mAllowedAssociations.get(pkg1); 2652 if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) { 2653 return false; 2654 } 2655 pai = mAllowedAssociations.get(pkg2); 2656 if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) { 2657 return false; 2658 } 2659 // If no explicit associations are provided in the manifest, then assume the app is 2660 // allowed associations with any package. 2661 return true; 2662 } 2663 2664 /** Sets up allowed associations for system prebuilt packages from system config (if needed). */ ensureAllowedAssociations()2665 private void ensureAllowedAssociations() { 2666 if (mAllowedAssociations == null) { 2667 ArrayMap<String, ArraySet<String>> allowedAssociations = 2668 SystemConfig.getInstance().getAllowedAssociations(); 2669 mAllowedAssociations = new ArrayMap<>(allowedAssociations.size()); 2670 PackageManagerInternal pm = getPackageManagerInternal(); 2671 for (int i = 0; i < allowedAssociations.size(); i++) { 2672 final String pkg = allowedAssociations.keyAt(i); 2673 final ArraySet<String> asc = allowedAssociations.valueAt(i); 2674 2675 // Query latest debuggable flag from package-manager. 2676 boolean isDebuggable = false; 2677 try { 2678 ApplicationInfo ai = AppGlobals.getPackageManager() 2679 .getApplicationInfo(pkg, MATCH_ALL, 0); 2680 if (ai != null) { 2681 isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 2682 } 2683 } catch (RemoteException e) { 2684 /* ignore */ 2685 } 2686 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable)); 2687 } 2688 } 2689 } 2690 2691 /** Updates allowed associations for app info (specifically, based on debuggability). */ updateAssociationForApp(ApplicationInfo appInfo)2692 void updateAssociationForApp(ApplicationInfo appInfo) { 2693 ensureAllowedAssociations(); 2694 PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName); 2695 if (pai != null) { 2696 pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); 2697 } 2698 } 2699 2700 @Override onTransact(int code, Parcel data, Parcel reply, int flags)2701 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2702 throws RemoteException { 2703 if (code == SYSPROPS_TRANSACTION) { 2704 // We need to tell all apps about the system property change. 2705 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2706 synchronized (mProcLock) { 2707 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 2708 mProcessList.getProcessNamesLOSP().getMap(); 2709 final int numOfNames = pmap.size(); 2710 for (int ip = 0; ip < numOfNames; ip++) { 2711 SparseArray<ProcessRecord> apps = pmap.valueAt(ip); 2712 final int numOfApps = apps.size(); 2713 for (int ia = 0; ia < numOfApps; ia++) { 2714 ProcessRecord app = apps.valueAt(ia); 2715 final IApplicationThread thread = app.getThread(); 2716 if (thread != null) { 2717 procs.add(thread.asBinder()); 2718 } 2719 } 2720 } 2721 } 2722 2723 int N = procs.size(); 2724 for (int i=0; i<N; i++) { 2725 Parcel data2 = Parcel.obtain(); 2726 try { 2727 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 2728 Binder.FLAG_ONEWAY); 2729 } catch (RemoteException e) { 2730 } 2731 data2.recycle(); 2732 } 2733 } 2734 try { 2735 return super.onTransact(code, data, reply, flags); 2736 } catch (RuntimeException e) { 2737 // The activity manager only throws certain exceptions intentionally, so let's 2738 // log all others. 2739 if (!(e instanceof SecurityException 2740 || e instanceof IllegalArgumentException 2741 || e instanceof IllegalStateException)) { 2742 Slog.wtf(TAG, "Activity Manager Crash." 2743 + " UID:" + Binder.getCallingUid() 2744 + " PID:" + Binder.getCallingPid() 2745 + " TRANS:" + code, e); 2746 } 2747 throw e; 2748 } 2749 } 2750 updateCpuStats()2751 void updateCpuStats() { 2752 mAppProfiler.updateCpuStats(); 2753 } 2754 updateCpuStatsNow()2755 void updateCpuStatsNow() { 2756 mAppProfiler.updateCpuStatsNow(); 2757 } 2758 2759 @Override batteryNeedsCpuUpdate()2760 public void batteryNeedsCpuUpdate() { 2761 updateCpuStatsNow(); 2762 } 2763 2764 @Override batteryPowerChanged(boolean onBattery)2765 public void batteryPowerChanged(boolean onBattery) { 2766 // When plugging in, update the CPU stats first before changing 2767 // the plug state. 2768 updateCpuStatsNow(); 2769 synchronized (mProcLock) { 2770 mOnBattery = DEBUG_POWER ? true : onBattery; 2771 } 2772 } 2773 2774 @Override batteryStatsReset()2775 public void batteryStatsReset() { 2776 // Empty for now. 2777 } 2778 2779 @Override batterySendBroadcast(Intent intent)2780 public void batterySendBroadcast(Intent intent) { 2781 synchronized (this) { 2782 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, null, 2783 null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(), 2784 Binder.getCallingPid(), UserHandle.USER_ALL); 2785 } 2786 } 2787 2788 /** 2789 * Initialize the application bind args. These are passed to each 2790 * process when the bindApplication() IPC is sent to the process. They're 2791 * lazily setup to make sure the services are running when they're asked for. 2792 */ getCommonServicesLocked(boolean isolated)2793 private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) { 2794 // Isolated processes won't get this optimization, so that we don't 2795 // violate the rules about which services they have access to. 2796 if (isolated) { 2797 if (mIsolatedAppBindArgs == null) { 2798 mIsolatedAppBindArgs = new ArrayMap<>(1); 2799 // See b/79378449 about the following exemption. 2800 addServiceToMap(mIsolatedAppBindArgs, "package"); 2801 addServiceToMap(mIsolatedAppBindArgs, "permissionmgr"); 2802 } 2803 return mIsolatedAppBindArgs; 2804 } 2805 2806 if (mAppBindArgs == null) { 2807 mAppBindArgs = new ArrayMap<>(); 2808 2809 // Add common services. 2810 // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too. 2811 // Enable the check in ApplicationThread.bindApplication() to make sure. 2812 addServiceToMap(mAppBindArgs, "package"); 2813 addServiceToMap(mAppBindArgs, "permissionmgr"); 2814 addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE); 2815 addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE); 2816 addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE); 2817 addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE); 2818 addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE); 2819 addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE); 2820 addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE); 2821 addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE); 2822 addServiceToMap(mAppBindArgs, "graphicsstats"); 2823 addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE); 2824 addServiceToMap(mAppBindArgs, "content"); 2825 addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE); 2826 addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE); 2827 addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE); 2828 addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE); 2829 addServiceToMap(mAppBindArgs, Context.POWER_SERVICE); 2830 addServiceToMap(mAppBindArgs, Context.USER_SERVICE); 2831 addServiceToMap(mAppBindArgs, "mount"); 2832 addServiceToMap(mAppBindArgs, Context.PLATFORM_COMPAT_SERVICE); 2833 } 2834 return mAppBindArgs; 2835 } 2836 addServiceToMap(ArrayMap<String, IBinder> map, String name)2837 private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) { 2838 final IBinder service = ServiceManager.getService(name); 2839 if (service != null) { 2840 map.put(name, service); 2841 if (false) { 2842 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache."); 2843 } 2844 } 2845 } 2846 2847 @Override setFocusedRootTask(int taskId)2848 public void setFocusedRootTask(int taskId) { 2849 mActivityTaskManager.setFocusedRootTask(taskId); 2850 } 2851 2852 /** Sets the task stack listener that gets callbacks when a task stack changes. */ 2853 @Override registerTaskStackListener(ITaskStackListener listener)2854 public void registerTaskStackListener(ITaskStackListener listener) { 2855 mActivityTaskManager.registerTaskStackListener(listener); 2856 } 2857 2858 /** 2859 * Unregister a task stack listener so that it stops receiving callbacks. 2860 */ 2861 @Override unregisterTaskStackListener(ITaskStackListener listener)2862 public void unregisterTaskStackListener(ITaskStackListener listener) { 2863 mActivityTaskManager.unregisterTaskStackListener(listener); 2864 } 2865 2866 @GuardedBy("this") updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2867 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2868 ProcessRecord client) { 2869 mProcessList.updateLruProcessLocked(app, activityChange, client); 2870 } 2871 2872 @GuardedBy("this") removeLruProcessLocked(ProcessRecord app)2873 final void removeLruProcessLocked(ProcessRecord app) { 2874 mProcessList.removeLruProcessLocked(app); 2875 } 2876 2877 @GuardedBy("this") getProcessRecordLocked(String processName, int uid)2878 final ProcessRecord getProcessRecordLocked(String processName, int uid) { 2879 return mProcessList.getProcessRecordLocked(processName, uid); 2880 } 2881 2882 @GuardedBy(anyOf = {"this", "mProcLock"}) getProcessNamesLOSP()2883 final ProcessMap<ProcessRecord> getProcessNamesLOSP() { 2884 return mProcessList.getProcessNamesLOSP(); 2885 } 2886 notifyPackageUse(String packageName, int reason)2887 void notifyPackageUse(String packageName, int reason) { 2888 getPackageManagerInternal().notifyPackageUse(packageName, reason); 2889 } 2890 startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2891 boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 2892 String processName, String abiOverride, int uid, Runnable crashHandler) { 2893 synchronized(this) { 2894 ApplicationInfo info = new ApplicationInfo(); 2895 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 2896 // For isolated processes, the former contains the parent's uid and the latter the 2897 // actual uid of the isolated process. 2898 // In the special case introduced by this method (which is, starting an isolated 2899 // process directly from the SystemServer without an actual parent app process) the 2900 // closest thing to a parent's uid is SYSTEM_UID. 2901 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 2902 // the |isolated| logic in the ProcessRecord constructor. 2903 info.uid = SYSTEM_UID; 2904 info.processName = processName; 2905 info.className = entryPoint; 2906 info.packageName = "android"; 2907 info.seInfoUser = SELinuxUtil.COMPLETE_STR; 2908 info.targetSdkVersion = Build.VERSION.SDK_INT; 2909 ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */, 2910 false /* knownToBeDead */, 0 /* intentFlags */, 2911 sNullHostingRecord /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY, 2912 true /* allowWhileBooting */, true /* isolated */, 2913 uid, false /* isSdkSandbox */, 0 /* sdkSandboxUid */, 2914 null /* sdkSandboxClientAppPackage */, 2915 abiOverride, entryPoint, entryPointArgs, crashHandler); 2916 return proc != null; 2917 } 2918 } 2919 2920 @GuardedBy("this") startSdkSandboxProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid, String sdkSandboxClientAppPackage)2921 final ProcessRecord startSdkSandboxProcessLocked(String processName, 2922 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2923 HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid, 2924 String sdkSandboxClientAppPackage) { 2925 return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, 2926 hostingRecord, zygotePolicyFlags, false /* allowWhileBooting */, 2927 false /* isolated */, 0 /* isolatedUid */, 2928 true /* isSdkSandbox */, sdkSandboxUid, sdkSandboxClientAppPackage, 2929 null /* ABI override */, null /* entryPoint */, 2930 null /* entryPointArgs */, null /* crashHandler */); 2931 } 2932 2933 @GuardedBy("this") startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated)2934 final ProcessRecord startProcessLocked(String processName, 2935 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2936 HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, 2937 boolean isolated) { 2938 return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, 2939 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */, 2940 false /* isSdkSandbox */, 0 /* sdkSandboxClientAppUid */, 2941 null /* sdkSandboxClientAppPackage */, 2942 null /* ABI override */, null /* entryPoint */, 2943 null /* entryPointArgs */, null /* crashHandler */); 2944 } 2945 isAllowedWhileBooting(ApplicationInfo ai)2946 boolean isAllowedWhileBooting(ApplicationInfo ai) { 2947 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 2948 } 2949 2950 /** 2951 * Update battery stats on the activity' usage. 2952 * @param activity 2953 * @param uid 2954 * @param userId 2955 * @param resumed 2956 */ updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)2957 void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) { 2958 if (DEBUG_SWITCH) { 2959 Slog.d(TAG_SWITCH, 2960 "updateBatteryStats: comp=" + activity + "res=" + resumed); 2961 } 2962 mBatteryStatsService.updateBatteryStatsOnActivityUsage(activity.getPackageName(), 2963 activity.getShortClassName(), uid, userId, resumed); 2964 } 2965 2966 /** 2967 * Update UsageStas on the activity's usage. 2968 * @param activity 2969 * @param userId 2970 * @param event 2971 * @param appToken ActivityRecord's appToken. 2972 * @param taskRoot Task's root 2973 */ updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)2974 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 2975 IBinder appToken, ComponentName taskRoot, ActivityId activityId) { 2976 if (DEBUG_SWITCH) { 2977 Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp=" 2978 + activity + " hash=" + appToken.hashCode() + " event=" + event); 2979 } 2980 if (mUsageStatsService != null) { 2981 mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(), taskRoot); 2982 if (event == Event.ACTIVITY_RESUMED) { 2983 // Report component usage as an activity is an app component 2984 mUsageStatsService.reportEvent( 2985 activity.getPackageName(), userId, Event.APP_COMPONENT_USED); 2986 } 2987 } 2988 ContentCaptureManagerInternal contentCaptureService = mContentCaptureService; 2989 if (contentCaptureService != null && (event == Event.ACTIVITY_PAUSED 2990 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED 2991 || event == Event.ACTIVITY_DESTROYED)) { 2992 contentCaptureService.notifyActivityEvent(userId, activity, event, activityId); 2993 } 2994 // Currently we have move most of logic to the client side. When the activity lifecycle 2995 // event changed, the client side will notify the VoiceInteractionManagerService. But 2996 // when the application process died, the VoiceInteractionManagerService will miss the 2997 // activity lifecycle event changed, so we still need ACTIVITY_DESTROYED event here to 2998 // know if the activity has been destroyed. 2999 if (mVoiceInteractionManagerProvider != null && event == Event.ACTIVITY_DESTROYED) { 3000 mVoiceInteractionManagerProvider.notifyActivityDestroyed(appToken); 3001 } 3002 } 3003 3004 /** 3005 * Update UsageStats on this package's usage. 3006 * @param packageName 3007 * @param userId 3008 * @param event 3009 */ updateActivityUsageStats(String packageName, int userId, int event)3010 public void updateActivityUsageStats(String packageName, int userId, int event) { 3011 if (DEBUG_SWITCH) { 3012 Slog.d(TAG_SWITCH, "updateActivityUsageStats: package=" 3013 + packageName + " event=" + event); 3014 } 3015 if (mUsageStatsService != null) { 3016 mUsageStatsService.reportEvent(packageName, userId, event); 3017 } 3018 } 3019 3020 /** 3021 * Update Usages on this foreground service's usage. 3022 * @param service 3023 * @param userId 3024 * @param started 3025 */ updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)3026 void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) { 3027 if (DEBUG_SWITCH) { 3028 Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp=" 3029 + service + " started=" + started); 3030 } 3031 if (mUsageStatsService != null) { 3032 mUsageStatsService.reportEvent(service, userId, 3033 started ? UsageEvents.Event.FOREGROUND_SERVICE_START 3034 : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null); 3035 } 3036 } 3037 3038 /** 3039 * Enforces that the uid that calls a method is not an 3040 * {@link UserHandle#isIsolated(int) isolated} uid. 3041 * 3042 * @param caller the name of the method being called. 3043 * @throws SecurityException if the calling uid is an isolated uid. 3044 */ enforceNotIsolatedCaller(String caller)3045 /* package */ void enforceNotIsolatedCaller(String caller) { 3046 if (UserHandle.isIsolated(Binder.getCallingUid())) { 3047 throw new SecurityException("Isolated process not allowed to call " + caller); 3048 } 3049 } 3050 3051 /** 3052 * Enforces that the uid that calls a method is not an 3053 * {@link UserHandle#isIsolated(int) isolated} uid or an 3054 * {@link Process#isSdkSandboxUid(int) SDK sandbox} uid. 3055 * 3056 * @param caller the name of the method being called. 3057 * @throws SecurityException if the calling uid is an isolated uid or SDK sandbox uid. 3058 */ enforceNotIsolatedOrSdkSandboxCaller(String caller)3059 void enforceNotIsolatedOrSdkSandboxCaller(String caller) { 3060 enforceNotIsolatedCaller(caller); 3061 3062 if (Process.isSdkSandboxUid(Binder.getCallingUid())) { 3063 throw new SecurityException("SDK sandbox process not allowed to call " + caller); 3064 } 3065 } 3066 3067 /** 3068 * If the caller is an {@link Process#isSdkSandboxUid(int) SDK sandbox uid}, enforces that the 3069 * SDK sandbox has permission to start or bind to a given service. 3070 * 3071 * @param intent the intent used to start or bind to the service. 3072 * @throws IllegalStateException if {@link SdkSandboxManagerLocal} cannot be resolved. 3073 * @throws SecurityException if the SDK sandbox is not allowed to bind to this service. 3074 */ enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent)3075 private void enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent) { 3076 if (Process.isSdkSandboxUid(Binder.getCallingUid())) { 3077 SdkSandboxManagerLocal sdkSandboxManagerLocal = 3078 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 3079 if (sdkSandboxManagerLocal != null) { 3080 sdkSandboxManagerLocal.enforceAllowedToStartOrBindService(intent); 3081 } else { 3082 throw new IllegalStateException("SdkSandboxManagerLocal not found when checking" 3083 + " whether SDK sandbox uid may start or bind to a service."); 3084 } 3085 } 3086 } 3087 3088 /** 3089 * Enforces that the uid of the caller matches the uid of the package. 3090 * 3091 * @param packageName the name of the package to match uid against. 3092 * @param callingUid the uid of the caller. 3093 * @throws SecurityException if the calling uid doesn't match uid of the package. 3094 */ enforceCallingPackage(String packageName, int callingUid)3095 private void enforceCallingPackage(String packageName, int callingUid) { 3096 final int userId = UserHandle.getUserId(callingUid); 3097 final int packageUid = getPackageManagerInternal().getPackageUid(packageName, 3098 /*flags=*/ 0, userId); 3099 if (packageUid != callingUid) { 3100 throw new SecurityException(packageName + " does not belong to uid " + callingUid); 3101 } 3102 } 3103 3104 @Override setPackageScreenCompatMode(String packageName, int mode)3105 public void setPackageScreenCompatMode(String packageName, int mode) { 3106 mActivityTaskManager.setPackageScreenCompatMode(packageName, mode); 3107 } 3108 hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid)3109 private boolean hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid) { 3110 final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS, 3111 callingUid, callingPackage, null, false, "", false).getOpMode(); 3112 if (mode == AppOpsManager.MODE_DEFAULT) { 3113 return checkPermission(Manifest.permission.PACKAGE_USAGE_STATS, callingPid, callingUid) 3114 == PackageManager.PERMISSION_GRANTED; 3115 } 3116 return mode == AppOpsManager.MODE_ALLOWED; 3117 } 3118 hasUsageStatsPermission(String callingPackage)3119 private boolean hasUsageStatsPermission(String callingPackage) { 3120 return hasUsageStatsPermission(callingPackage, 3121 Binder.getCallingUid(), Binder.getCallingPid()); 3122 } 3123 enforceUsageStatsPermission(String callingPackage, int callingUid, int callingPid, String operation)3124 private void enforceUsageStatsPermission(String callingPackage, 3125 int callingUid, int callingPid, String operation) { 3126 if (!hasUsageStatsPermission(callingPackage, callingUid, callingPid)) { 3127 final String errorMsg = "Permission denial for <" + operation + "> from pid=" 3128 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3129 + " which requires PACKAGE_USAGE_STATS permission"; 3130 throw new SecurityException(errorMsg); 3131 } 3132 } 3133 3134 @Override getPackageProcessState(String packageName, String callingPackage)3135 public int getPackageProcessState(String packageName, String callingPackage) { 3136 if (!hasUsageStatsPermission(callingPackage)) { 3137 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 3138 "getPackageProcessState"); 3139 } 3140 3141 final int[] procState = {PROCESS_STATE_NONEXISTENT}; 3142 synchronized (mProcLock) { 3143 mProcessList.forEachLruProcessesLOSP(false, proc -> { 3144 if (procState[0] > proc.mState.getSetProcState()) { 3145 if (proc.getPkgList().containsKey(packageName) || (proc.getPkgDeps() != null 3146 && proc.getPkgDeps().contains(packageName))) { 3147 procState[0] = proc.mState.getSetProcState(); 3148 } 3149 } 3150 }); 3151 } 3152 return procState[0]; 3153 } 3154 3155 @Override setProcessMemoryTrimLevel(String process, int userId, int level)3156 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) 3157 throws RemoteException { 3158 if (!isCallerShell()) { 3159 throw new SecurityException("Only shell can call it"); 3160 } 3161 synchronized (this) { 3162 final ProcessRecord app = findProcessLOSP(process, userId, "setProcessMemoryTrimLevel"); 3163 if (app == null) { 3164 throw new IllegalArgumentException("Unknown process: " + process); 3165 } 3166 final IApplicationThread thread = app.getThread(); 3167 if (thread == null) { 3168 throw new IllegalArgumentException("Process has no app thread"); 3169 } 3170 if (app.mProfile.getTrimMemoryLevel() >= level) { 3171 throw new IllegalArgumentException( 3172 "Unable to set a higher trim level than current level"); 3173 } 3174 if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || 3175 app.mState.getCurProcState() > PROCESS_STATE_IMPORTANT_FOREGROUND)) { 3176 throw new IllegalArgumentException("Unable to set a background trim level " 3177 + "on a foreground process"); 3178 } 3179 thread.scheduleTrimMemory(level); 3180 synchronized (mProcLock) { 3181 app.mProfile.setTrimMemoryLevel(level); 3182 } 3183 return true; 3184 } 3185 } 3186 dispatchOomAdjObserver(String msg)3187 void dispatchOomAdjObserver(String msg) { 3188 OomAdjObserver observer; 3189 synchronized (mOomAdjObserverLock) { 3190 observer = mCurOomAdjObserver; 3191 } 3192 3193 if (observer != null) { 3194 observer.onOomAdjMessage(msg); 3195 } 3196 } 3197 setOomAdjObserver(int uid, OomAdjObserver observer)3198 void setOomAdjObserver(int uid, OomAdjObserver observer) { 3199 synchronized (mOomAdjObserverLock) { 3200 mCurOomAdjUid = uid; 3201 mCurOomAdjObserver = observer; 3202 } 3203 } 3204 clearOomAdjObserver()3205 void clearOomAdjObserver() { 3206 synchronized (mOomAdjObserverLock) { 3207 mCurOomAdjUid = -1; 3208 mCurOomAdjObserver = null; 3209 } 3210 } 3211 reportUidInfoMessageLocked(String tag, String msg, int uid)3212 void reportUidInfoMessageLocked(String tag, String msg, int uid) { 3213 Slog.i(TAG, msg); 3214 synchronized (mOomAdjObserverLock) { 3215 if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) { 3216 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget(); 3217 } 3218 } 3219 } 3220 3221 /** 3222 * @deprecated use {@link #startActivityWithFeature} instead 3223 */ 3224 @Deprecated 3225 @Override startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3226 public int startActivity(IApplicationThread caller, String callingPackage, 3227 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3228 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { 3229 return mActivityTaskManager.startActivity(caller, callingPackage, null, intent, 3230 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 3231 } 3232 3233 @Override startActivityWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3234 public int startActivityWithFeature(IApplicationThread caller, String callingPackage, 3235 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, 3236 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, 3237 Bundle bOptions) { 3238 return mActivityTaskManager.startActivity(caller, callingPackage, callingFeatureId, intent, 3239 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 3240 } 3241 3242 /** 3243 * @deprecated use {@link #startActivityAsUserWithFeature} instead 3244 */ 3245 @Deprecated 3246 @Override startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3247 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 3248 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3249 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 3250 return startActivityAsUserWithFeature(caller, callingPackage, null, intent, resolvedType, 3251 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId); 3252 } 3253 3254 @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)3255 public final int startActivityAsUserWithFeature(IApplicationThread caller, 3256 String callingPackage, String callingFeatureId, Intent intent, String resolvedType, 3257 IBinder resultTo, String resultWho, int requestCode, int startFlags, 3258 ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 3259 return mActivityTaskManager.startActivityAsUser(caller, callingPackage, 3260 callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, 3261 startFlags, profilerInfo, bOptions, userId); 3262 } 3263 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)3264 WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 3265 @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, 3266 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, 3267 Bundle bOptions, int userId) { 3268 return mActivityTaskManager.startActivityAndWait(caller, callingPackage, 3269 callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, 3270 startFlags, profilerInfo, bOptions, userId); 3271 } 3272 3273 @Override startActivityFromRecents(int taskId, Bundle bOptions)3274 public final int startActivityFromRecents(int taskId, Bundle bOptions) { 3275 return mActivityTaskManager.startActivityFromRecents(taskId, bOptions); 3276 } 3277 3278 /** 3279 * This is the internal entry point for handling Activity.finish(). 3280 * 3281 * @param token The Binder token referencing the Activity we want to finish. 3282 * @param resultCode Result code, if any, from this Activity. 3283 * @param resultData Result data (Intent), if any, from this Activity. 3284 * @param finishTask Whether to finish the task associated with this Activity. 3285 * 3286 * @return Returns true if the activity successfully finished, or false if it is still running. 3287 */ 3288 @Override finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3289 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 3290 int finishTask) { 3291 return ActivityClient.getInstance().finishActivity(token, resultCode, resultData, 3292 finishTask); 3293 } 3294 3295 @Override setRequestedOrientation(IBinder token, int requestedOrientation)3296 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 3297 ActivityClient.getInstance().setRequestedOrientation(token, requestedOrientation); 3298 } 3299 3300 @Override finishHeavyWeightApp()3301 public final void finishHeavyWeightApp() { 3302 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3303 != PackageManager.PERMISSION_GRANTED) { 3304 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 3305 + Binder.getCallingPid() 3306 + ", uid=" + Binder.getCallingUid() 3307 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3308 Slog.w(TAG, msg); 3309 throw new SecurityException(msg); 3310 } 3311 mAtmInternal.finishHeavyWeightApp(); 3312 } 3313 3314 @Override crashApplicationWithType(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId)3315 public void crashApplicationWithType(int uid, int initialPid, String packageName, int userId, 3316 String message, boolean force, int exceptionTypeId) { 3317 crashApplicationWithTypeWithExtras(uid, initialPid, packageName, userId, message, 3318 force, exceptionTypeId, null); 3319 } 3320 3321 @Override crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId, @Nullable Bundle extras)3322 public void crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, 3323 int userId, String message, boolean force, int exceptionTypeId, 3324 @Nullable Bundle extras) { 3325 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3326 != PackageManager.PERMISSION_GRANTED) { 3327 String msg = "Permission Denial: crashApplication() from pid=" 3328 + Binder.getCallingPid() 3329 + ", uid=" + Binder.getCallingUid() 3330 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3331 Slog.w(TAG, msg); 3332 throw new SecurityException(msg); 3333 } 3334 3335 synchronized(this) { 3336 mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId, 3337 message, force, exceptionTypeId, extras); 3338 } 3339 } 3340 3341 /** 3342 * Main function for removing an existing process from the activity manager 3343 * as a result of that process going away. Clears out all connections 3344 * to the process. 3345 */ 3346 @GuardedBy("this") handleAppDiedLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, boolean fromBinderDied)3347 final void handleAppDiedLocked(ProcessRecord app, int pid, 3348 boolean restarting, boolean allowRestart, boolean fromBinderDied) { 3349 boolean kept = cleanUpApplicationRecordLocked(app, pid, restarting, allowRestart, -1, 3350 false /*replacingPid*/, fromBinderDied); 3351 if (!kept && !restarting) { 3352 removeLruProcessLocked(app); 3353 if (pid > 0) { 3354 ProcessList.remove(pid); 3355 } 3356 } 3357 3358 mAppProfiler.onAppDiedLocked(app); 3359 3360 mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> { 3361 Slog.w(TAG, "Crash of app " + app.processName 3362 + " running instrumentation " + app.getActiveInstrumentation().mClass); 3363 Bundle info = new Bundle(); 3364 info.putString("shortMsg", "Process crashed."); 3365 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 3366 }); 3367 } 3368 3369 @GuardedBy(anyOf = {"this", "mProcLock"}) getRecordForAppLOSP(IApplicationThread thread)3370 ProcessRecord getRecordForAppLOSP(IApplicationThread thread) { 3371 if (thread == null) { 3372 return null; 3373 } 3374 return getRecordForAppLOSP(thread.asBinder()); 3375 } 3376 3377 @GuardedBy(anyOf = {"this", "mProcLock"}) getRecordForAppLOSP(IBinder threadBinder)3378 ProcessRecord getRecordForAppLOSP(IBinder threadBinder) { 3379 if (threadBinder == null) { 3380 return null; 3381 } 3382 3383 ProcessRecord record = mProcessList.getLRURecordForAppLOSP(threadBinder); 3384 if (record != null) return record; 3385 3386 // Validation: if it isn't in the LRU list, it shouldn't exist, but let's double-check that. 3387 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 3388 mProcessList.getProcessNamesLOSP().getMap(); 3389 for (int i = pmap.size()-1; i >= 0; i--) { 3390 final SparseArray<ProcessRecord> procs = pmap.valueAt(i); 3391 for (int j = procs.size()-1; j >= 0; j--) { 3392 final ProcessRecord proc = procs.valueAt(j); 3393 final IApplicationThread procThread = proc.getThread(); 3394 if (procThread != null && procThread.asBinder() == threadBinder) { 3395 if (!proc.isPendingFinishAttach()) { 3396 Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: " 3397 + proc); 3398 } 3399 return proc; 3400 } 3401 } 3402 } 3403 3404 return null; 3405 } 3406 3407 @GuardedBy("this") appDiedLocked(ProcessRecord app, String reason)3408 final void appDiedLocked(ProcessRecord app, String reason) { 3409 appDiedLocked(app, app.getPid(), app.getThread(), false, reason); 3410 } 3411 3412 @GuardedBy("this") appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied, String reason)3413 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, 3414 boolean fromBinderDied, String reason) { 3415 // First check if this ProcessRecord is actually active for the pid. 3416 final ProcessRecord curProc; 3417 synchronized (mPidsSelfLocked) { 3418 curProc = mPidsSelfLocked.get(pid); 3419 } 3420 if (curProc != app) { 3421 if (!fromBinderDied || !mProcessList.handleDyingAppDeathLocked(app, pid)) { 3422 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc); 3423 } 3424 return; 3425 } 3426 3427 mBatteryStatsService.noteProcessDied(app.info.uid, pid); 3428 3429 if (!app.isKilled()) { 3430 if (!fromBinderDied) { 3431 killProcessQuiet(pid); 3432 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_OTHER, 3433 ApplicationExitInfo.SUBREASON_UNKNOWN, reason); 3434 } 3435 app.killProcessGroupIfNecessaryLocked(true); 3436 synchronized (mProcLock) { 3437 app.setKilled(true); 3438 } 3439 } 3440 3441 // Clean up already done if the process has been re-started. 3442 IApplicationThread appThread; 3443 final int setAdj = app.mState.getSetAdj(); 3444 final int setProcState = app.mState.getSetProcState(); 3445 if (app.getPid() == pid && (appThread = app.getThread()) != null 3446 && appThread.asBinder() == thread.asBinder()) { 3447 boolean doLowMem = app.getActiveInstrumentation() == null; 3448 boolean doOomAdj = doLowMem; 3449 if (!app.isKilledByAm()) { 3450 reportUidInfoMessageLocked(TAG, 3451 "Process " + app.processName + " (pid " + pid + ") has died: " 3452 + ProcessList.makeOomAdjString(setAdj, true) + " " 3453 + ProcessList.makeProcStateString(setProcState), app.info.uid); 3454 mAppProfiler.setAllowLowerMemLevelLocked(true); 3455 } else { 3456 // Note that we always want to do oom adj to update our state with the 3457 // new number of procs. 3458 mAppProfiler.setAllowLowerMemLevelLocked(false); 3459 doLowMem = false; 3460 } 3461 if (doOomAdj) { 3462 if (Flags.migrateFullOomadjUpdates()) { 3463 app.forEachConnectionHost((host) -> enqueueOomAdjTargetLocked(host)); 3464 } 3465 } 3466 3467 EventLogTags.writeAmProcDied(app.userId, pid, app.processName, setAdj, setProcState); 3468 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 3469 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder()); 3470 handleAppDiedLocked(app, pid, false, true, fromBinderDied); 3471 3472 if (doOomAdj) { 3473 if (Flags.migrateFullOomadjUpdates()) { 3474 updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_PROCESS_END); 3475 } else { 3476 updateOomAdjLocked(OOM_ADJ_REASON_PROCESS_END); 3477 } 3478 } 3479 if (doLowMem) { 3480 mAppProfiler.doLowMemReportIfNeededLocked(app); 3481 } 3482 } else if (app.getPid() != pid) { 3483 // A new process has already been started. 3484 reportUidInfoMessageLocked(TAG, 3485 "Process " + app.processName + " (pid " + pid 3486 + ") has died and restarted (pid " + app.getPid() + ").", app.info.uid); 3487 3488 EventLogTags.writeAmProcDied(app.userId, app.getPid(), app.processName, 3489 setAdj, setProcState); 3490 } else if (DEBUG_PROCESSES) { 3491 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread " 3492 + thread.asBinder()); 3493 } 3494 3495 // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal 3496 // for pulling memory stats of other running processes when this process died. 3497 if (!hasMemcg()) { 3498 FrameworkStatsLog.write(FrameworkStatsLog.APP_DIED, SystemClock.elapsedRealtime()); 3499 } 3500 } 3501 3502 @Override clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)3503 public boolean clearApplicationUserData(final String packageName, boolean keepState, 3504 final IPackageDataObserver observer, int userId) { 3505 return clearApplicationUserData(packageName, keepState, /*isRestore=*/ false, observer, 3506 userId); 3507 } 3508 clearApplicationUserData(final String packageName, boolean keepState, boolean isRestore, final IPackageDataObserver observer, int userId)3509 private boolean clearApplicationUserData(final String packageName, boolean keepState, 3510 boolean isRestore, final IPackageDataObserver observer, int userId) { 3511 enforceNotIsolatedCaller("clearApplicationUserData"); 3512 int uid = Binder.getCallingUid(); 3513 int pid = Binder.getCallingPid(); 3514 EventLog.writeEvent(EventLogTags.AM_CLEAR_APP_DATA_CALLER, pid, uid, packageName); 3515 final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false, 3516 ALLOW_FULL_ONLY, "clearApplicationUserData", null); 3517 3518 final ApplicationInfo appInfo; 3519 final boolean isInstantApp; 3520 3521 final long callingId = Binder.clearCallingIdentity(); 3522 try { 3523 IPackageManager pm = AppGlobals.getPackageManager(); 3524 boolean permitted = true; 3525 // Instant packages are not protected 3526 if (getPackageManagerInternal().isPackageDataProtected( 3527 resolvedUserId, packageName)) { 3528 if (ActivityManager.checkUidPermission(android.Manifest.permission.MANAGE_USERS, 3529 uid) == PERMISSION_GRANTED) { 3530 // The caller has the MANAGE_USERS permission, tell them what's going on. 3531 throw new SecurityException( 3532 "Cannot clear data for a protected package: " + packageName); 3533 } else { 3534 permitted = false; // fall through and throw the SecurityException below. 3535 } 3536 } 3537 3538 ApplicationInfo applicationInfo = null; 3539 if (permitted) { 3540 try { 3541 applicationInfo = pm.getApplicationInfo(packageName, 3542 MATCH_UNINSTALLED_PACKAGES, resolvedUserId); 3543 } catch (RemoteException e) { 3544 /* ignore */ 3545 } 3546 permitted = (applicationInfo != null && applicationInfo.uid == uid) // own uid data 3547 || (checkComponentPermission(permission.CLEAR_APP_USER_DATA, 3548 pid, uid, -1, true) == PackageManager.PERMISSION_GRANTED); 3549 } 3550 3551 if (!permitted) { 3552 throw new SecurityException("PID " + pid + " does not have permission " 3553 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 3554 + " of package " + packageName); 3555 } 3556 appInfo = applicationInfo; 3557 3558 final boolean hasInstantMetadata = getPackageManagerInternal() 3559 .hasInstantApplicationMetadata(packageName, resolvedUserId); 3560 final boolean isUninstalledAppWithoutInstantMetadata = 3561 (appInfo == null && !hasInstantMetadata); 3562 isInstantApp = (appInfo != null && appInfo.isInstantApp()) 3563 || hasInstantMetadata; 3564 final boolean canAccessInstantApps = checkComponentPermission( 3565 permission.ACCESS_INSTANT_APPS, pid, uid, -1, true) 3566 == PackageManager.PERMISSION_GRANTED; 3567 3568 if (isUninstalledAppWithoutInstantMetadata || (isInstantApp 3569 && !canAccessInstantApps)) { 3570 Slog.w(TAG, "Invalid packageName: " + packageName); 3571 if (observer != null) { 3572 try { 3573 observer.onRemoveCompleted(packageName, false); 3574 } catch (RemoteException e) { 3575 Slog.i(TAG, "Observer no longer exists."); 3576 } 3577 } 3578 return false; 3579 } 3580 3581 synchronized (this) { 3582 if (appInfo != null) { 3583 forceStopPackageLocked(packageName, appInfo.uid, "clear data"); 3584 mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId); 3585 } 3586 } 3587 3588 final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() { 3589 @Override 3590 public void onRemoveCompleted(String packageName, boolean succeeded) 3591 throws RemoteException { 3592 if (appInfo != null) { 3593 synchronized (ActivityManagerService.this) { 3594 finishForceStopPackageLocked(packageName, appInfo.uid); 3595 } 3596 } 3597 3598 if (succeeded) { 3599 3600 mPackageManagerInt.sendPackageDataClearedBroadcast(packageName, 3601 ((appInfo != null) ? appInfo.uid : INVALID_UID), resolvedUserId, 3602 isRestore, isInstantApp); 3603 } 3604 3605 if (observer != null) { 3606 observer.onRemoveCompleted(packageName, succeeded); 3607 } 3608 } 3609 }; 3610 3611 try { 3612 // Clear application user data 3613 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId); 3614 3615 if (appInfo != null) { 3616 // Restore already established notification state and permission grants, 3617 // so it told us to keep those intact -- it's about to emplace app data 3618 // that is appropriate for those bits of system state. 3619 if (!keepState) { 3620 // Remove all permissions granted from/to this package 3621 mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId, 3622 true, false); 3623 3624 // Reset notification state 3625 INotificationManager inm = NotificationManager.getService(); 3626 inm.clearData(packageName, appInfo.uid, uid == appInfo.uid); 3627 } 3628 3629 // Clear its scheduled jobs 3630 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 3631 // Clearing data is a user-initiated action. 3632 js.cancelJobsForUid(appInfo.uid, /* includeProxiedJobs */ true, 3633 JobParameters.STOP_REASON_USER, 3634 JobParameters.INTERNAL_STOP_REASON_DATA_CLEARED, "clear data"); 3635 3636 // Clear its pending alarms 3637 AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class); 3638 ami.removeAlarmsForUid(appInfo.uid); 3639 } 3640 } catch (RemoteException e) { 3641 } 3642 } finally { 3643 Binder.restoreCallingIdentity(callingId); 3644 } 3645 return true; 3646 } 3647 3648 @Override killBackgroundProcesses(final String packageName, int userId)3649 public void killBackgroundProcesses(final String packageName, int userId) { 3650 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3651 != PackageManager.PERMISSION_GRANTED && 3652 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 3653 != PackageManager.PERMISSION_GRANTED) { 3654 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 3655 + Binder.getCallingPid() 3656 + ", uid=" + Binder.getCallingUid() 3657 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3658 Slog.w(TAG, msg); 3659 throw new SecurityException(msg); 3660 } 3661 final boolean hasKillAllPermission = checkCallingPermission( 3662 android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES) == PERMISSION_GRANTED; 3663 final int callingUid = Binder.getCallingUid(); 3664 final int callingAppId = UserHandle.getAppId(callingUid); 3665 3666 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, 3667 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 3668 final int[] userIds = mUserController.expandUserId(userId); 3669 3670 final long callingId = Binder.clearCallingIdentity(); 3671 try { 3672 IPackageManager pm = AppGlobals.getPackageManager(); 3673 for (int targetUserId : userIds) { 3674 int appId = -1; 3675 try { 3676 appId = UserHandle.getAppId( 3677 pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 3678 targetUserId)); 3679 } catch (RemoteException e) { 3680 } 3681 if (appId == -1 || (!hasKillAllPermission && appId != callingAppId)) { 3682 Slog.w(TAG, "Invalid packageName: " + packageName); 3683 return; 3684 } 3685 synchronized (this) { 3686 synchronized (mProcLock) { 3687 mProcessList.killPackageProcessesLSP(packageName, appId, targetUserId, 3688 ProcessList.SERVICE_ADJ, ApplicationExitInfo.REASON_USER_REQUESTED, 3689 ApplicationExitInfo.SUBREASON_KILL_BACKGROUND, "kill background"); 3690 } 3691 } 3692 } 3693 } finally { 3694 Binder.restoreCallingIdentity(callingId); 3695 } 3696 } 3697 3698 @Override killAllBackgroundProcesses()3699 public void killAllBackgroundProcesses() { 3700 if (checkCallingPermission(android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES) 3701 != PackageManager.PERMISSION_GRANTED) { 3702 final String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 3703 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3704 + " requires " + android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES; 3705 Slog.w(TAG, msg); 3706 throw new SecurityException(msg); 3707 } 3708 3709 final long callingId = Binder.clearCallingIdentity(); 3710 try { 3711 synchronized (this) { 3712 // Allow memory level to go down (the flag needs to be set before updating oom adj) 3713 // because this method is also used to simulate low memory. 3714 mAppProfiler.setAllowLowerMemLevelLocked(true); 3715 synchronized (mProcLock) { 3716 mProcessList.killPackageProcessesLSP(null /* packageName */, -1 /* appId */, 3717 UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ, 3718 ApplicationExitInfo.REASON_USER_REQUESTED, 3719 ApplicationExitInfo.SUBREASON_KILL_BACKGROUND, 3720 "kill all background"); 3721 } 3722 3723 mAppProfiler.doLowMemReportIfNeededLocked(null); 3724 } 3725 } finally { 3726 Binder.restoreCallingIdentity(callingId); 3727 } 3728 } 3729 3730 /** 3731 * Kills all background processes, except those matching any of the 3732 * specified properties. 3733 * 3734 * @param minTargetSdk the target SDK version at or above which to preserve 3735 * processes, or {@code -1} to ignore the target SDK 3736 * @param maxProcState the process state at or below which to preserve 3737 * processes, or {@code -1} to ignore the process state 3738 */ killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)3739 void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 3740 if (checkCallingPermission(android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES) 3741 != PackageManager.PERMISSION_GRANTED) { 3742 final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid=" 3743 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3744 + " requires " + android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES; 3745 Slog.w(TAG, msg); 3746 throw new SecurityException(msg); 3747 } 3748 3749 final long callingId = Binder.clearCallingIdentity(); 3750 try { 3751 synchronized (this) { 3752 synchronized (mProcLock) { 3753 mProcessList.killAllBackgroundProcessesExceptLSP(minTargetSdk, maxProcState); 3754 } 3755 } 3756 } finally { 3757 Binder.restoreCallingIdentity(callingId); 3758 } 3759 } 3760 3761 @Override stopAppForUser(final String packageName, int userId)3762 public void stopAppForUser(final String packageName, int userId) { 3763 if (checkCallingPermission(MANAGE_ACTIVITY_TASKS) 3764 != PackageManager.PERMISSION_GRANTED) { 3765 String msg = "Permission Denial: stopAppForUser() from pid=" 3766 + Binder.getCallingPid() 3767 + ", uid=" + Binder.getCallingUid() 3768 + " requires " + MANAGE_ACTIVITY_TASKS; 3769 Slog.w(TAG, msg); 3770 throw new SecurityException(msg); 3771 } 3772 3773 final int callingPid = Binder.getCallingPid(); 3774 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 3775 userId, true, ALLOW_FULL_ONLY, "stopAppForUser", null); 3776 final long callingId = Binder.clearCallingIdentity(); 3777 try { 3778 stopAppForUserInternal(packageName, userId); 3779 } finally { 3780 Binder.restoreCallingIdentity(callingId); 3781 } 3782 } 3783 3784 @Override registerForegroundServiceObserver(IForegroundServiceObserver callback)3785 public boolean registerForegroundServiceObserver(IForegroundServiceObserver callback) { 3786 final int callingUid = Binder.getCallingUid(); 3787 final int permActivityTasks = checkCallingPermission(MANAGE_ACTIVITY_TASKS); 3788 final int permAcrossUsersFull = checkCallingPermission(INTERACT_ACROSS_USERS_FULL); 3789 if (permActivityTasks != PackageManager.PERMISSION_GRANTED 3790 || permAcrossUsersFull != PERMISSION_GRANTED) { 3791 String msg = "Permission Denial: registerForegroundServiceObserver() from pid=" 3792 + Binder.getCallingPid() 3793 + ", uid=" + callingUid 3794 + " requires " + MANAGE_ACTIVITY_TASKS 3795 + " and " + INTERACT_ACROSS_USERS_FULL; 3796 Slog.w(TAG, msg); 3797 throw new SecurityException(msg); 3798 } 3799 3800 synchronized (this) { 3801 return mServices.registerForegroundServiceObserverLocked(callingUid, callback); 3802 } 3803 } 3804 3805 @Override forceStopPackage(final String packageName, int userId)3806 public void forceStopPackage(final String packageName, int userId) { 3807 forceStopPackage(packageName, userId, /*flags=*/ 0, null); 3808 } 3809 3810 @Override forceStopPackageEvenWhenStopping(final String packageName, int userId)3811 public void forceStopPackageEvenWhenStopping(final String packageName, int userId) { 3812 forceStopPackage(packageName, userId, ActivityManager.FLAG_OR_STOPPED, null); 3813 } 3814 forceStopPackage(final String packageName, int userId, int userRunningFlags, String reason)3815 void forceStopPackage(final String packageName, int userId, int userRunningFlags, 3816 String reason) { 3817 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3818 != PackageManager.PERMISSION_GRANTED) { 3819 String msg = "Permission Denial: forceStopPackage() from pid=" 3820 + Binder.getCallingPid() 3821 + ", uid=" + Binder.getCallingUid() 3822 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3823 Slog.w(TAG, msg); 3824 throw new SecurityException(msg); 3825 } 3826 final int callingPid = Binder.getCallingPid(); 3827 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 3828 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 3829 final long callingId = Binder.clearCallingIdentity(); 3830 try { 3831 IPackageManager pm = AppGlobals.getPackageManager(); 3832 synchronized (this) { 3833 int[] users = userId == UserHandle.USER_ALL 3834 ? mUserController.getUsers() : new int[] { userId }; 3835 for (int user : users) { 3836 if (getPackageManagerInternal().isPackageStateProtected( 3837 packageName, user)) { 3838 Slog.w(TAG, "Ignoring request to force stop protected package " 3839 + packageName + " u" + user); 3840 return; 3841 } 3842 3843 int pkgUid = -1; 3844 try { 3845 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 3846 user); 3847 } catch (RemoteException e) { 3848 } 3849 if (pkgUid == -1) { 3850 Slog.w(TAG, "Invalid packageName: " + packageName); 3851 continue; 3852 } 3853 try { 3854 pm.setPackageStoppedState(packageName, true, user); 3855 } catch (RemoteException e) { 3856 } catch (IllegalArgumentException e) { 3857 Slog.w(TAG, "Failed trying to unstop package " 3858 + packageName + ": " + e); 3859 } 3860 if (mUserController.isUserRunning(user, userRunningFlags)) { 3861 3862 String description; 3863 if (reason == null) { 3864 description = "from pid " + callingPid; 3865 3866 // Add the name of the process if it's available 3867 final ProcessRecord callerApp; 3868 synchronized (mPidsSelfLocked) { 3869 callerApp = mPidsSelfLocked.get(callingPid); 3870 } 3871 if (callerApp != null) { 3872 description += " (" + callerApp.processName + ")"; 3873 } 3874 } else { 3875 description = reason; 3876 } 3877 3878 forceStopPackageLocked(packageName, UserHandle.getAppId(pkgUid), 3879 false /* callerWillRestart */, false /* purgeCache */, 3880 true /* doIt */, false /* evenPersistent */, 3881 false /* uninstalling */, true /* packageStateStopped */, 3882 user, description); 3883 finishForceStopPackageLocked(packageName, pkgUid); 3884 } 3885 } 3886 } 3887 } finally { 3888 Binder.restoreCallingIdentity(callingId); 3889 } 3890 } 3891 3892 @Override addPackageDependency(String packageName)3893 public void addPackageDependency(String packageName) { 3894 int callingPid = Binder.getCallingPid(); 3895 if (callingPid == myPid()) { 3896 // Yeah, um, no. 3897 return; 3898 } 3899 final int callingUid = Binder.getCallingUid(); 3900 final int callingUserId = UserHandle.getUserId(callingUid); 3901 if (getPackageManagerInternal().filterAppAccess(packageName, callingUid, callingUserId)) { 3902 Slog.w(TAG, "Failed trying to add dependency on non-existing package: " + packageName); 3903 return; 3904 } 3905 ProcessRecord proc; 3906 synchronized (mPidsSelfLocked) { 3907 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 3908 } 3909 if (proc != null) { 3910 ArraySet<String> pkgDeps = proc.getPkgDeps(); 3911 synchronized (this) { 3912 synchronized (mProcLock) { 3913 if (pkgDeps == null) { 3914 proc.setPkgDeps(pkgDeps = new ArraySet<String>(1)); 3915 } 3916 pkgDeps.add(packageName); 3917 } 3918 } 3919 } 3920 } 3921 3922 /* 3923 * The pkg name and app id have to be specified. 3924 */ 3925 @Override killApplication(String pkg, int appId, @CanBeALL @UserIdInt int userId, String reason, int exitInfoReason)3926 public void killApplication(String pkg, int appId, @CanBeALL @UserIdInt int userId, 3927 String reason, int exitInfoReason) { 3928 if (pkg == null) { 3929 return; 3930 } 3931 // Make sure the uid is valid. 3932 if (appId < 0) { 3933 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 3934 return; 3935 } 3936 int callerUid = Binder.getCallingUid(); 3937 // Only the system server can kill an application 3938 if (UserHandle.getAppId(callerUid) == SYSTEM_UID) { 3939 // Post an aysnc message to kill the application 3940 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 3941 msg.arg1 = appId; 3942 msg.arg2 = userId; 3943 SomeArgs args = SomeArgs.obtain(); 3944 args.arg1 = pkg; 3945 args.arg2 = reason; 3946 args.arg3 = exitInfoReason; 3947 msg.obj = args; 3948 mHandler.sendMessage(msg); 3949 } else { 3950 throw new SecurityException(callerUid + " cannot kill pkg: " + 3951 pkg); 3952 } 3953 } 3954 3955 @Override closeSystemDialogs(String reason)3956 public void closeSystemDialogs(String reason) { 3957 mAtmInternal.closeSystemDialogs(reason); 3958 } 3959 3960 @Override getProcessMemoryInfo(int[] pids)3961 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 3962 enforceNotIsolatedCaller("getProcessMemoryInfo"); 3963 3964 final long now = SystemClock.uptimeMillis(); 3965 final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME; 3966 3967 final int callingPid = Binder.getCallingPid(); 3968 final int callingUid = Binder.getCallingUid(); 3969 final int callingUserId = UserHandle.getUserId(callingUid); 3970 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 3971 callingUid) == PackageManager.PERMISSION_GRANTED; 3972 // Check REAL_GET_TASKS to see if they are allowed to access other uids 3973 final boolean allUids = mAtmInternal.isGetTasksAllowed( 3974 "getProcessMemoryInfo", callingPid, callingUid); 3975 3976 // Check if the caller is actually instrumented and from shell, if it's true, we may lift 3977 // the throttle of PSS info sampling. 3978 boolean isCallerInstrumentedFromShell = false; 3979 synchronized (mProcLock) { 3980 synchronized (mPidsSelfLocked) { 3981 ProcessRecord caller = mPidsSelfLocked.get(callingPid); 3982 if (caller != null) { 3983 final ActiveInstrumentation instr = caller.getActiveInstrumentation(); 3984 isCallerInstrumentedFromShell = instr != null 3985 && (instr.mSourceUid == SHELL_UID || instr.mSourceUid == ROOT_UID); 3986 } 3987 } 3988 } 3989 3990 final Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 3991 for (int i=pids.length-1; i>=0; i--) { 3992 final Debug.MemoryInfo mi = infos[i] = new Debug.MemoryInfo(); 3993 final ProcessRecord proc; 3994 final int oomAdj; 3995 final ProcessProfileRecord profile; 3996 synchronized (mAppProfiler.mProfilerLock) { 3997 synchronized (mPidsSelfLocked) { 3998 proc = mPidsSelfLocked.get(pids[i]); 3999 if (proc != null) { 4000 profile = proc.mProfile; 4001 oomAdj = profile.getSetAdj(); 4002 } else { 4003 profile = null; 4004 oomAdj = 0; 4005 } 4006 } 4007 } 4008 final int targetUid = (proc != null) ? proc.uid : -1; 4009 final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1; 4010 4011 if (callingUid != targetUid) { 4012 if (!allUids) { 4013 continue; // Not allowed to see other UIDs. 4014 } 4015 4016 if (!allUsers && (targetUserId != callingUserId)) { 4017 continue; // Not allowed to see other users. 4018 } 4019 } 4020 if (proc != null) { 4021 synchronized (mAppProfiler.mProfilerLock) { 4022 if (profile.getLastMemInfoTime() >= lastNow && profile.getLastMemInfo() != null 4023 && !isCallerInstrumentedFromShell) { 4024 // It hasn't been long enough that we want to take another sample; return 4025 // the last one. 4026 mi.set(profile.getLastMemInfo()); 4027 continue; 4028 } 4029 } 4030 } 4031 final long startTime = SystemClock.currentThreadTimeMillis(); 4032 final Debug.MemoryInfo memInfo = new Debug.MemoryInfo(); 4033 Debug.getMemoryInfo(pids[i], memInfo); 4034 final long duration = SystemClock.currentThreadTimeMillis() - startTime; 4035 mi.set(memInfo); 4036 if (proc != null) { 4037 synchronized (mAppProfiler.mProfilerLock) { 4038 profile.setLastMemInfo(memInfo); 4039 profile.setLastMemInfoTime(SystemClock.uptimeMillis()); 4040 if (profile.getThread() != null && profile.getSetAdj() == oomAdj) { 4041 // Record this for posterity if the process has been stable. 4042 profile.addPss(mi.getTotalPss(), 4043 mi.getTotalUss(), mi.getTotalRss(), false, 4044 ProcessStats.ADD_PSS_EXTERNAL_SLOW, duration); 4045 } 4046 } 4047 } 4048 } 4049 return infos; 4050 } 4051 4052 @Override getProcessPss(int[] pids)4053 public long[] getProcessPss(int[] pids) { 4054 enforceNotIsolatedCaller("getProcessPss"); 4055 4056 final int callingPid = Binder.getCallingPid(); 4057 final int callingUid = Binder.getCallingUid(); 4058 final int userId = UserHandle.getUserId(callingUid); 4059 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 4060 callingUid) == PackageManager.PERMISSION_GRANTED; 4061 // Check REAL_GET_TASKS to see if they are allowed to access other uids 4062 final boolean allUids = mAtmInternal.isGetTasksAllowed( 4063 "getProcessPss", callingPid, callingUid); 4064 4065 final long[] pss = new long[pids.length]; 4066 for (int i=pids.length-1; i>=0; i--) { 4067 ProcessRecord proc; 4068 int oomAdj; 4069 synchronized (mProcLock) { 4070 synchronized (mPidsSelfLocked) { 4071 proc = mPidsSelfLocked.get(pids[i]); 4072 oomAdj = proc != null ? proc.mState.getSetAdj() : 0; 4073 } 4074 } 4075 if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) { 4076 // The caller is not allow to get information about this other process... 4077 // just leave it empty. 4078 continue; 4079 } 4080 final long[] tmpUss = new long[3]; 4081 final long startTime = SystemClock.currentThreadTimeMillis(); 4082 final long pi = pss[i] = Debug.getPss(pids[i], tmpUss, null); 4083 final long duration = SystemClock.currentThreadTimeMillis() - startTime; 4084 if (proc != null) { 4085 final ProcessProfileRecord profile = proc.mProfile; 4086 synchronized (mAppProfiler.mProfilerLock) { 4087 if (profile.getThread() != null && profile.getSetAdj() == oomAdj) { 4088 // Record this for posterity if the process has been stable. 4089 profile.addPss(pi, tmpUss[0], tmpUss[2], false, 4090 ProcessStats.ADD_PSS_EXTERNAL, duration); 4091 } 4092 } 4093 } 4094 } 4095 return pss; 4096 } 4097 4098 @Override killApplicationProcess(String processName, int uid)4099 public void killApplicationProcess(String processName, int uid) { 4100 if (processName == null) { 4101 return; 4102 } 4103 4104 int callerUid = Binder.getCallingUid(); 4105 // Only the system server can kill an application 4106 if (callerUid == SYSTEM_UID) { 4107 synchronized (this) { 4108 ProcessRecord app = getProcessRecordLocked(processName, uid); 4109 IApplicationThread thread; 4110 if (app != null && (thread = app.getThread()) != null) { 4111 try { 4112 thread.scheduleSuicide(); 4113 } catch (RemoteException e) { 4114 // If the other end already died, then our work here is done. 4115 } 4116 } else { 4117 Slog.w(TAG, "Process/uid not found attempting kill of " 4118 + processName + " / " + uid); 4119 } 4120 } 4121 } else { 4122 throw new SecurityException(callerUid + " cannot kill app process: " + 4123 processName); 4124 } 4125 } 4126 4127 @GuardedBy("this") forceStopPackageLocked(final String packageName, int uid, String reason)4128 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 4129 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 4130 false, true, false, false, false, UserHandle.getUserId(uid), reason); 4131 } 4132 4133 @GuardedBy("this") finishForceStopPackageLocked(final String packageName, int uid)4134 private void finishForceStopPackageLocked(final String packageName, int uid) { 4135 int flags = 0; 4136 if (!mProcessesReady) { 4137 flags = Intent.FLAG_RECEIVER_REGISTERED_ONLY 4138 | Intent.FLAG_RECEIVER_FOREGROUND; 4139 } 4140 mPackageManagerInt.sendPackageRestartedBroadcast(packageName, uid, flags); 4141 } 4142 cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4143 void cleanupDisabledPackageComponentsLocked( 4144 String packageName, int userId, String[] changedClasses) { 4145 4146 Set<String> disabledClasses = null; 4147 boolean packageDisabled = false; 4148 IPackageManager pm = AppGlobals.getPackageManager(); 4149 4150 if (changedClasses == null) { 4151 // Nothing changed... 4152 return; 4153 } 4154 4155 // Determine enable/disable state of the package and its components. 4156 int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4157 for (int i = changedClasses.length - 1; i >= 0; i--) { 4158 final String changedClass = changedClasses[i]; 4159 4160 if (changedClass.equals(packageName)) { 4161 try { 4162 // Entire package setting changed 4163 enabled = pm.getApplicationEnabledSetting(packageName, 4164 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4165 } catch (Exception e) { 4166 // No such package/component; probably racing with uninstall. In any 4167 // event it means we have nothing further to do here. 4168 return; 4169 } 4170 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4171 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4172 if (packageDisabled) { 4173 // Entire package is disabled. 4174 // No need to continue to check component states. 4175 disabledClasses = null; 4176 break; 4177 } 4178 } else { 4179 try { 4180 enabled = pm.getComponentEnabledSetting( 4181 new ComponentName(packageName, changedClass), 4182 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4183 } catch (Exception e) { 4184 // As above, probably racing with uninstall. 4185 return; 4186 } 4187 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4188 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) { 4189 if (disabledClasses == null) { 4190 disabledClasses = new ArraySet<>(changedClasses.length); 4191 } 4192 disabledClasses.add(changedClass); 4193 } 4194 } 4195 } 4196 4197 if (!packageDisabled && disabledClasses == null) { 4198 // Nothing to do here... 4199 return; 4200 } 4201 4202 mAtmInternal.cleanupDisabledPackageComponents( 4203 packageName, disabledClasses, userId, mBooted); 4204 4205 // Clean-up disabled services. 4206 mServices.bringDownDisabledPackageServicesLocked( 4207 packageName, disabledClasses, userId, false /* evenPersistent */, 4208 false /* fullStop */, true /* doIt */); 4209 4210 // Clean-up disabled providers. 4211 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4212 mCpHelper.getProviderMap().collectPackageProvidersLocked( 4213 packageName, disabledClasses, true, false, userId, providers); 4214 for (int i = providers.size() - 1; i >= 0; i--) { 4215 mCpHelper.removeDyingProviderLocked(null, providers.get(i), true); 4216 } 4217 4218 // Clean-up disabled broadcast receivers. 4219 mBroadcastQueue.cleanupDisabledPackageReceiversLocked( 4220 packageName, disabledClasses, userId); 4221 4222 } 4223 clearBroadcastQueueForUserLocked(int userId)4224 final boolean clearBroadcastQueueForUserLocked(int userId) { 4225 boolean didSomething = mBroadcastQueue.cleanupDisabledPackageReceiversLocked( 4226 null, null, userId); 4227 return didSomething; 4228 } 4229 4230 @GuardedBy("this") forceStopAppZygoteLocked(String packageName, int appId, int userId)4231 final void forceStopAppZygoteLocked(String packageName, int appId, int userId) { 4232 if (packageName == null) { 4233 return; 4234 } 4235 if (appId < 0) { 4236 appId = UserHandle.getAppId(getPackageManagerInternal().getPackageUid(packageName, 4237 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM)); 4238 } 4239 4240 mProcessList.killAppZygotesLocked(packageName, appId, userId, true /* force */); 4241 } 4242 stopAppForUserInternal(final String packageName, @UserIdInt final int userId)4243 void stopAppForUserInternal(final String packageName, @UserIdInt final int userId) { 4244 final int uid = getPackageManagerInternal().getPackageUid(packageName, 4245 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, userId); 4246 if (uid < 0) { 4247 Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId 4248 + " but does not exist in that user"); 4249 return; 4250 } 4251 4252 // Policy: certain classes of app are not subject to user-invoked stop 4253 if (getPackageManagerInternal().isPackageStateProtected(packageName, userId)) { 4254 Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId 4255 + " but it is protected"); 4256 return; 4257 } 4258 4259 Slog.i(TAG, "Stopping app for user: " + packageName + "/" + userId); 4260 4261 // A specific subset of the work done in forceStopPackageLocked(), because we are 4262 // intentionally not rendering the app nonfunctional; we're just halting its current 4263 // execution. 4264 final int appId = UserHandle.getAppId(uid); 4265 synchronized (this) { 4266 synchronized (mProcLock) { 4267 mAtmInternal.onForceStopPackage(packageName, true, false, userId); 4268 4269 mProcessList.killPackageProcessesLSP(packageName, appId, userId, 4270 ProcessList.INVALID_ADJ, true, false, true, 4271 false, true /* setRemoved */, false, 4272 ApplicationExitInfo.REASON_USER_REQUESTED, 4273 ApplicationExitInfo.SUBREASON_STOP_APP, 4274 "fully stop " + packageName + "/" + userId + " by user request"); 4275 } 4276 4277 mServices.bringDownDisabledPackageServicesLocked( 4278 packageName, null, userId, false, true, true); 4279 mServices.onUidRemovedLocked(uid); 4280 4281 if (mBooted) { 4282 mAtmInternal.resumeTopActivities(true); 4283 } 4284 } 4285 } 4286 4287 @GuardedBy("this") forceStopUserPackagesLocked(int userId, String reasonString, boolean evenImportantServices)4288 final boolean forceStopUserPackagesLocked(int userId, String reasonString, 4289 boolean evenImportantServices) { 4290 int minOomAdj = evenImportantServices ? ProcessList.INVALID_ADJ 4291 : ProcessList.FOREGROUND_APP_ADJ; 4292 return forceStopPackageInternalLocked(null, -1, false, false, 4293 true, false, false, false, userId, reasonString, 4294 ApplicationExitInfo.REASON_USER_STOPPED, minOomAdj); 4295 } 4296 4297 @GuardedBy("this") forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, int userId, String reasonString)4298 final boolean forceStopPackageLocked(String packageName, int appId, 4299 boolean callerWillRestart, boolean purgeCache, boolean doit, 4300 boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, 4301 int userId, String reasonString) { 4302 int reason = packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED 4303 : ApplicationExitInfo.REASON_USER_REQUESTED; 4304 return forceStopPackageLocked(packageName, appId, callerWillRestart, purgeCache, doit, 4305 evenPersistent, uninstalling, packageStateStopped, userId, reasonString, reason); 4306 } 4307 4308 @GuardedBy("this") forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, @CanBeALL @UserIdInt int userId, String reasonString, int reason)4309 final boolean forceStopPackageLocked(String packageName, int appId, 4310 boolean callerWillRestart, boolean purgeCache, boolean doit, 4311 boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, 4312 @CanBeALL @UserIdInt int userId, String reasonString, int reason) { 4313 return forceStopPackageInternalLocked(packageName, appId, callerWillRestart, purgeCache, 4314 doit, evenPersistent, uninstalling, packageStateStopped, userId, reasonString, 4315 reason, ProcessList.INVALID_ADJ); 4316 } 4317 4318 @GuardedBy("this") forceStopPackageInternalLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, @CanBeALL @UserIdInt int userId, String reasonString, int reason, int minOomAdj)4319 private boolean forceStopPackageInternalLocked(String packageName, int appId, 4320 boolean callerWillRestart, boolean purgeCache, boolean doit, 4321 boolean evenPersistent, boolean uninstalling, boolean packageStateStopped, 4322 @CanBeALL @UserIdInt int userId, String reasonString, int reason, int minOomAdj) { 4323 int i; 4324 4325 if (userId == UserHandle.USER_ALL && packageName == null) { 4326 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 4327 } 4328 4329 final int uid = getPackageManagerInternal().getPackageUid(packageName, 4330 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM); 4331 if (appId < 0 && packageName != null) { 4332 appId = UserHandle.getAppId(uid); 4333 } 4334 4335 boolean didSomething; 4336 if (doit) { 4337 if (packageName != null) { 4338 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId 4339 + " user=" + userId + ": " + reasonString); 4340 } else { 4341 Slog.i(TAG, "Force stopping u" + userId + ": " + reasonString); 4342 } 4343 4344 mAppErrors.resetProcessCrashTime(packageName == null, appId, userId); 4345 } 4346 4347 synchronized (mProcLock) { 4348 // Notify first that the package is stopped, so its process won't be restarted 4349 // unexpectedly if there is an activity of the package without attached process 4350 // becomes visible when killing its other processes with visible activities. 4351 didSomething = mAtmInternal.onForceStopPackage( 4352 packageName, doit, evenPersistent, userId); 4353 int subReason; 4354 if (reason == ApplicationExitInfo.REASON_USER_REQUESTED) { 4355 subReason = ApplicationExitInfo.SUBREASON_FORCE_STOP; 4356 } else { 4357 subReason = ApplicationExitInfo.SUBREASON_UNKNOWN; 4358 } 4359 4360 didSomething |= mProcessList.killPackageProcessesLSP(packageName, appId, userId, 4361 minOomAdj, callerWillRestart, false /* allowRestart */, doit, 4362 evenPersistent, true /* setRemoved */, uninstalling, 4363 reason, 4364 subReason, 4365 (packageName == null ? ("stop user " + userId) : ("stop " + packageName)) 4366 + " due to " + reasonString); 4367 } 4368 4369 if (mServices.bringDownDisabledPackageServicesLocked( 4370 packageName, null /* filterByClasses */, userId, evenPersistent, 4371 true, doit, minOomAdj)) { 4372 if (!doit) { 4373 return true; 4374 } 4375 didSomething = true; 4376 } 4377 mServices.onUidRemovedLocked(uid); 4378 4379 if (packageName == null) { 4380 // Remove all sticky broadcasts from this user. 4381 mBroadcastController.removeStickyBroadcasts(userId); 4382 } 4383 4384 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4385 if (mCpHelper.getProviderMap().collectPackageProvidersLocked(packageName, null, doit, 4386 evenPersistent, userId, providers)) { 4387 if (!doit) { 4388 return true; 4389 } 4390 didSomething = true; 4391 } 4392 for (i = providers.size() - 1; i >= 0; i--) { 4393 mCpHelper.removeDyingProviderLocked(null, providers.get(i), true); 4394 } 4395 4396 // Remove transient permissions granted from/to this package/user 4397 mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false); 4398 4399 if (doit) { 4400 didSomething |= mBroadcastQueue.cleanupDisabledPackageReceiversLocked( 4401 packageName, null, userId); 4402 } 4403 4404 boolean clearPendingIntentsForStoppedApp = false; 4405 try { 4406 clearPendingIntentsForStoppedApp = (packageStateStopped 4407 && android.content.pm.Flags.stayStopped()); 4408 } catch (IllegalStateException e) { 4409 // It's unlikely for a package to be force-stopped early in the boot cycle. So, if we 4410 // check for 'packageStateStopped' which should evaluate to 'false', then this should 4411 // ensure we are not accessing the flag early in the boot cycle. As an additional 4412 // safety measure, catch the exception and ignore to avoid causing a device restart. 4413 clearPendingIntentsForStoppedApp = false; 4414 } 4415 if (packageName == null || uninstalling || clearPendingIntentsForStoppedApp) { 4416 final int cancelReason; 4417 if (packageName == null) { 4418 cancelReason = PendingIntentRecord.CANCEL_REASON_USER_STOPPED; 4419 } else if (uninstalling) { 4420 cancelReason = PendingIntentRecord.CANCEL_REASON_OWNER_UNINSTALLED; 4421 } else { 4422 cancelReason = PendingIntentRecord.CANCEL_REASON_OWNER_FORCE_STOPPED; 4423 } 4424 didSomething |= mPendingIntentController.removePendingIntentsForPackage( 4425 packageName, userId, appId, doit, cancelReason); 4426 } 4427 4428 if (doit) { 4429 if (purgeCache && packageName != null) { 4430 AttributeCache ac = AttributeCache.instance(); 4431 if (ac != null) { 4432 ac.removePackage(packageName); 4433 } 4434 } 4435 if (mBooted) { 4436 mAtmInternal.resumeTopActivities(true /* scheduleIdle */); 4437 } 4438 } 4439 4440 return didSomething; 4441 } 4442 4443 @GuardedBy("this") handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout)4444 void handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout) { 4445 final int pid = app.getPid(); 4446 boolean gone = isKillTimeout || removePidLocked(pid, app); 4447 4448 if (gone) { 4449 if (isKillTimeout) { 4450 // It's still alive... maybe blocked at uninterruptible sleep ? 4451 final ProcessRecord successor = app.mSuccessor; 4452 if (successor == null) { 4453 // There might be a race, nothing to do here. 4454 return; 4455 } 4456 Slog.wtf(TAG, app.toString() + " " + app.getDyingPid() 4457 + " refused to die while trying to launch " + successor 4458 + ", cancelling the process start"); 4459 4460 // It doesn't make sense to proceed with launching the new instance while the old 4461 // instance is still alive, abort the launch. 4462 app.mSuccessorStartRunnable = null; 4463 app.mSuccessor = null; 4464 successor.mPredecessor = null; 4465 4466 // We're going to cleanup the successor process record, which wasn't started at all. 4467 app = successor; 4468 } else { 4469 final String msg = "Process " + app + " failed to attach"; 4470 Slog.w(TAG, msg); 4471 EventLogTags.writeAmProcessStartTimeout(app.userId, pid, app.uid, app.processName); 4472 if (app.getActiveInstrumentation() != null) { 4473 final Bundle info = new Bundle(); 4474 info.putString("shortMsg", "failed to attach"); 4475 info.putString("longMsg", msg); 4476 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 4477 } 4478 } 4479 synchronized (mProcLock) { 4480 mProcessList.removeProcessNameLocked(app.processName, app.uid); 4481 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 4482 // Take care of any launching providers waiting for this process. 4483 mCpHelper.cleanupAppInLaunchingProvidersLocked(app, true); 4484 // Take care of any services that are waiting for the process. 4485 mServices.processStartTimedOutLocked(app); 4486 // Take care of any broadcasts waiting for the process. 4487 mBroadcastQueue.onApplicationTimeoutLocked(app); 4488 if (!isKillTimeout) { 4489 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 4490 app.killLocked("start timeout", 4491 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true); 4492 removeLruProcessLocked(app); 4493 } 4494 if (app.isolated) { 4495 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 4496 mProcessList.mAppExitInfoTracker.mIsolatedUidRecords.removeIsolatedUid( 4497 app.uid, app.info.uid); 4498 getPackageManagerInternal().removeIsolatedUid(app.uid); 4499 } 4500 } 4501 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4502 if (!isKillTimeout && backupTarget != null && backupTarget.app.getPid() == pid) { 4503 Slog.w(TAG, "Unattached app died before backup, skipping"); 4504 final int userId = app.userId; 4505 final String packageName = app.info.packageName; 4506 mHandler.post(() -> { 4507 LocalServices.getService(BackupManagerInternal.class).agentDisconnectedForUser( 4508 packageName, userId); 4509 }); 4510 } 4511 } else { 4512 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 4513 } 4514 } 4515 4516 @GuardedBy("this") attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4517 private void attachApplicationLocked(@NonNull IApplicationThread thread, 4518 int pid, int callingUid, long startSeq) { 4519 // Find the application record that is being attached... either via 4520 // the pid if we are running in multiple processes, or just pull the 4521 // next app record if we are emulating process with anonymous threads. 4522 ProcessRecord app; 4523 long startTime = SystemClock.uptimeMillis(); 4524 long bindApplicationTimeMillis; 4525 long bindApplicationTimeNanos; 4526 if (pid != MY_PID && pid >= 0) { 4527 synchronized (mPidsSelfLocked) { 4528 app = mPidsSelfLocked.get(pid); 4529 } 4530 if (app != null && (app.getStartUid() != callingUid || app.getStartSeq() != startSeq)) { 4531 String processName = null; 4532 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4533 if (pending != null) { 4534 processName = pending.processName; 4535 } 4536 final String msg = "attachApplicationLocked process:" + processName 4537 + " startSeq:" + startSeq 4538 + " pid:" + pid 4539 + " belongs to another existing app:" + app.processName 4540 + " startSeq:" + app.getStartSeq(); 4541 Slog.wtf(TAG, msg); 4542 // SafetyNet logging for b/131105245. 4543 EventLog.writeEvent(0x534e4554, "131105245", app.getStartUid(), msg); 4544 // If there is already an app occupying that pid that hasn't been cleaned up 4545 cleanUpApplicationRecordLocked(app, pid, false, false, -1, 4546 true /*replacingPid*/, false /* fromBinderDied */); 4547 removePidLocked(pid, app); 4548 app = null; 4549 } 4550 } else { 4551 app = null; 4552 } 4553 4554 // It's possible that process called attachApplication before we got a chance to 4555 // update the internal state. 4556 if (app == null && startSeq > 0) { 4557 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4558 if (pending != null && pending.getStartUid() == callingUid 4559 && pending.getStartSeq() == startSeq 4560 && mProcessList.handleProcessStartedLocked(pending, pid, 4561 pending.isUsingWrapper(), startSeq, true)) { 4562 app = pending; 4563 } 4564 } 4565 4566 if (app == null) { 4567 Slog.w(TAG, "No pending application record for pid " + pid 4568 + " (IApplicationThread " + thread + "); dropping process"); 4569 EventLogTags.writeAmDropProcess(pid); 4570 if (pid > 0 && pid != MY_PID) { 4571 killProcessQuiet(pid); 4572 //TODO: killProcessGroup(app.info.uid, pid); 4573 // We can't log the app kill info for this process since we don't 4574 // know who it is, so just skip the logging. 4575 } else { 4576 try { 4577 thread.scheduleExit(); 4578 } catch (Exception e) { 4579 // Ignore exceptions. 4580 } 4581 } 4582 return; 4583 } 4584 4585 // If this application record is still attached to a previous 4586 // process, clean it up now. 4587 if (app.getThread() != null) { 4588 handleAppDiedLocked(app, pid, true, true, false /* fromBinderDied */); 4589 } 4590 4591 // Tell the process all about itself. 4592 4593 if (DEBUG_ALL) Slog.v( 4594 TAG, "Binding process pid " + pid + " to record " + app); 4595 4596 final String processName = app.processName; 4597 try { 4598 AppDeathRecipient adr = new AppDeathRecipient( 4599 app, pid, thread); 4600 thread.asBinder().linkToDeath(adr, 0); 4601 app.setDeathRecipient(adr); 4602 } catch (RemoteException e) { 4603 app.resetPackageList(mProcessStats); 4604 mProcessList.startProcessLocked(app, 4605 new HostingRecord(HostingRecord.HOSTING_TYPE_LINK_FAIL, processName), 4606 ZYGOTE_POLICY_FLAG_EMPTY); 4607 return; 4608 } 4609 4610 EventLogTags.writeAmProcBound(app.userId, pid, app.processName); 4611 4612 synchronized (mProcLock) { 4613 mProcessStateController.setAttachingProcessStatesLSP(app); 4614 clearProcessForegroundLocked(app); 4615 app.setDebugging(false); 4616 app.setKilledByAm(false); 4617 app.setKilled(false); 4618 // We carefully use the same state that PackageManager uses for 4619 // filtering, since we use this flag to decide if we need to install 4620 // providers when user is unlocked later 4621 app.setUnlocked(StorageManager.isCeStorageUnlocked(app.userId)); 4622 } 4623 4624 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4625 List<ProviderInfo> providers = normalMode 4626 ? mCpHelper.generateApplicationProvidersLocked(app) 4627 : null; 4628 4629 if (providers != null && mCpHelper.checkAppInLaunchingProvidersLocked(app)) { 4630 Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG); 4631 msg.obj = app; 4632 mHandler.sendMessageDelayed(msg, 4633 ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS); 4634 } 4635 4636 checkTime(startTime, "attachApplicationLocked: before bindApplication"); 4637 4638 if (!normalMode) { 4639 Slog.i(TAG, "Launching preboot mode app: " + app); 4640 } 4641 4642 if (DEBUG_ALL) Slog.v( 4643 TAG, "New app record " + app 4644 + " thread=" + thread.asBinder() + " pid=" + pid); 4645 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4646 try { 4647 int testMode = ApplicationThreadConstants.DEBUG_OFF; 4648 if (mDebugApp != null && mDebugApp.equals(processName)) { 4649 if (mWaitForDebugger) { 4650 if (mSuspendUponWait) { 4651 testMode = ApplicationThreadConstants.DEBUG_SUSPEND; 4652 } else { 4653 testMode = ApplicationThreadConstants.DEBUG_WAIT; 4654 } 4655 } else { 4656 testMode = ApplicationThreadConstants.DEBUG_ON; 4657 } 4658 app.setDebugging(true); 4659 if (mDebugTransient) { 4660 mDebugApp = mOrigDebugApp; 4661 mWaitForDebugger = mOrigWaitForDebugger; 4662 } 4663 } 4664 4665 boolean enableTrackAllocation = false; 4666 synchronized (mProcLock) { 4667 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) { 4668 enableTrackAllocation = true; 4669 mTrackAllocationApp = null; 4670 } 4671 } 4672 4673 // If the app is being launched for restore or full backup, set it up specially 4674 boolean isRestrictedBackupMode = false; 4675 if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) { 4676 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID 4677 && ((backupTarget.backupMode == BackupRecord.RESTORE_FULL) 4678 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL)) 4679 && backupTarget.useRestrictedMode; 4680 } 4681 4682 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 4683 4684 if (instr != null) { 4685 notifyPackageUse(instr.mClass.getPackageName(), 4686 PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION); 4687 } 4688 ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info; 4689 4690 ProfilerInfo profilerInfo = mAppProfiler.setupProfilerInfoLocked(thread, app, instr); 4691 4692 // We deprecated Build.SERIAL and it is not accessible to 4693 // Instant Apps and target APIs higher than O MR1. Since access to the serial 4694 // is now behind a permission we push down the value. 4695 final String buildSerial = (!appInfo.isInstantApp() 4696 && appInfo.targetSdkVersion < Build.VERSION_CODES.P) 4697 ? sTheRealBuildSerial : Build.UNKNOWN; 4698 4699 // Figure out whether the app needs to run in autofill compat mode. 4700 AutofillOptions autofillOptions = null; 4701 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 4702 final AutofillManagerInternal afm = LocalServices.getService( 4703 AutofillManagerInternal.class); 4704 if (afm != null) { 4705 autofillOptions = afm.getAutofillOptions( 4706 app.info.packageName, app.info.longVersionCode, app.userId); 4707 } 4708 } 4709 ContentCaptureOptions contentCaptureOptions = null; 4710 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 4711 final ContentCaptureManagerInternal ccm = 4712 LocalServices.getService(ContentCaptureManagerInternal.class); 4713 if (ccm != null) { 4714 contentCaptureOptions = ccm.getOptionsForPackage(app.userId, 4715 app.info.packageName); 4716 } 4717 } 4718 SharedMemory serializedSystemFontMap = null; 4719 final FontManagerInternal fm = LocalServices.getService(FontManagerInternal.class); 4720 if (fm != null) { 4721 serializedSystemFontMap = fm.getSerializedSystemFontMap(); 4722 } 4723 4724 checkTime(startTime, "attachApplicationLocked: immediately before bindApplication"); 4725 bindApplicationTimeMillis = SystemClock.uptimeMillis(); 4726 bindApplicationTimeNanos = SystemClock.uptimeNanos(); 4727 final ActivityTaskManagerInternal.PreBindInfo preBindInfo = 4728 mAtmInternal.preBindApplication(app.getWindowProcessController(), appInfo); 4729 app.setCompat(preBindInfo.compatibilityInfo); 4730 final ActiveInstrumentation instr2 = app.getActiveInstrumentation(); 4731 if (mPlatformCompat != null) { 4732 mPlatformCompat.resetReporting(app.info); 4733 } 4734 final ProviderInfoList providerList = ProviderInfoList.fromList(providers); 4735 app.mProfile.mLastCpuDelayTime.set(app.getCpuDelayTime()); 4736 if (app.getIsolatedEntryPoint() != null) { 4737 // This is an isolated process which should just call an entry point instead of 4738 // being bound to an application. 4739 thread.runIsolatedEntryPoint( 4740 app.getIsolatedEntryPoint(), app.getIsolatedEntryPointArgs()); 4741 } else { 4742 boolean isSdkInSandbox = false; 4743 ComponentName instrumentationName = null; 4744 Bundle instrumentationArgs = null; 4745 IInstrumentationWatcher instrumentationWatcher = null; 4746 IUiAutomationConnection instrumentationUiConnection = null; 4747 if (instr2 != null) { 4748 isSdkInSandbox = instr2.mIsSdkInSandbox; 4749 instrumentationName = instr2.mClass; 4750 instrumentationArgs = instr2.mArguments; 4751 instrumentationWatcher = instr2.mWatcher; 4752 instrumentationUiConnection = instr2.mUiAutomationConnection; 4753 } 4754 thread.bindApplication( 4755 processName, 4756 appInfo, 4757 app.sdkSandboxClientAppVolumeUuid, 4758 app.sdkSandboxClientAppPackage, 4759 isSdkInSandbox, 4760 providerList, 4761 instrumentationName, 4762 profilerInfo, 4763 instrumentationArgs, 4764 instrumentationWatcher, 4765 instrumentationUiConnection, 4766 testMode, 4767 mBinderTransactionTrackingEnabled, 4768 enableTrackAllocation, 4769 isRestrictedBackupMode || !normalMode, 4770 app.isPersistent(), 4771 preBindInfo.configuration, 4772 app.getCompat(), 4773 getCommonServicesLocked(app.isolated), 4774 mCoreSettingsObserver.getCoreSettingsLocked(), 4775 buildSerial, 4776 autofillOptions, 4777 contentCaptureOptions, 4778 app.getDisabledCompatChanges(), 4779 app.getLoggableCompatChanges(), 4780 serializedSystemFontMap, 4781 mApplicationSharedMemoryReadOnlyFd, 4782 app.getStartElapsedTime(), 4783 app.getStartUptime()); 4784 } 4785 4786 Message msg = mHandler.obtainMessage(BIND_APPLICATION_TIMEOUT_SOFT_MSG); 4787 msg.obj = app; 4788 msg.arg1 = BIND_APPLICATION_TIMEOUT; 4789 mHandler.sendMessageDelayed(msg, msg.arg1 /* BIND_APPLICATION_TIMEOUT */); 4790 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4791 4792 if (profilerInfo != null) { 4793 profilerInfo.closeFd(); 4794 profilerInfo = null; 4795 } 4796 4797 app.setBindApplicationTime(bindApplicationTimeMillis); 4798 mProcessList.getAppStartInfoTracker() 4799 .addTimestampToStart(app, bindApplicationTimeNanos, 4800 ApplicationStartInfo.START_TIMESTAMP_BIND_APPLICATION); 4801 4802 // Make app active after binding application or client may be running requests (e.g 4803 // starting activities) before it is ready. 4804 synchronized (mProcLock) { 4805 app.makeActive(new ApplicationThreadDeferred(thread), mProcessStats); 4806 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication"); 4807 } 4808 mProcessStateController.setPendingFinishAttach(app, true); 4809 4810 updateLruProcessLocked(app, false, null); 4811 checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked"); 4812 4813 final long now = SystemClock.uptimeMillis(); 4814 synchronized (mAppProfiler.mProfilerLock) { 4815 app.mProfile.setLastRequestedGc(now); 4816 app.mProfile.setLastLowMemory(now); 4817 } 4818 4819 // Remove this record from the list of starting applications. 4820 mPersistentStartingProcesses.remove(app); 4821 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) { 4822 Slog.v(TAG_PROCESSES, "Attach application locked removing on hold: " + app); 4823 } 4824 mProcessesOnHold.remove(app); 4825 4826 // See if the top visible activity is waiting to run in this process... 4827 if (com.android.server.am.Flags.expediteActivityLaunchOnColdStart()) { 4828 if (normalMode) { 4829 mAtmInternal.attachApplication(app.getWindowProcessController()); 4830 } 4831 } 4832 updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN); 4833 checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked"); 4834 4835 if (!mConstants.mEnableWaitForFinishAttachApplication) { 4836 finishAttachApplicationInner(startSeq, callingUid, pid); 4837 } 4838 maybeSendBootCompletedLocked(app, isRestrictedBackupMode); 4839 } catch (Exception e) { 4840 // We need kill the process group here. (b/148588589) 4841 Slog.wtf(TAG, "Exception thrown during bind of " + app, e); 4842 app.resetPackageList(mProcessStats); 4843 app.unlinkDeathRecipient(); 4844 app.killLocked("error during bind", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 4845 true); 4846 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */); 4847 return; 4848 } 4849 } 4850 4851 @Override attachApplication(IApplicationThread thread, long startSeq)4852 public final void attachApplication(IApplicationThread thread, long startSeq) { 4853 if (thread == null) { 4854 throw new SecurityException("Invalid application interface"); 4855 } 4856 synchronized (this) { 4857 int callingPid = Binder.getCallingPid(); 4858 final int callingUid = Binder.getCallingUid(); 4859 final long origId = Binder.clearCallingIdentity(); 4860 attachApplicationLocked(thread, callingPid, callingUid, startSeq); 4861 Binder.restoreCallingIdentity(origId); 4862 } 4863 } 4864 finishAttachApplicationInner(long startSeq, int uid, int pid)4865 private void finishAttachApplicationInner(long startSeq, int uid, int pid) { 4866 final long startTime = SystemClock.uptimeMillis(); 4867 // Find the application record that is being attached... either via 4868 // the pid if we are running in multiple processes, or just pull the 4869 // next app record if we are emulating process with anonymous threads. 4870 final ProcessRecord app; 4871 synchronized (mPidsSelfLocked) { 4872 app = mPidsSelfLocked.get(pid); 4873 } 4874 4875 if (app != null && app.getStartUid() == uid && app.getStartSeq() == startSeq) { 4876 mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_SOFT_MSG, app); 4877 mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_HARD_MSG, app); 4878 } else { 4879 Slog.wtf(TAG, "Mismatched or missing ProcessRecord: " + app + ". Pid: " + pid 4880 + ". Uid: " + uid); 4881 if (pid > 0) { 4882 killProcess(pid); 4883 killProcessGroup(uid, pid); 4884 } 4885 mProcessList.noteAppKill(pid, uid, 4886 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 4887 ApplicationExitInfo.SUBREASON_UNKNOWN, 4888 "wrong startSeq"); 4889 synchronized (this) { 4890 app.killLocked("unexpected process record", 4891 ApplicationExitInfo.REASON_OTHER, true); 4892 } 4893 return; 4894 } 4895 4896 synchronized (this) { 4897 // Mark the finish attach application phase as completed 4898 mProcessStateController.setPendingFinishAttach(app, false); 4899 4900 final String processName = app.processName; 4901 boolean badApp = false; 4902 boolean didSomething = false; 4903 4904 if (!com.android.server.am.Flags.expediteActivityLaunchOnColdStart()) { 4905 final boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4906 4907 if (normalMode) { 4908 try { 4909 didSomething |= mAtmInternal.attachApplication( 4910 app.getWindowProcessController()); 4911 } catch (Exception e) { 4912 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); 4913 badApp = true; 4914 } 4915 } 4916 } 4917 4918 // Find any services that should be running in this process... 4919 if (!badApp) { 4920 try { 4921 didSomething |= mServices.attachApplicationLocked(app, processName); 4922 checkTime(startTime, "finishAttachApplicationInner: " 4923 + "after mServices.attachApplicationLocked"); 4924 } catch (Exception e) { 4925 Slog.wtf(TAG, "Exception thrown starting services in " + app, e); 4926 badApp = true; 4927 } 4928 } 4929 4930 // Check if a next-broadcast receiver is in this process... 4931 if (!badApp) { 4932 try { 4933 didSomething |= mBroadcastQueue.onApplicationAttachedLocked(app); 4934 checkTime(startTime, "finishAttachApplicationInner: " 4935 + "after dispatching broadcasts"); 4936 } catch (BroadcastDeliveryFailedException e) { 4937 // If the app died trying to launch the receiver we declare it 'bad' 4938 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e); 4939 badApp = true; 4940 } 4941 } 4942 4943 // Check whether the next backup agent is in this process... 4944 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4945 if (!badApp && backupTarget != null && backupTarget.app == app) { 4946 if (DEBUG_BACKUP) { 4947 Slog.v(TAG_BACKUP, 4948 "New app is backup target, launching agent for " + app); 4949 } 4950 4951 notifyPackageUse(backupTarget.appInfo.packageName, 4952 PackageManager.NOTIFY_PACKAGE_USE_BACKUP); 4953 try { 4954 app.getThread().scheduleCreateBackupAgent(backupTarget.appInfo, 4955 backupTarget.backupMode, backupTarget.userId, 4956 backupTarget.backupDestination); 4957 } catch (Exception e) { 4958 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e); 4959 badApp = true; 4960 } 4961 } 4962 4963 if (badApp) { 4964 app.killLocked("error during init", 4965 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true); 4966 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */); 4967 return; 4968 } 4969 4970 if (!didSomething) { 4971 updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN); 4972 checkTime(startTime, "finishAttachApplicationInner: after updateOomAdjLocked"); 4973 } 4974 4975 final HostingRecord hostingRecord = app.getHostingRecord(); 4976 final String shortAction = getShortAction(hostingRecord.getAction()); 4977 FrameworkStatsLog.write( 4978 FrameworkStatsLog.PROCESS_START_TIME, 4979 app.info.uid, 4980 pid, 4981 app.info.packageName, 4982 FrameworkStatsLog.PROCESS_START_TIME__TYPE__COLD, 4983 app.getStartElapsedTime(), 4984 (int) (app.getBindApplicationTime() - app.getStartUptime()), 4985 (int) (SystemClock.uptimeMillis() - app.getStartUptime()), 4986 hostingRecord.getType(), 4987 hostingRecord.getName(), 4988 shortAction, 4989 HostingRecord.getHostingTypeIdStatsd(hostingRecord.getType()), 4990 HostingRecord.getTriggerTypeForStatsd(hostingRecord.getTriggerType())); 4991 } 4992 } 4993 4994 @Override finishAttachApplication(long startSeq, long timestampApplicationOnCreateNs)4995 public final void finishAttachApplication(long startSeq, long timestampApplicationOnCreateNs) { 4996 final int pid = Binder.getCallingPid(); 4997 final int uid = Binder.getCallingUid(); 4998 4999 if (!mConstants.mEnableWaitForFinishAttachApplication) { 5000 Slog.i(TAG, "Flag disabled. Ignoring finishAttachApplication from uid: " 5001 + uid + ". pid: " + pid); 5002 return; 5003 } 5004 5005 if (pid == MY_PID && uid == SYSTEM_UID) { 5006 return; 5007 } 5008 5009 final long origId = Binder.clearCallingIdentity(); 5010 try { 5011 finishAttachApplicationInner(startSeq, uid, pid); 5012 } finally { 5013 Binder.restoreCallingIdentity(origId); 5014 } 5015 5016 if (android.app.Flags.appStartInfoTimestamps() && timestampApplicationOnCreateNs > 0) { 5017 addStartInfoTimestampInternal(ApplicationStartInfo.START_TIMESTAMP_APPLICATION_ONCREATE, 5018 timestampApplicationOnCreateNs, UserHandle.getUserId(uid), uid); 5019 } 5020 } 5021 handleBindApplicationTimeoutSoft(ProcessRecord app, int softTimeoutMillis)5022 private void handleBindApplicationTimeoutSoft(ProcessRecord app, int softTimeoutMillis) { 5023 // Similar logic as the broadcast delivery timeout: 5024 // instead of immediately triggering an ANR, extend the timeout by 5025 // the amount of time the process was runnable-but-waiting; we're 5026 // only willing to do this once before triggering an hard ANR. 5027 final long cpuDelayTime = app.getCpuDelayTime() - app.mProfile.mLastCpuDelayTime.get(); 5028 final long hardTimeoutMillis = MathUtils.constrain(cpuDelayTime, 0, softTimeoutMillis); 5029 5030 if (hardTimeoutMillis == 0) { 5031 handleBindApplicationTimeoutHard(app); 5032 return; 5033 } 5034 5035 Slog.i(TAG, "Extending process start timeout by " + hardTimeoutMillis + "ms for " + app); 5036 Trace.instant(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplicationTimeSoft " 5037 + app.processName + "(" + app.getPid() + ")"); 5038 final Message msg = mHandler.obtainMessage(BIND_APPLICATION_TIMEOUT_HARD_MSG, app); 5039 mHandler.sendMessageDelayed(msg, hardTimeoutMillis); 5040 } 5041 handleBindApplicationTimeoutHard(ProcessRecord app)5042 private void handleBindApplicationTimeoutHard(ProcessRecord app) { 5043 final String anrMessage; 5044 synchronized (app) { 5045 anrMessage = "Process " + app + " failed to complete startup"; 5046 } 5047 5048 mAnrHelper.appNotResponding(app, TimeoutRecord.forAppStart(anrMessage)); 5049 } 5050 handleFollowUpOomAdjusterUpdate()5051 private void handleFollowUpOomAdjusterUpdate() { 5052 // Remove any existing duplicate messages on the handler here while no lock is being held. 5053 // If another follow up update is needed, it will be scheduled by OomAdjuster. 5054 mHandler.removeMessages(FOLLOW_UP_OOMADJUSTER_UPDATE_MSG); 5055 synchronized (this) { 5056 mProcessStateController.runFollowUpUpdate(); 5057 } 5058 } 5059 5060 /** 5061 * @return The last part of the string of an intent's action. 5062 */ getShortAction(@ullable String action)5063 static @Nullable String getShortAction(@Nullable String action) { 5064 String shortAction = action; 5065 if (action != null) { 5066 int index = action.lastIndexOf('.'); 5067 if (index != -1 && index != action.length() - 1) { 5068 shortAction = action.substring(index + 1); 5069 } 5070 } 5071 return shortAction; 5072 } 5073 checkTime(long startTime, String where)5074 void checkTime(long startTime, String where) { 5075 long now = SystemClock.uptimeMillis(); 5076 if ((now - startTime) > 50) { 5077 // If we are taking more than 50ms, log about it. 5078 Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where); 5079 } 5080 } 5081 5082 /** 5083 * Send LOCKED_BOOT_COMPLETED and BOOT_COMPLETED to the package explicitly when unstopped, 5084 * or when the package first starts in private space 5085 */ maybeSendBootCompletedLocked(ProcessRecord app, boolean isRestrictedBackupMode)5086 private void maybeSendBootCompletedLocked(ProcessRecord app, boolean isRestrictedBackupMode) { 5087 boolean sendBroadcast = false; 5088 if (android.os.Flags.allowPrivateProfile() 5089 && android.multiuser.Flags.enablePrivateSpaceFeatures()) { 5090 final UserManagerInternal umInternal = 5091 LocalServices.getService(UserManagerInternal.class); 5092 UserInfo userInfo = umInternal.getUserInfo(app.userId); 5093 5094 if (userInfo != null && userInfo.isPrivateProfile()) { 5095 // Packages in private space get deferred boot completed whenever they start the 5096 // first time since profile start 5097 if (!mPrivateSpaceBootCompletedPackages.contains(app.info.packageName)) { 5098 mPrivateSpaceBootCompletedPackages.add(app.info.packageName); 5099 sendBroadcast = true; 5100 } // else, stopped packages in private space may still hit the logic below 5101 } 5102 } 5103 5104 final boolean wasForceStopped = app.wasForceStopped() 5105 || app.getWindowProcessController().wasForceStopped(); 5106 if (android.app.Flags.appRestrictionsApi() && wasForceStopped) { 5107 noteAppRestrictionEnabled(app.info.packageName, app.uid, 5108 RESTRICTION_LEVEL_FORCE_STOPPED, false, 5109 RESTRICTION_REASON_USAGE, "unknown", RESTRICTION_SOURCE_USER, 0L); 5110 } 5111 5112 // Don't send BOOT_COMPLETED if currently in restricted backup mode 5113 if (isRestrictedBackupMode) return; 5114 5115 if (!sendBroadcast) { 5116 if (!android.content.pm.Flags.stayStopped()) return; 5117 // Nothing to do if it wasn't previously stopped 5118 if (!wasForceStopped) { 5119 return; 5120 } 5121 } 5122 5123 // Send LOCKED_BOOT_COMPLETED, if necessary 5124 if (app.getApplicationInfo().isEncryptionAware()) { 5125 sendBootBroadcastToAppLocked(app, new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED), 5126 REASON_LOCKED_BOOT_COMPLETED); 5127 } 5128 // Send BOOT_COMPLETED if the user is unlocked 5129 if (StorageManager.isCeStorageUnlocked(app.userId)) { 5130 sendBootBroadcastToAppLocked(app, new Intent(Intent.ACTION_BOOT_COMPLETED), 5131 REASON_BOOT_COMPLETED); 5132 } 5133 // The stopped state is reset in ProcessRecord when the pid changes, to deal with 5134 // any re-use of the ProcessRecord. 5135 } 5136 5137 /** Send a boot_completed broadcast to app */ sendBootBroadcastToAppLocked(ProcessRecord app, Intent intent, @PowerExemptionManager.ReasonCode int reason)5138 private void sendBootBroadcastToAppLocked(ProcessRecord app, Intent intent, 5139 @PowerExemptionManager.ReasonCode int reason) { 5140 intent.setPackage(app.info.packageName); 5141 intent.putExtra(Intent.EXTRA_USER_HANDLE, app.userId); 5142 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT 5143 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND 5144 | Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 5145 5146 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, 5147 new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED}, 5148 null, null, AppOpsManager.OP_NONE, 5149 null, true, 5150 false, MY_PID, SYSTEM_UID, 5151 SYSTEM_UID, MY_PID, app.userId); 5152 } 5153 5154 @Override showBootMessage(final CharSequence msg, final boolean always)5155 public void showBootMessage(final CharSequence msg, final boolean always) { 5156 if (Binder.getCallingUid() != myUid()) { 5157 throw new SecurityException(); 5158 } 5159 mWindowManager.showBootMessage(msg, always); 5160 } 5161 finishBooting()5162 final void finishBooting() { 5163 TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing", 5164 Trace.TRACE_TAG_ACTIVITY_MANAGER); 5165 t.traceBegin("FinishBooting"); 5166 5167 synchronized (this) { 5168 if (!mBootAnimationComplete) { 5169 mCallFinishBooting = true; 5170 return; 5171 } 5172 mCallFinishBooting = false; 5173 } 5174 5175 // Let the ART runtime in zygote and system_server know that the boot completed. 5176 ZYGOTE_PROCESS.bootCompleted(); 5177 VMRuntime.bootCompleted(); 5178 5179 IntentFilter pkgFilter = new IntentFilter(); 5180 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 5181 pkgFilter.addDataScheme("package"); 5182 mContext.registerReceiver(new BroadcastReceiver() { 5183 @Override 5184 public void onReceive(Context context, Intent intent) { 5185 final String action = intent.getAction(); 5186 if (action == null) { 5187 return; 5188 } 5189 5190 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 5191 if (pkgs != null) { 5192 for (String pkg : pkgs) { 5193 synchronized (ActivityManagerService.this) { 5194 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 5195 false, 0, "query restart")) { 5196 setResultCode(Activity.RESULT_OK); 5197 return; 5198 } 5199 } 5200 } 5201 } 5202 } 5203 }, pkgFilter); 5204 5205 // Inform checkpointing systems of success 5206 try { 5207 // This line is needed to CTS test for the correct exception handling 5208 // See b/138952436#comment36 for context 5209 Slog.i(TAG, "About to commit checkpoint"); 5210 IStorageManager storageManager = InstallLocationUtils.getStorageManager(); 5211 storageManager.commitChanges(); 5212 } catch (Exception e) { 5213 PowerManager pm = (PowerManager) 5214 mInjector.getContext().getSystemService(Context.POWER_SERVICE); 5215 pm.reboot("Checkpoint commit failed"); 5216 } 5217 5218 // Let system services know. 5219 mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED); 5220 5221 synchronized (this) { 5222 // Ensure that any processes we had put on hold are now started 5223 // up. 5224 final int NP = mProcessesOnHold.size(); 5225 if (NP > 0) { 5226 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mProcessesOnHold); 5227 for (int ip = 0; ip < NP; ip++) { 5228 if (DEBUG_PROCESSES) { 5229 Slog.v(TAG_PROCESSES, "Starting process on hold: " + procs.get(ip)); 5230 } 5231 mProcessList.startProcessLocked(procs.get(ip), 5232 new HostingRecord(HostingRecord.HOSTING_TYPE_ON_HOLD), 5233 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 5234 } 5235 } 5236 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 5237 return; 5238 } 5239 // Start looking for apps that are abusing wake locks. 5240 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 5241 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 5242 // Tell anyone interested that we are done booting! 5243 SystemProperties.set("sys.boot_completed", "1"); 5244 SystemProperties.set("dev.bootcomplete", "1"); 5245 5246 // Start PSI monitoring in LMKD if it was skipped earlier. 5247 ProcessList.startPsiMonitoringAfterBoot(); 5248 5249 mUserController.onBootComplete( 5250 new IIntentReceiver.Stub() { 5251 @Override 5252 public void performReceive(Intent intent, int resultCode, 5253 String data, Bundle extras, boolean ordered, 5254 boolean sticky, int sendingUser) { 5255 mBootCompletedTimestamp = SystemClock.uptimeMillis(); 5256 // Defer the full Pss collection as the system is really busy now. 5257 mHandler.postDelayed(() -> { 5258 synchronized (mProcLock) { 5259 mAppProfiler.requestPssAllProcsLPr( 5260 SystemClock.uptimeMillis(), true, false); 5261 } 5262 }, mConstants.FULL_PSS_MIN_INTERVAL); 5263 } 5264 }); 5265 mUserController.scheduleStartProfiles(); 5266 } 5267 // UART is on if init's console service is running, send a warning notification. 5268 showConsoleNotificationIfActive(); 5269 showMteOverrideNotificationIfActive(); 5270 5271 t.traceEnd(); 5272 } 5273 showConsoleNotificationIfActive()5274 private void showConsoleNotificationIfActive() { 5275 if (!SystemProperties.get("init.svc.console").equals("running")) { 5276 return; 5277 } 5278 String title = mContext 5279 .getString(com.android.internal.R.string.console_running_notification_title); 5280 String message = mContext 5281 .getString(com.android.internal.R.string.console_running_notification_message); 5282 Notification notification = 5283 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 5284 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 5285 .setWhen(0) 5286 .setOngoing(true) 5287 .setTicker(title) 5288 .setDefaults(0) // please be quiet 5289 .setColor(mContext.getColor( 5290 com.android.internal.R.color 5291 .system_notification_accent_color)) 5292 .setContentTitle(title) 5293 .setContentText(message) 5294 .setVisibility(Notification.VISIBILITY_PUBLIC) 5295 .build(); 5296 5297 NotificationManager notificationManager = 5298 mContext.getSystemService(NotificationManager.class); 5299 notificationManager.notifyAsUser( 5300 null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL); 5301 5302 } 5303 showMteOverrideNotificationIfActive()5304 private void showMteOverrideNotificationIfActive() { 5305 String bootctl = SystemProperties.get("arm64.memtag.bootctl"); 5306 // If MTE is on, there is one in three cases: 5307 // * a fullmte build: ro.arm64.memtag.bootctl_supported is not set 5308 // * memtag: arm64.memtag.bootctl contains "memtag" 5309 // * memtag-once 5310 // In the condition below we detect memtag-once by exclusion. 5311 if (Arrays.asList(bootctl.split(",")).contains("memtag") 5312 || !SystemProperties.getBoolean("ro.arm64.memtag.bootctl_supported", false) 5313 || !com.android.internal.os.Zygote.nativeSupportsMemoryTagging()) { 5314 return; 5315 } 5316 String title = mContext 5317 .getString(com.android.internal.R.string.mte_override_notification_title); 5318 String message = mContext 5319 .getString(com.android.internal.R.string.mte_override_notification_message); 5320 Notification notification = 5321 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 5322 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 5323 .setOngoing(true) 5324 .setTicker(title) 5325 .setDefaults(0) // please be quiet 5326 .setColor(mContext.getColor( 5327 com.android.internal.R.color 5328 .system_notification_accent_color)) 5329 .setContentTitle(title) 5330 .setContentText(message) 5331 .setVisibility(Notification.VISIBILITY_PUBLIC) 5332 .build(); 5333 5334 NotificationManager notificationManager = 5335 mContext.getSystemService(NotificationManager.class); 5336 notificationManager.notifyAsUser( 5337 null, SystemMessage.NOTE_MTE_OVERRIDE_ENABLED, notification, UserHandle.ALL); 5338 } 5339 5340 @Override bootAnimationComplete()5341 public void bootAnimationComplete() { 5342 if (DEBUG_ALL) Slog.d(TAG, "bootAnimationComplete: Callers=" + Debug.getCallers(4)); 5343 5344 final boolean callFinishBooting; 5345 synchronized (this) { 5346 callFinishBooting = mCallFinishBooting; 5347 mBootAnimationComplete = true; 5348 } 5349 if (callFinishBooting) { 5350 finishBooting(); 5351 } 5352 } 5353 5354 /** 5355 * Starts Home if there is no completion signal from ThemeOverlayController 5356 */ scheduleHomeTimeout()5357 private void scheduleHomeTimeout() { 5358 if (!isHomeLaunchDelayable()) { 5359 Slog.d(TAG, "ThemeHomeDelay: Home launch is not delayable, skipping timeout creation"); 5360 return; 5361 } 5362 5363 if (!mHasHomeDelay.compareAndSet(false, true)) return; 5364 5365 mHandler.postDelayed(() -> { 5366 int userId = mUserController.getCurrentUserId(); 5367 if (!isThemeOverlayReady(userId)) { 5368 Slog.d(TAG, 5369 "ThemeHomeDelay: ThemeOverlayController not responding, launching " 5370 + "Home after " + HOME_LAUNCH_TIMEOUT_MS + "ms" 5371 + " with user " + userId); 5372 setThemeOverlayReady(userId); 5373 } 5374 }, HOME_LAUNCH_TIMEOUT_MS); 5375 5376 } 5377 5378 /** 5379 * Used by ThemeOverlayController to notify when color 5380 * palette is ready. 5381 * 5382 * @param userId The ID of the user where ThemeOverlayController is ready. 5383 * @hide 5384 */ 5385 @Override setThemeOverlayReady(@serIdInt int userId)5386 public void setThemeOverlayReady(@UserIdInt int userId) { 5387 if (!isHomeLaunchDelayable()) { 5388 Slog.d(TAG, "ThemeHomeDelay: Home launch is not delayable, " 5389 + "ignoring setThemeOverlayReady() call"); 5390 return; 5391 } 5392 5393 enforceCallingPermission(Manifest.permission.SET_THEME_OVERLAY_CONTROLLER_READY, 5394 "setThemeOverlayReady"); 5395 Slog.d(TAG, "ThemeHomeDelay: userId " + userId 5396 + " notified ThemeOverlayController completeness"); 5397 boolean updateUser; 5398 synchronized (mThemeOverlayReadyUsers) { 5399 updateUser = mThemeOverlayReadyUsers.add(userId); 5400 Slog.d(TAG, "ThemeHomeDelay: updateUser " + userId + " isUpdatable: " + updateUser); 5401 } 5402 5403 if (updateUser) { 5404 Slog.d(TAG, "ThemeHomeDelay: updating user " + userId); 5405 mAtmInternal.startHomeOnAllDisplays(userId, "setThemeOverlayReady"); 5406 } 5407 } 5408 5409 /** 5410 * Returns current state of ThemeOverlayController color 5411 * palette readiness. 5412 * 5413 * @hide 5414 */ isThemeOverlayReady(int userId)5415 public boolean isThemeOverlayReady(int userId) { 5416 synchronized (mThemeOverlayReadyUsers) { 5417 return mThemeOverlayReadyUsers.contains(userId); 5418 } 5419 } 5420 5421 /** Checks whether the home launch delay feature is enabled. */ isHomeLaunchDelayable()5422 private boolean isHomeLaunchDelayable() { 5423 // This feature is disabled on Auto since it seems to add an unacceptably long boot delay 5424 // without even solving the underlying issue (it merely hits the timeout). 5425 // This feature is disabled on TV since the ThemeOverlayController is currently not present 5426 // and therefore we do not want to wait unnecessarily. 5427 // This feature is currently disabled in WearOS to avoid extreme boot regressions 5428 return enableHomeDelay() 5429 && !mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE) 5430 && !mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK) 5431 && !mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH); 5432 } 5433 ensureBootCompleted()5434 final void ensureBootCompleted() { 5435 boolean booting; 5436 boolean enableScreen; 5437 synchronized (this) { 5438 booting = mBooting; 5439 mBooting = false; 5440 enableScreen = !mBooted; 5441 mBooted = true; 5442 } 5443 5444 if (booting) { 5445 finishBooting(); 5446 } 5447 5448 if (enableScreen) { 5449 mAtmInternal.enableScreenAfterBoot(mBooted); 5450 } 5451 } 5452 5453 /** 5454 * @deprecated Use {@link #getIntentSenderWithFeature} instead 5455 */ 5456 @Deprecated 5457 @Override getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5458 public IIntentSender getIntentSender(int type, 5459 String packageName, IBinder token, String resultWho, 5460 int requestCode, Intent[] intents, String[] resolvedTypes, 5461 int flags, Bundle bOptions, int userId) { 5462 return getIntentSenderWithFeature(type, packageName, null, token, resultWho, requestCode, 5463 intents, resolvedTypes, flags, bOptions, userId); 5464 } 5465 5466 @Override getIntentSenderWithFeature(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5467 public IIntentSender getIntentSenderWithFeature(int type, String packageName, String featureId, 5468 IBinder token, String resultWho, int requestCode, Intent[] intents, 5469 String[] resolvedTypes, int flags, Bundle bOptions, int userId) { 5470 enforceNotIsolatedCaller("getIntentSender"); 5471 5472 return getIntentSenderWithFeatureAsApp(type, packageName, featureId, token, resultWho, 5473 requestCode, intents, resolvedTypes, flags, bOptions, userId, 5474 Binder.getCallingUid()); 5475 } 5476 5477 /** 5478 * System-internal callers can invoke this with owningUid being the app's own identity 5479 * rather than the public API's behavior of always assigning ownership to the actual 5480 * caller identity. This will create an IntentSender as though the package/userid/uid app 5481 * were the caller, so that the ultimate PendingIntent is triggered with only the app's 5482 * capabilities and not the system's. Used in cases like notification groups where 5483 * the OS must synthesize a PendingIntent on an app's behalf. 5484 */ 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)5485 public IIntentSender getIntentSenderWithFeatureAsApp(int type, String packageName, 5486 String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, 5487 String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid) { 5488 // NOTE: The service lock isn't held in this method because nothing in the method requires 5489 // the service lock to be held. 5490 5491 // Refuse possible leaked file descriptors 5492 if (intents != null) { 5493 if (intents.length < 1) { 5494 throw new IllegalArgumentException("Intents array length must be >= 1"); 5495 } 5496 for (int i=0; i<intents.length; i++) { 5497 Intent intent = intents[i]; 5498 if (intent != null) { 5499 if (intent.hasFileDescriptors()) { 5500 throw new IllegalArgumentException("File descriptors passed in Intent"); 5501 } 5502 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 5503 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 5504 throw new IllegalArgumentException( 5505 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 5506 } 5507 boolean isActivityResultType = 5508 type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT; 5509 if (PendingIntent.isNewMutableDisallowedImplicitPendingIntent(flags, intent, 5510 isActivityResultType)) { 5511 boolean isChangeEnabled = CompatChanges.isChangeEnabled( 5512 PendingIntent.BLOCK_MUTABLE_IMPLICIT_PENDING_INTENT, 5513 packageName, UserHandle.of(userId)); 5514 String resolvedType = resolvedTypes == null 5515 || i >= resolvedTypes.length ? null : resolvedTypes[i]; 5516 SaferIntentUtils.reportUnsafeIntentEvent( 5517 UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__NEW_MUTABLE_IMPLICIT_PENDING_INTENT_RETRIEVED, 5518 owningUid, Process.INVALID_PID, 5519 intent, resolvedType, isChangeEnabled); 5520 if (isChangeEnabled) { 5521 String msg = packageName + ": Targeting U+ (version " 5522 + Build.VERSION_CODES.UPSIDE_DOWN_CAKE + " and above) disallows" 5523 + " creating or retrieving a PendingIntent with FLAG_MUTABLE," 5524 + " an implicit Intent within and without FLAG_NO_CREATE and" 5525 + " FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT for" 5526 + " security reasons. To retrieve an already existing" 5527 + " PendingIntent, use FLAG_NO_CREATE, however, to create a" 5528 + " new PendingIntent with an implicit Intent use" 5529 + " FLAG_IMMUTABLE."; 5530 throw new IllegalArgumentException(msg); 5531 } 5532 } 5533 intents[i] = new Intent(intent); 5534 intents[i].removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH); 5535 } 5536 } 5537 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 5538 throw new IllegalArgumentException( 5539 "Intent array length does not match resolvedTypes length"); 5540 } 5541 } 5542 if (bOptions != null) { 5543 if (bOptions.hasFileDescriptors()) { 5544 throw new IllegalArgumentException("File descriptors passed in options"); 5545 } 5546 } 5547 5548 int origUserId = userId; 5549 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), owningUid, userId, 5550 type == ActivityManager.INTENT_SENDER_BROADCAST, 5551 ALLOW_NON_FULL, "getIntentSender", null); 5552 if (origUserId == UserHandle.USER_CURRENT) { 5553 // We don't want to evaluate this until the pending intent is 5554 // actually executed. However, we do want to always do the 5555 // security checking for it above. 5556 userId = UserHandle.USER_CURRENT; 5557 } 5558 5559 if (owningUid != 0 && owningUid != SYSTEM_UID) { 5560 if (!getPackageManagerInternal().isSameApp( 5561 packageName, 5562 MATCH_DEBUG_TRIAGED_MISSING, 5563 owningUid, 5564 UserHandle.getUserId(owningUid))) { 5565 String msg = "Permission Denial: getIntentSender() from pid=" 5566 + Binder.getCallingPid() 5567 + ", uid=" + owningUid 5568 + " is not allowed to send as package " + packageName; 5569 Slog.w(TAG, msg); 5570 throw new SecurityException(msg); 5571 } 5572 } 5573 5574 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 5575 return mAtmInternal.getIntentSender(type, packageName, featureId, owningUid, 5576 userId, token, resultWho, requestCode, intents, resolvedTypes, flags, 5577 bOptions); 5578 } 5579 return mPendingIntentController.getIntentSender(type, packageName, featureId, 5580 owningUid, userId, token, resultWho, requestCode, intents, resolvedTypes, 5581 flags, bOptions); 5582 } 5583 5584 @Override sendIntentSender(IApplicationThread caller, IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5585 public int sendIntentSender(IApplicationThread caller, IIntentSender target, 5586 IBinder allowlistToken, int code, Intent intent, String resolvedType, 5587 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 5588 if (target instanceof PendingIntentRecord) { 5589 final PendingIntentRecord originalRecord = (PendingIntentRecord) target; 5590 5591 addCreatorToken(intent, originalRecord.getPackageName()); 5592 5593 // In multi-display scenarios, there can be background users who execute the 5594 // PendingIntent. In these scenarios, we don't want to use the foreground user as the 5595 // current user. 5596 final PendingIntentRecord.Key originalKey = originalRecord.key; 5597 final UserManagerInternal umInternal = 5598 LocalServices.getService(UserManagerInternal.class); 5599 final int callingUserId = UserHandle.getCallingUserId(); 5600 if (UserManager.isVisibleBackgroundUsersEnabled() 5601 && originalKey.userId == UserHandle.USER_CURRENT 5602 && callingUserId != UserHandle.USER_SYSTEM 5603 && umInternal.isUserVisible(callingUserId)) { 5604 EventLogTags.writeAmIntentSenderRedirectUser(callingUserId); 5605 final PendingIntentRecord.Key key = new PendingIntentRecord.Key(originalKey.type, 5606 originalKey.packageName, originalKey.featureId, originalKey.activity, 5607 originalKey.who, originalKey.requestCode, originalKey.allIntents, 5608 originalKey.allResolvedTypes, originalKey.flags, originalKey.options, 5609 callingUserId); 5610 5611 final PendingIntentRecord newRecord = new PendingIntentRecord( 5612 originalRecord.controller, key, originalRecord.uid); 5613 5614 return newRecord.sendWithResult(caller, code, intent, resolvedType, allowlistToken, 5615 finishedReceiver, requiredPermission, options); 5616 } 5617 5618 return originalRecord.sendWithResult(caller, code, intent, resolvedType, allowlistToken, 5619 finishedReceiver, requiredPermission, options); 5620 } else { 5621 if (intent == null) { 5622 // Weird case: someone has given us their own custom IIntentSender, and now 5623 // they have someone else trying to send to it but of course this isn't 5624 // really a PendingIntent, so there is no base Intent, and the caller isn't 5625 // supplying an Intent... but we never want to dispatch a null Intent to 5626 // a receiver, so um... let's make something up. 5627 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call"); 5628 intent = new Intent(Intent.ACTION_MAIN); 5629 } 5630 try { 5631 final int callingUid = Binder.getCallingUid(); 5632 final String packageName; 5633 final long token = Binder.clearCallingIdentity(); 5634 try { 5635 packageName = AppGlobals.getPackageManager().getNameForUid(callingUid); 5636 } finally { 5637 Binder.restoreCallingIdentity(token); 5638 } 5639 5640 if (allowlistToken != null) { 5641 Slog.wtf(TAG, "Send a non-null allowlistToken to a non-PI target." 5642 + " Calling package: " + packageName + "; intent: " + intent 5643 + "; options: " + options); 5644 } 5645 5646 addCreatorToken(intent, packageName); 5647 5648 target.send(code, intent, resolvedType, null, null, 5649 requiredPermission, options); 5650 } catch (RemoteException e) { 5651 } 5652 // Platform code can rely on getting a result back when the send is done, but if 5653 // this intent sender is from outside of the system we can't rely on it doing that. 5654 // So instead we don't give it the result receiver, and instead just directly 5655 // report the finish immediately. 5656 if (finishedReceiver != null) { 5657 try { 5658 finishedReceiver.performReceive(intent, 0, 5659 null, null, false, false, UserHandle.getCallingUserId()); 5660 } catch (RemoteException e) { 5661 } 5662 } 5663 return 0; 5664 } 5665 } 5666 5667 @Override cancelIntentSender(IIntentSender sender)5668 public void cancelIntentSender(IIntentSender sender) { 5669 mPendingIntentController.cancelIntentSender(sender); 5670 } 5671 5672 @Override registerIntentSenderCancelListenerEx( IIntentSender sender, IResultReceiver receiver)5673 public boolean registerIntentSenderCancelListenerEx( 5674 IIntentSender sender, IResultReceiver receiver) { 5675 return mPendingIntentController.registerIntentSenderCancelListener(sender, receiver); 5676 } 5677 5678 @Override unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5679 public void unregisterIntentSenderCancelListener(IIntentSender sender, 5680 IResultReceiver receiver) { 5681 mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver); 5682 } 5683 5684 @Override getInfoForIntentSender(IIntentSender sender)5685 public PendingIntentInfo getInfoForIntentSender(IIntentSender sender) { 5686 if (sender instanceof PendingIntentRecord) { 5687 final PendingIntentRecord res = (PendingIntentRecord) sender; 5688 final String packageName = res.key.packageName; 5689 final int uid = res.uid; 5690 final boolean shouldFilter = getPackageManagerInternal().filterAppAccess( 5691 packageName, Binder.getCallingUid(), UserHandle.getUserId(uid)); 5692 return new PendingIntentInfo( 5693 shouldFilter ? null : packageName, 5694 shouldFilter ? INVALID_UID : uid, 5695 (res.key.flags & PendingIntent.FLAG_IMMUTABLE) != 0, 5696 res.key.type); 5697 } else { 5698 return new PendingIntentInfo(null, INVALID_UID, false, 5699 ActivityManager.INTENT_SENDER_UNKNOWN); 5700 } 5701 } 5702 5703 @Override isIntentSenderTargetedToPackage(IIntentSender pendingResult)5704 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 5705 if (!(pendingResult instanceof PendingIntentRecord)) { 5706 return false; 5707 } 5708 try { 5709 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5710 if (res.key.allIntents == null) { 5711 return false; 5712 } 5713 for (int i=0; i<res.key.allIntents.length; i++) { 5714 Intent intent = res.key.allIntents[i]; 5715 if (intent.getPackage() != null && intent.getComponent() != null) { 5716 return false; 5717 } 5718 } 5719 return true; 5720 } catch (ClassCastException e) { 5721 } 5722 return false; 5723 } 5724 5725 @Override isIntentSenderAnActivity(IIntentSender pendingResult)5726 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 5727 if (!(pendingResult instanceof PendingIntentRecord)) { 5728 return false; 5729 } 5730 try { 5731 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5732 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 5733 return true; 5734 } 5735 return false; 5736 } catch (ClassCastException e) { 5737 } 5738 return false; 5739 } 5740 5741 @Override getIntentForIntentSender(IIntentSender pendingResult)5742 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 5743 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5744 "getIntentForIntentSender()"); 5745 if (!(pendingResult instanceof PendingIntentRecord)) { 5746 return null; 5747 } 5748 try { 5749 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5750 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 5751 } catch (ClassCastException e) { 5752 } 5753 return null; 5754 } 5755 5756 @Override queryIntentComponentsForIntentSender( IIntentSender pendingResult, int matchFlags)5757 public ParceledListSlice<ResolveInfo> queryIntentComponentsForIntentSender( 5758 IIntentSender pendingResult, int matchFlags) { 5759 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5760 "queryIntentComponentsForIntentSender()"); 5761 Objects.requireNonNull(pendingResult); 5762 final PendingIntentRecord res; 5763 try { 5764 res = (PendingIntentRecord) pendingResult; 5765 } catch (ClassCastException e) { 5766 return null; 5767 } 5768 final Intent intent = res.key.requestIntent; 5769 if (intent == null) { 5770 return null; 5771 } 5772 final int userId = res.key.userId; 5773 final int uid = res.uid; 5774 final String resolvedType = res.key.requestResolvedType; 5775 switch (res.key.type) { 5776 case ActivityManager.INTENT_SENDER_ACTIVITY: 5777 return new ParceledListSlice<>(mPackageManagerInt.queryIntentActivities( 5778 intent, resolvedType, matchFlags, uid, userId)); 5779 case ActivityManager.INTENT_SENDER_SERVICE: 5780 case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE: 5781 return new ParceledListSlice<>(mPackageManagerInt.queryIntentServices( 5782 intent, matchFlags, uid, userId)); 5783 case ActivityManager.INTENT_SENDER_BROADCAST: 5784 return new ParceledListSlice<>(mPackageManagerInt.queryIntentReceivers( 5785 intent, resolvedType, matchFlags, uid, Process.INVALID_PID, userId, false)); 5786 default: // ActivityManager.INTENT_SENDER_ACTIVITY_RESULT 5787 throw new IllegalStateException("Unsupported intent sender type: " + res.key.type); 5788 } 5789 } 5790 5791 @Override getTagForIntentSender(IIntentSender pendingResult, String prefix)5792 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) { 5793 if (!(pendingResult instanceof PendingIntentRecord)) { 5794 return null; 5795 } 5796 try { 5797 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5798 synchronized (this) { 5799 return getTagForIntentSenderLocked(res, prefix); 5800 } 5801 } catch (ClassCastException e) { 5802 } 5803 return null; 5804 } 5805 getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5806 String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) { 5807 final Intent intent = res.key.requestIntent; 5808 if (intent != null) { 5809 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null 5810 || res.lastTagPrefix.equals(prefix))) { 5811 return res.lastTag; 5812 } 5813 res.lastTagPrefix = prefix; 5814 final StringBuilder sb = new StringBuilder(128); 5815 if (prefix != null) { 5816 sb.append(prefix); 5817 } 5818 if (intent.getAction() != null) { 5819 sb.append(intent.getAction()); 5820 } else if (intent.getComponent() != null) { 5821 intent.getComponent().appendShortString(sb); 5822 } else { 5823 sb.append("?"); 5824 } 5825 return res.lastTag = sb.toString(); 5826 } 5827 return null; 5828 } 5829 5830 @Override setProcessLimit(int max)5831 public void setProcessLimit(int max) { 5832 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5833 "setProcessLimit()"); 5834 synchronized (this) { 5835 mConstants.setOverrideMaxCachedProcesses(max); 5836 trimApplicationsLocked(true, OOM_ADJ_REASON_PROCESS_END); 5837 } 5838 } 5839 5840 @Override getProcessLimit()5841 public int getProcessLimit() { 5842 synchronized (this) { 5843 return mConstants.getOverrideMaxCachedProcesses(); 5844 } 5845 } 5846 importanceTokenDied(ImportanceToken token)5847 void importanceTokenDied(ImportanceToken token) { 5848 synchronized (ActivityManagerService.this) { 5849 ProcessRecord pr = null; 5850 synchronized (mPidsSelfLocked) { 5851 ImportanceToken cur 5852 = mImportantProcesses.get(token.pid); 5853 if (cur != token) { 5854 return; 5855 } 5856 mImportantProcesses.remove(token.pid); 5857 pr = mPidsSelfLocked.get(token.pid); 5858 if (pr == null) { 5859 return; 5860 } 5861 mProcessStateController.setForcingToImportant(pr, null); 5862 clearProcessForegroundLocked(pr); 5863 } 5864 mProcessStateController.runUpdate(pr, OOM_ADJ_REASON_UI_VISIBILITY); 5865 } 5866 } 5867 5868 @Override setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5869 public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) { 5870 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5871 "setProcessImportant()"); 5872 synchronized(this) { 5873 boolean changed = false; 5874 5875 ProcessRecord pr = null; 5876 synchronized (mPidsSelfLocked) { 5877 pr = mPidsSelfLocked.get(pid); 5878 if (pr == null && isForeground) { 5879 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 5880 return; 5881 } 5882 ImportanceToken oldToken = mImportantProcesses.get(pid); 5883 if (oldToken != null) { 5884 oldToken.token.unlinkToDeath(oldToken, 0); 5885 mImportantProcesses.remove(pid); 5886 if (pr != null) { 5887 mProcessStateController.setForcingToImportant(pr, null); 5888 } 5889 changed = true; 5890 } 5891 if (isForeground && token != null) { 5892 ImportanceToken newToken = new ImportanceToken(pid, token, reason) { 5893 @Override 5894 public void binderDied() { 5895 importanceTokenDied(this); 5896 } 5897 }; 5898 try { 5899 token.linkToDeath(newToken, 0); 5900 mImportantProcesses.put(pid, newToken); 5901 mProcessStateController.setForcingToImportant(pr, newToken); 5902 changed = true; 5903 } catch (RemoteException e) { 5904 // If the process died while doing this, we will later 5905 // do the cleanup with the process death link. 5906 } 5907 } 5908 } 5909 5910 if (changed) { 5911 mProcessStateController.runUpdate(pr, OOM_ADJ_REASON_UI_VISIBILITY); 5912 } 5913 } 5914 } 5915 isAppForeground(int uid)5916 private boolean isAppForeground(int uid) { 5917 synchronized (mProcLock) { 5918 UidRecord uidRec = mProcessList.mActiveUids.get(uid); 5919 if (uidRec == null || uidRec.isIdle()) { 5920 return false; 5921 } 5922 return uidRec.getCurProcState() <= PROCESS_STATE_IMPORTANT_FOREGROUND; 5923 } 5924 } 5925 isAppBad(final String processName, final int uid)5926 private boolean isAppBad(final String processName, final int uid) { 5927 return mAppErrors.isBadProcess(processName, uid); 5928 } 5929 5930 // NOTE: this is an internal method used by the OnShellCommand implementation only and should 5931 // be guarded by permission checking. getUidState(int uid)5932 int getUidState(int uid) { 5933 synchronized (mProcLock) { 5934 return mProcessList.getUidProcStateLOSP(uid); 5935 } 5936 } 5937 5938 @GuardedBy("this") getUidStateLocked(int uid)5939 int getUidStateLocked(int uid) { 5940 return mProcessList.getUidProcStateLOSP(uid); 5941 } 5942 5943 @GuardedBy("this") getUidProcessCapabilityLocked(int uid)5944 int getUidProcessCapabilityLocked(int uid) { 5945 return mProcessList.getUidProcessCapabilityLOSP(uid); 5946 } 5947 5948 // ========================================================= 5949 // PROCESS INFO 5950 // ========================================================= 5951 5952 static class ProcessInfoService extends IProcessInfoService.Stub { 5953 final ActivityManagerService mActivityManagerService; ProcessInfoService(ActivityManagerService activityManagerService)5954 ProcessInfoService(ActivityManagerService activityManagerService) { 5955 mActivityManagerService = activityManagerService; 5956 } 5957 5958 @Override getProcessStatesFromPids( int[] pids, int[] states)5959 public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) { 5960 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 5961 /*in*/ pids, /*out*/ states, null); 5962 } 5963 5964 @Override getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5965 public void getProcessStatesAndOomScoresFromPids( 5966 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 5967 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 5968 /*in*/ pids, /*out*/ states, /*out*/ scores); 5969 } 5970 } 5971 5972 /** 5973 * For each PID in the given input array, write the current process state 5974 * for that process into the states array, or -1 to indicate that no 5975 * process with the given PID exists. If scores array is provided, write 5976 * the oom score for the process into the scores array, with INVALID_ADJ 5977 * indicating the PID doesn't exist. 5978 */ getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5979 public void getProcessStatesAndOomScoresForPIDs( 5980 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 5981 if (scores != null) { 5982 enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE, 5983 "getProcessStatesAndOomScoresForPIDs()"); 5984 } 5985 5986 if (pids == null) { 5987 throw new NullPointerException("pids"); 5988 } else if (states == null) { 5989 throw new NullPointerException("states"); 5990 } else if (pids.length != states.length) { 5991 throw new IllegalArgumentException("pids and states arrays have different lengths!"); 5992 } else if (scores != null && pids.length != scores.length) { 5993 throw new IllegalArgumentException("pids and scores arrays have different lengths!"); 5994 } 5995 5996 synchronized (mProcLock) { 5997 int newestTimeIndex = -1; 5998 long newestTime = Long.MIN_VALUE; 5999 for (int i = 0; i < pids.length; i++) { 6000 final ProcessRecord pr; 6001 synchronized (mPidsSelfLocked) { 6002 pr = mPidsSelfLocked.get(pids[i]); 6003 } 6004 if (pr != null) { 6005 final long pendingTopTime = 6006 mPendingStartActivityUids.getPendingTopPidTime(pr.uid, pids[i]); 6007 if (pendingTopTime != PendingStartActivityUids.INVALID_TIME) { 6008 // The uid in mPendingStartActivityUids gets the TOP process state. 6009 states[i] = PROCESS_STATE_TOP; 6010 if (scores != null) { 6011 // The uid in mPendingStartActivityUids gets a better score. 6012 scores[i] = ProcessList.FOREGROUND_APP_ADJ - 1; 6013 } 6014 if (pendingTopTime > newestTime) { 6015 newestTimeIndex = i; 6016 newestTime = pendingTopTime; 6017 } 6018 } else { 6019 states[i] = pr.mState.getCurProcState(); 6020 if (scores != null) { 6021 scores[i] = pr.mState.getCurAdj(); 6022 } 6023 } 6024 } else { 6025 states[i] = PROCESS_STATE_NONEXISTENT; 6026 if (scores != null) { 6027 scores[i] = ProcessList.INVALID_ADJ; 6028 } 6029 } 6030 } 6031 // The uid with the newest timestamp in mPendingStartActivityUids gets the best 6032 // score. 6033 if (newestTimeIndex != -1) { 6034 if (scores != null) { 6035 scores[newestTimeIndex] = ProcessList.FOREGROUND_APP_ADJ - 2; 6036 } 6037 } 6038 } 6039 } 6040 6041 // ========================================================= 6042 // PERMISSIONS 6043 // ========================================================= 6044 6045 static class PermissionController extends IPermissionController.Stub { 6046 ActivityManagerService mActivityManagerService; PermissionController(ActivityManagerService activityManagerService)6047 PermissionController(ActivityManagerService activityManagerService) { 6048 mActivityManagerService = activityManagerService; 6049 } 6050 6051 @Override checkPermission(String permission, int pid, int uid)6052 public boolean checkPermission(String permission, int pid, int uid) { 6053 return mActivityManagerService.checkPermission(permission, pid, 6054 uid) == PackageManager.PERMISSION_GRANTED; 6055 } 6056 6057 @Override noteOp(String op, int uid, String packageName)6058 public int noteOp(String op, int uid, String packageName) { 6059 // TODO moltmann: Allow to specify featureId 6060 return mActivityManagerService.mAppOpsService 6061 .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName, null, 6062 false, "", false).getOpMode(); 6063 } 6064 6065 @Override getPackagesForUid(int uid)6066 public String[] getPackagesForUid(int uid) { 6067 return mActivityManagerService.mContext.getPackageManager() 6068 .getPackagesForUid(uid); 6069 } 6070 6071 @Override isRuntimePermission(String permission)6072 public boolean isRuntimePermission(String permission) { 6073 try { 6074 PermissionInfo info = mActivityManagerService.mContext.getPackageManager() 6075 .getPermissionInfo(permission, 0); 6076 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 6077 == PermissionInfo.PROTECTION_DANGEROUS; 6078 } catch (NameNotFoundException nnfe) { 6079 Slog.e(TAG, "No such permission: "+ permission, nnfe); 6080 } 6081 return false; 6082 } 6083 6084 @Override getPackageUid(String packageName, int flags)6085 public int getPackageUid(String packageName, int flags) { 6086 try { 6087 return mActivityManagerService.mContext.getPackageManager() 6088 .getPackageUid(packageName, flags); 6089 } catch (NameNotFoundException nnfe) { 6090 return -1; 6091 } 6092 } 6093 } 6094 6095 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 6096 @Override checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)6097 public int checkComponentPermission(String permission, int pid, int uid, 6098 int owningUid, boolean exported) { 6099 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 6100 owningUid, exported); 6101 } 6102 6103 @Override getAMSLock()6104 public Object getAMSLock() { 6105 return ActivityManagerService.this; 6106 } 6107 } 6108 6109 /** 6110 * Allows if {@code pid} is {@link #MY_PID}, then denies if the {@code pid} has been denied 6111 * provided non-{@code null} {@code permission} before. Otherwise calls into 6112 * {@link ActivityManager#checkComponentPermission(String, int, int, int, boolean)}. 6113 */ 6114 @PackageManager.PermissionResult 6115 @PermissionMethod checkComponentPermission(@ermissionName String permission, int pid, int uid, int owningUid, boolean exported)6116 public static int checkComponentPermission(@PermissionName String permission, int pid, int uid, 6117 int owningUid, boolean exported) { 6118 return checkComponentPermission(permission, pid, uid, Context.DEVICE_ID_DEFAULT, 6119 owningUid, exported); 6120 } 6121 6122 /** 6123 * Allows if {@code pid} is {@link #MY_PID}, then denies if the {@code pid} has been denied 6124 * provided non-{@code null} {@code permission} before. Otherwise calls into 6125 * {@link ActivityManager#checkComponentPermission(String, int, int, int, boolean)}. 6126 */ 6127 @PackageManager.PermissionResult 6128 @PermissionMethod checkComponentPermission(@ermissionName String permission, int pid, int uid, int deviceId, int owningUid, boolean exported)6129 public static int checkComponentPermission(@PermissionName String permission, int pid, int uid, 6130 int deviceId, int owningUid, boolean exported) { 6131 if (pid == MY_PID) { 6132 return PackageManager.PERMISSION_GRANTED; 6133 } 6134 // If there is an explicit permission being checked, and this is coming from a process 6135 // that has been denied access to that permission, then just deny. Ultimately this may 6136 // not be quite right -- it means that even if the caller would have access for another 6137 // reason (such as being the owner of the component it is trying to access), it would still 6138 // fail. This also means the system and root uids would be able to deny themselves 6139 // access to permissions, which... well okay. ¯\_(ツ)_/¯ 6140 if (permission != null) { 6141 synchronized (sActiveProcessInfoSelfLocked) { 6142 ProcessInfo procInfo = sActiveProcessInfoSelfLocked.get(pid); 6143 if (procInfo != null && procInfo.deniedPermissions != null 6144 && procInfo.deniedPermissions.contains(permission)) { 6145 return PackageManager.PERMISSION_DENIED; 6146 } 6147 } 6148 } 6149 return ActivityManager.checkComponentPermission(permission, uid, deviceId, 6150 owningUid, exported); 6151 } 6152 enforceDebuggable(ProcessRecord proc)6153 private void enforceDebuggable(ProcessRecord proc) { 6154 if (!Build.IS_DEBUGGABLE && !proc.isDebuggable()) { 6155 throw new SecurityException("Process not debuggable: " + proc.info.packageName); 6156 } 6157 } 6158 enforceDebuggable(ApplicationInfo info)6159 private void enforceDebuggable(ApplicationInfo info) { 6160 if (!Build.IS_DEBUGGABLE && (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 6161 throw new SecurityException("Process not debuggable: " + info.packageName); 6162 } 6163 } 6164 6165 /** 6166 * As the only public entry point for permissions checking, this method 6167 * can enforce the semantic that requesting a check on a null global 6168 * permission is automatically denied. (Internally a null permission 6169 * string is used when calling {@link #checkComponentPermission} in cases 6170 * when only uid-based security is needed.) 6171 * 6172 * This can be called with or without the global lock held. 6173 */ 6174 @Override 6175 @PackageManager.PermissionResult 6176 @PermissionMethod checkPermission(@ermissionName String permission, int pid, int uid)6177 public int checkPermission(@PermissionName String permission, int pid, int uid) { 6178 return checkPermissionForDevice(permission, pid, uid, Context.DEVICE_ID_DEFAULT); 6179 } 6180 6181 /** 6182 * As the only public entry point for permissions checking, this method 6183 * can enforce the semantic that requesting a check on a null global 6184 * permission is automatically denied. (Internally a null permission 6185 * string is used when calling {@link #checkComponentPermission} in cases 6186 * when only uid-based security is needed.) 6187 * 6188 * This can be called with or without the global lock held. 6189 */ 6190 @Override 6191 @PackageManager.PermissionResult 6192 @PermissionMethod checkPermissionForDevice(@ermissionName String permission, int pid, int uid, int deviceId)6193 public int checkPermissionForDevice(@PermissionName String permission, int pid, int uid, 6194 int deviceId) { 6195 if (permission == null) { 6196 return PackageManager.PERMISSION_DENIED; 6197 } 6198 return checkComponentPermission(permission, pid, uid, deviceId, -1, true); 6199 } 6200 6201 /** 6202 * Binder IPC calls go through the public entry point. 6203 * This can be called with or without the global lock held. 6204 */ 6205 @PackageManager.PermissionResult 6206 @PermissionMethod checkCallingPermission(@ermissionName String permission)6207 int checkCallingPermission(@PermissionName String permission) { 6208 return checkPermission(permission, 6209 Binder.getCallingPid(), 6210 Binder.getCallingUid()); 6211 } 6212 6213 /** 6214 * This can be called with or without the global lock held. 6215 */ 6216 @PermissionMethod enforceCallingPermission(@ermissionName String permission, String func)6217 void enforceCallingPermission(@PermissionName String permission, String func) { 6218 if (checkCallingPermission(permission) 6219 == PackageManager.PERMISSION_GRANTED) { 6220 return; 6221 } 6222 6223 String msg = "Permission Denial: " + func + " from pid=" 6224 + Binder.getCallingPid() 6225 + ", uid=" + Binder.getCallingUid() 6226 + " requires " + permission; 6227 Slog.w(TAG, msg); 6228 throw new SecurityException(msg); 6229 } 6230 6231 /** 6232 * This can be called with or without the global lock held. 6233 */ 6234 @PermissionMethod(anyOf = true) enforceCallingHasAtLeastOnePermission(String func, String... permissions)6235 private void enforceCallingHasAtLeastOnePermission(String func, String... permissions) { 6236 for (String permission : permissions) { 6237 if (checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) { 6238 return; 6239 } 6240 } 6241 6242 String msg = "Permission Denial: " + func + " from pid=" 6243 + Binder.getCallingPid() 6244 + ", uid=" + Binder.getCallingUid() 6245 + " requires one of " + Arrays.toString(permissions); 6246 Slog.w(TAG, msg); 6247 throw new SecurityException(msg); 6248 } 6249 6250 /** 6251 * This can be called with or without the global lock held. 6252 */ 6253 @PermissionMethod enforcePermission(@ermissionName String permission, int pid, int uid, String func)6254 void enforcePermission(@PermissionName String permission, int pid, int uid, String func) { 6255 if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) { 6256 return; 6257 } 6258 6259 String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid 6260 + " requires " + permission; 6261 Slog.w(TAG, msg); 6262 throw new SecurityException(msg); 6263 } 6264 isAppStartModeDisabled(int uid, String packageName)6265 public boolean isAppStartModeDisabled(int uid, String packageName) { 6266 synchronized (mProcLock) { 6267 return getAppStartModeLOSP(uid, packageName, 0, -1, false, true, false) 6268 == ActivityManager.APP_START_MODE_DISABLED; 6269 } 6270 } 6271 isInRestrictedBucket(int userId, String packageName, long nowElapsed)6272 private boolean isInRestrictedBucket(int userId, String packageName, long nowElapsed) { 6273 return UsageStatsManager.STANDBY_BUCKET_RESTRICTED 6274 <= mUsageStatsService.getAppStandbyBucket(packageName, userId, nowElapsed); 6275 } 6276 6277 // Unified app-op and target sdk check 6278 @GuardedBy(anyOf = {"this", "mProcLock"}) appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6279 int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) { 6280 // Apps that target O+ are always subject to background check 6281 if (packageTargetSdk >= Build.VERSION_CODES.O) { 6282 if (DEBUG_BACKGROUND_CHECK) { 6283 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted"); 6284 } 6285 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 6286 } 6287 // It's a legacy app. If it's in the RESTRICTED bucket, always restrict on battery. 6288 if (mOnBattery // Short-circuit in common case. 6289 && mConstants.FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS 6290 && isInRestrictedBucket( 6291 UserHandle.getUserId(uid), packageName, SystemClock.elapsedRealtime())) { 6292 if (DEBUG_BACKGROUND_CHECK) { 6293 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " in RESTRICTED bucket"); 6294 } 6295 return ActivityManager.APP_START_MODE_DELAYED; 6296 } 6297 // Not in the RESTRICTED bucket so policy is based on AppOp check. 6298 int appop = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_RUN_IN_BACKGROUND, 6299 uid, packageName, null, ""); 6300 if (DEBUG_BACKGROUND_CHECK) { 6301 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop); 6302 } 6303 switch (appop) { 6304 case AppOpsManager.MODE_ALLOWED: 6305 // If force-background-check is enabled, restrict all apps that aren't allowlisted. 6306 if (mForceBackgroundCheck && 6307 !UserHandle.isCore(uid) && 6308 !isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ true)) { 6309 if (DEBUG_BACKGROUND_CHECK) { 6310 Slog.i(TAG, "Force background check: " + 6311 uid + "/" + packageName + " restricted"); 6312 } 6313 return ActivityManager.APP_START_MODE_DELAYED; 6314 } 6315 return ActivityManager.APP_START_MODE_NORMAL; 6316 case AppOpsManager.MODE_IGNORED: 6317 return ActivityManager.APP_START_MODE_DELAYED; 6318 default: 6319 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 6320 } 6321 } 6322 6323 // Service launch is available to apps with run-in-background exemptions but 6324 // some other background operations are not. If we're doing a check 6325 // of service-launch policy, allow those callers to proceed unrestricted. 6326 @GuardedBy(anyOf = {"this", "mProcLock"}) appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6327 int appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) { 6328 // Persistent app? 6329 if (mPackageManagerInt.isPackagePersistent(packageName)) { 6330 if (DEBUG_BACKGROUND_CHECK) { 6331 Slog.i(TAG, "App " + uid + "/" + packageName 6332 + " is persistent; not restricted in background"); 6333 } 6334 return ActivityManager.APP_START_MODE_NORMAL; 6335 } 6336 6337 // Non-persistent but background whitelisted? 6338 if (uidOnBackgroundAllowlistLOSP(uid)) { 6339 if (DEBUG_BACKGROUND_CHECK) { 6340 Slog.i(TAG, "App " + uid + "/" + packageName 6341 + " on background allowlist; not restricted in background"); 6342 } 6343 return ActivityManager.APP_START_MODE_NORMAL; 6344 } 6345 6346 // Is this app on the battery whitelist? 6347 if (isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ false)) { 6348 if (DEBUG_BACKGROUND_CHECK) { 6349 Slog.i(TAG, "App " + uid + "/" + packageName 6350 + " on idle allowlist; not restricted in background"); 6351 } 6352 return ActivityManager.APP_START_MODE_NORMAL; 6353 } 6354 6355 // None of the service-policy criteria apply, so we apply the common criteria 6356 return appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk); 6357 } 6358 6359 @GuardedBy(anyOf = {"this", "mProcLock"}) getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6360 int getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, 6361 int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) { 6362 if (mInternal.isPendingTopUid(uid)) { 6363 return ActivityManager.APP_START_MODE_NORMAL; 6364 } 6365 UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 6366 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg=" 6367 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle=" 6368 + (uidRec != null ? uidRec.isIdle() : false)); 6369 if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.isIdle()) { 6370 boolean ephemeral; 6371 if (uidRec == null) { 6372 ephemeral = getPackageManagerInternal().isPackageEphemeral( 6373 UserHandle.getUserId(uid), packageName); 6374 } else { 6375 ephemeral = uidRec.isEphemeral(); 6376 } 6377 6378 if (ephemeral) { 6379 // We are hard-core about ephemeral apps not running in the background. 6380 return ActivityManager.APP_START_MODE_DISABLED; 6381 } else { 6382 if (disabledOnly) { 6383 // The caller is only interested in whether app starts are completely 6384 // disabled for the given package (that is, it is an instant app). So 6385 // we don't need to go further, which is all just seeing if we should 6386 // apply a "delayed" mode for a regular app. 6387 return ActivityManager.APP_START_MODE_NORMAL; 6388 } 6389 final int startMode = (alwaysRestrict) 6390 ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk) 6391 : appServicesRestrictedInBackgroundLOSP(uid, packageName, 6392 packageTargetSdk); 6393 if (DEBUG_BACKGROUND_CHECK) { 6394 Slog.d(TAG, "checkAllowBackground: uid=" + uid 6395 + " pkg=" + packageName + " startMode=" + startMode 6396 + " onallowlist=" + isOnDeviceIdleAllowlistLOSP(uid, false) 6397 + " onallowlist(ei)=" + isOnDeviceIdleAllowlistLOSP(uid, true)); 6398 } 6399 if (startMode == ActivityManager.APP_START_MODE_DELAYED) { 6400 // This is an old app that has been forced into a "compatible as possible" 6401 // mode of background check. To increase compatibility, we will allow other 6402 // foreground apps to cause its services to start. 6403 if (callingPid >= 0) { 6404 ProcessRecord proc; 6405 synchronized (mPidsSelfLocked) { 6406 proc = mPidsSelfLocked.get(callingPid); 6407 } 6408 if (proc != null && !ActivityManager.isProcStateBackground( 6409 proc.mState.getCurProcState())) { 6410 // Whoever is instigating this is in the foreground, so we will allow it 6411 // to go through. 6412 return ActivityManager.APP_START_MODE_NORMAL; 6413 } 6414 } 6415 } 6416 return startMode; 6417 } 6418 } 6419 return ActivityManager.APP_START_MODE_NORMAL; 6420 } 6421 6422 /** 6423 * @return whether a UID is in the system, user or temp doze allowlist. 6424 */ 6425 @GuardedBy(anyOf = {"this", "mProcLock"}) isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo)6426 boolean isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo) { 6427 final int appId = UserHandle.getAppId(uid); 6428 6429 final int[] allowlist = allowExceptIdleToo 6430 ? mDeviceIdleExceptIdleAllowlist 6431 : mDeviceIdleAllowlist; 6432 6433 return Arrays.binarySearch(allowlist, appId) >= 0 6434 || Arrays.binarySearch(mDeviceIdleTempAllowlist, appId) >= 0 6435 || mPendingTempAllowlist.get(uid) != null; 6436 } 6437 6438 /** 6439 * Is the uid allowlisted to start FGS? 6440 * @param uid 6441 * @return a TempAllowListEntry if the uid is allowed. 6442 * null if the uid is not allowed. 6443 */ 6444 @Nullable 6445 @GuardedBy(anyOf = {"this", "mProcLock"}) isAllowlistedForFgsStartLOSP(int uid)6446 FgsTempAllowListItem isAllowlistedForFgsStartLOSP(int uid) { 6447 if (Arrays.binarySearch(mDeviceIdleExceptIdleAllowlist, UserHandle.getAppId(uid)) >= 0) { 6448 return FAKE_TEMP_ALLOW_LIST_ITEM; 6449 } 6450 final Pair<Long, FgsTempAllowListItem> entry = mFgsStartTempAllowList.get(uid); 6451 return entry == null ? null : entry.second; 6452 } 6453 6454 private static class GetBackgroundStartPrivilegesFunctor implements Consumer<ProcessRecord> { 6455 private BackgroundStartPrivileges mBackgroundStartPrivileges = 6456 BackgroundStartPrivileges.NONE; 6457 private int mUid; 6458 prepare(int uid)6459 void prepare(int uid) { 6460 mUid = uid; 6461 mBackgroundStartPrivileges = BackgroundStartPrivileges.NONE; 6462 } 6463 6464 @NonNull getResult()6465 BackgroundStartPrivileges getResult() { 6466 return mBackgroundStartPrivileges; 6467 } 6468 accept(ProcessRecord pr)6469 public void accept(ProcessRecord pr) { 6470 if (pr.uid == mUid) { 6471 mBackgroundStartPrivileges = 6472 mBackgroundStartPrivileges.merge(pr.getBackgroundStartPrivileges()); 6473 } 6474 } 6475 } 6476 6477 private final GetBackgroundStartPrivilegesFunctor mGetBackgroundStartPrivilegesFunctor = 6478 new GetBackgroundStartPrivilegesFunctor(); 6479 6480 /** 6481 * Returns the current complete {@link BackgroundStartPrivileges} of the UID. 6482 */ 6483 @NonNull getBackgroundStartPrivileges(int uid)6484 private BackgroundStartPrivileges getBackgroundStartPrivileges(int uid) { 6485 synchronized (mProcLock) { 6486 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 6487 if (uidRecord == null) { 6488 return BackgroundStartPrivileges.NONE; 6489 } 6490 mGetBackgroundStartPrivilegesFunctor.prepare(uid); 6491 uidRecord.forEachProcess(mGetBackgroundStartPrivilegesFunctor); 6492 return mGetBackgroundStartPrivilegesFunctor.getResult(); 6493 } 6494 } 6495 6496 /** 6497 * Returns true if the reasonCode is included in the base set of reasons an app may be 6498 * allowed to schedule a 6499 * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}. 6500 * This is a shortcut and <b>DOES NOT</b> include all reasons. 6501 * Use {@link #canScheduleUserInitiatedJobs(int, int, String)} to cover all cases. 6502 */ doesReasonCodeAllowSchedulingUserInitiatedJobs(int reasonCode, int uid)6503 static boolean doesReasonCodeAllowSchedulingUserInitiatedJobs(int reasonCode, int uid) { 6504 switch (reasonCode) { 6505 case REASON_PROC_STATE_PERSISTENT: 6506 case REASON_PROC_STATE_PERSISTENT_UI: 6507 case REASON_PROC_STATE_TOP: 6508 case REASON_PROC_STATE_BTOP: 6509 case REASON_UID_VISIBLE: 6510 case REASON_SYSTEM_UID: 6511 case REASON_START_ACTIVITY_FLAG: 6512 case REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD: 6513 case REASON_COMPANION_DEVICE_MANAGER: 6514 case REASON_BACKGROUND_ACTIVITY_PERMISSION: 6515 case REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION: 6516 return true; 6517 case REASON_SYSTEM_ALERT_WINDOW_PERMISSION: 6518 if (!Flags.fgsDisableSaw() 6519 || !CompatChanges.isChangeEnabled(FGS_SAW_RESTRICTIONS, uid)) { 6520 return true; 6521 } else { 6522 // With the new SAW restrictions starting Android V, only allow the app to 6523 // schedule a user-initiated job if it's currently showing an overlay window 6524 // in additional to holding the permission - this additional logic will be 6525 // checked in #canScheduleUserInitiatedJobs(int, int, String) below since this 6526 // method is simply a shortcut for checking based on the reason codes. 6527 } 6528 } 6529 return false; 6530 } 6531 6532 /** 6533 * Returns true if the ProcessRecord has some conditions that allow the app to schedule a 6534 * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}. 6535 * This is a shortcut and <b>DOES NOT</b> include all reasons. 6536 * Use {@link #canScheduleUserInitiatedJobs(int, int, String)} to cover all cases. 6537 */ 6538 @GuardedBy(anyOf = {"this", "mProcLock"}) isProcessInStateToScheduleUserInitiatedJobsLocked( @ullable ProcessRecord pr, long nowElapsed, int uid)6539 private boolean isProcessInStateToScheduleUserInitiatedJobsLocked( 6540 @Nullable ProcessRecord pr, long nowElapsed, int uid) { 6541 if (pr == null) { 6542 return false; 6543 } 6544 6545 final BackgroundStartPrivileges backgroundStartPrivileges = 6546 pr.getBackgroundStartPrivileges(); 6547 // Is the allow activity background start flag on? 6548 if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) { 6549 // REASON_START_ACTIVITY_FLAG; 6550 return true; 6551 } 6552 6553 final ProcessStateRecord state = pr.mState; 6554 final int procstate = state.getCurProcState(); 6555 if (procstate <= PROCESS_STATE_BOUND_TOP) { 6556 if (doesReasonCodeAllowSchedulingUserInitiatedJobs( 6557 getReasonCodeFromProcState(procstate), uid)) { 6558 return true; 6559 } 6560 } 6561 6562 final long lastInvisibleTime = state.getLastInvisibleTime(); 6563 if (lastInvisibleTime > 0 && lastInvisibleTime < Long.MAX_VALUE) { 6564 final long timeSinceVisibleMs = nowElapsed - lastInvisibleTime; 6565 if (timeSinceVisibleMs < mConstants.mVisibleToInvisibleUijScheduleGraceDurationMs) { 6566 // REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD 6567 return true; 6568 } 6569 } 6570 6571 final ProcessServiceRecord psr = pr.mServices; 6572 if (psr != null && psr.hasForegroundServices()) { 6573 for (int s = psr.numberOfRunningServices() - 1; s >= 0; --s) { 6574 final ServiceRecord sr = psr.getRunningServiceAt(s); 6575 if (sr.isForeground && sr.mAllowUiJobScheduling) { 6576 return true; 6577 } 6578 } 6579 } 6580 6581 return false; 6582 } 6583 6584 /** 6585 * Returns whether the app in question is in a state where we allow scheduling a 6586 * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}. 6587 */ 6588 // TODO(262260570): log allow reason to an atom canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)6589 boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName) { 6590 synchronized (this) { 6591 final ProcessRecord processRecord; 6592 synchronized (mPidsSelfLocked) { 6593 processRecord = mPidsSelfLocked.get(pid); 6594 } 6595 6596 final long nowElapsed = SystemClock.elapsedRealtime(); 6597 final BackgroundStartPrivileges backgroundStartPrivileges; 6598 if (processRecord != null) { 6599 if (isProcessInStateToScheduleUserInitiatedJobsLocked( 6600 processRecord, nowElapsed, uid)) { 6601 return true; 6602 } 6603 backgroundStartPrivileges = processRecord.getBackgroundStartPrivileges(); 6604 } else { 6605 backgroundStartPrivileges = getBackgroundStartPrivileges(uid); 6606 } 6607 // Is the allow activity background start flag on? 6608 if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) { 6609 // REASON_START_ACTIVITY_FLAG; 6610 return true; 6611 } 6612 6613 // We allow scheduling a user-initiated job when the app is in the TOP or a 6614 // Background Activity Launch approved state. These are cases that indicate the user 6615 // has interacted with the app and therefore it is reasonable to believe the app may 6616 // attempt to schedule a user-initiated job in response to the user interaction. 6617 // As of Android UDC, the conditions required to grant a while-in-use permission 6618 // covers the majority of those cases, and so we piggyback on that logic as the base. 6619 // Missing cases are added after. 6620 if (mServices.canAllowWhileInUsePermissionInFgsLocked( 6621 pid, uid, pkgName, processRecord, backgroundStartPrivileges)) { 6622 return true; 6623 } 6624 6625 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 6626 final boolean hasSawPermission = mAtmInternal.hasSystemAlertWindowPermission(uid, pid, 6627 pkgName); 6628 final boolean strictSawCheckEnabled = Flags.fgsDisableSaw() 6629 && CompatChanges.isChangeEnabled(FGS_SAW_RESTRICTIONS, uid); 6630 if (uidRecord != null) { 6631 for (int i = uidRecord.getNumOfProcs() - 1; i >= 0; --i) { 6632 ProcessRecord pr = uidRecord.getProcessRecordByIndex(i); 6633 if (isProcessInStateToScheduleUserInitiatedJobsLocked(pr, nowElapsed, uid)) { 6634 return true; 6635 } else if (hasSawPermission && strictSawCheckEnabled) { 6636 // isProcessInStateToScheduleUserInitiatedJobsLocked() doesn't do a strict 6637 // check for the SAW permission which is enabled from V onwards, so perform 6638 // that here (pre-V versions will be checked in the conditional below) 6639 // Starting Android V, only allow the app to schedule a user-initiated job 6640 // if it's granted the permission and currently showing an overlay window 6641 if (pr != null && pr.mState.hasOverlayUi()) { 6642 return true; 6643 } 6644 } 6645 } 6646 } 6647 6648 if (hasSawPermission && !strictSawCheckEnabled) { 6649 // REASON_SYSTEM_ALERT_WINDOW_PERMISSION (pre-V) 6650 return true; 6651 } 6652 6653 final int userId = UserHandle.getUserId(uid); 6654 final boolean isCompanionApp = mInternal.isAssociatedCompanionApp(userId, uid); 6655 if (isCompanionApp) { 6656 if (checkPermission(REQUEST_COMPANION_RUN_IN_BACKGROUND, pid, uid) 6657 == PERMISSION_GRANTED) { 6658 // REASON_COMPANION_DEVICE_MANAGER; 6659 return true; 6660 } 6661 } 6662 } 6663 6664 return false; 6665 } 6666 6667 /** 6668 * @return allowlist tag for a uid from mPendingTempAllowlist, null if not currently on 6669 * the allowlist 6670 */ 6671 @GuardedBy(anyOf = {"this", "mProcLock"}) getPendingTempAllowlistTagForUidLOSP(int uid)6672 String getPendingTempAllowlistTagForUidLOSP(int uid) { 6673 final PendingTempAllowlist ptw = mPendingTempAllowlist.get(uid); 6674 return ptw != null ? ptw.tag : null; 6675 } 6676 6677 @VisibleForTesting grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId)6678 public void grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId) { 6679 getPackageManagerInternal() 6680 .grantImplicitAccess(userId, intent, recipientAppId, visibleUid, true /*direct*/); 6681 } 6682 6683 /** 6684 * @param uri This uri must NOT contain an embedded userId. 6685 * @param userId The userId in which the uri is to be resolved. 6686 */ 6687 @Override checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6688 public int checkUriPermission(Uri uri, int pid, int uid, 6689 final int modeFlags, int userId, IBinder callerToken) { 6690 return checkUriPermission(uri, pid, uid, modeFlags, userId, 6691 /* isFullAccessForContentUri */ false, "checkUriPermission"); 6692 } 6693 6694 /** 6695 * @param uri This uri must NOT contain an embedded userId. 6696 * @param userId The userId in which the uri is to be resolved. 6697 */ 6698 @Override checkContentUriPermissionFull(Uri uri, int pid, int uid, final int modeFlags, int userId)6699 public int checkContentUriPermissionFull(Uri uri, int pid, int uid, 6700 final int modeFlags, int userId) { 6701 return checkUriPermission(uri, pid, uid, modeFlags, userId, 6702 /* isFullAccessForContentUri */ true, "checkContentUriPermissionFull"); 6703 } 6704 checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, boolean isFullAccessForContentUri, String methodName)6705 private int checkUriPermission(Uri uri, int pid, int uid, 6706 final int modeFlags, int userId, boolean isFullAccessForContentUri, String methodName) { 6707 enforceNotIsolatedCaller(methodName); 6708 6709 // Our own process gets to do everything. 6710 if (pid == MY_PID) { 6711 return PackageManager.PERMISSION_GRANTED; 6712 } 6713 if (uid != ROOT_UID) { // bypass the root 6714 if (mPackageManagerInt.filterAppAccess(uid, Binder.getCallingUid())) { 6715 return PackageManager.PERMISSION_DENIED; 6716 } 6717 } 6718 boolean granted = mUgmInternal.checkUriPermission(new GrantUri(userId, uri, modeFlags), uid, 6719 modeFlags, isFullAccessForContentUri); 6720 6721 return granted ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED; 6722 } 6723 6724 @Override checkUriPermissions(@onNull List<Uri> uris, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6725 public int[] checkUriPermissions(@NonNull List<Uri> uris, int pid, int uid, 6726 final int modeFlags, int userId, IBinder callerToken) { 6727 final int size = uris.size(); 6728 int[] res = new int[size]; 6729 // Default value DENIED. 6730 Arrays.fill(res, PackageManager.PERMISSION_DENIED); 6731 6732 for (int i = 0; i < size; i++) { 6733 final Uri uri = uris.get(i); 6734 final int userIdFromUri = ContentProvider.getUserIdFromUri(uri, userId); 6735 res[i] = checkUriPermission(ContentProvider.getUriWithoutUserId(uri), pid, uid, 6736 modeFlags, userIdFromUri, callerToken); 6737 } 6738 return res; 6739 } 6740 6741 /** 6742 * @param uri This uri must NOT contain an embedded userId. 6743 * @param userId The userId in which the uri is to be resolved. 6744 */ 6745 @Override grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6746 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 6747 final int modeFlags, int userId) { 6748 enforceNotIsolatedCaller("grantUriPermission"); 6749 GrantUri grantUri = new GrantUri(userId, uri, modeFlags); 6750 synchronized (this) { 6751 final ProcessRecord r = getRecordForAppLOSP(caller); 6752 if (r == null) { 6753 throw new SecurityException("Unable to find app for caller " 6754 + caller 6755 + " when granting permission to uri " + grantUri); 6756 } 6757 if (targetPkg == null) { 6758 throw new IllegalArgumentException("null target"); 6759 } 6760 final int callingUserId = UserHandle.getUserId(r.uid); 6761 if (mPackageManagerInt.filterAppAccess(targetPkg, r.uid, callingUserId)) { 6762 return; 6763 } 6764 6765 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 6766 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 6767 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 6768 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 6769 6770 final Intent intent = new Intent(); 6771 intent.setData(ContentProvider.maybeAddUserId(uri, userId)); 6772 intent.setFlags(modeFlags); 6773 6774 final NeededUriGrants needed = mUgmInternal.checkGrantUriPermissionFromIntent(intent, 6775 r.uid, targetPkg, callingUserId); 6776 mUgmInternal.grantUriPermissionUncheckedFromIntent(needed, null); 6777 } 6778 } 6779 6780 /** 6781 * @param uri This uri must NOT contain an embedded userId. 6782 * @param userId The userId in which the uri is to be resolved. 6783 */ 6784 @Override revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6785 public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, 6786 final int modeFlags, int userId) { 6787 enforceNotIsolatedCaller("revokeUriPermission"); 6788 synchronized (this) { 6789 final ProcessRecord r = getRecordForAppLOSP(caller); 6790 if (r == null) { 6791 throw new SecurityException("Unable to find app for caller " 6792 + caller 6793 + " when revoking permission to uri " + uri); 6794 } 6795 if (uri == null) { 6796 Slog.w(TAG, "revokeUriPermission: null uri"); 6797 return; 6798 } 6799 6800 if (!Intent.isAccessUriMode(modeFlags)) { 6801 return; 6802 } 6803 6804 final String authority = uri.getAuthority(); 6805 final ProviderInfo pi = mCpHelper.getProviderInfoLocked(authority, userId, 6806 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 6807 if (pi == null) { 6808 Slog.w(TAG, "No content provider found for permission revoke: " 6809 + uri.toSafeString()); 6810 return; 6811 } 6812 6813 mUgmInternal.revokeUriPermission(targetPackage, r.uid, 6814 new GrantUri(userId, uri, modeFlags), modeFlags); 6815 } 6816 } 6817 6818 @Override showWaitingForDebugger(IApplicationThread who, boolean waiting)6819 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 6820 synchronized (mProcLock) { 6821 final ProcessRecord app = who != null ? getRecordForAppLOSP(who) : null; 6822 if (app == null) return; 6823 6824 Message msg = Message.obtain(); 6825 msg.what = WAIT_FOR_DEBUGGER_UI_MSG; 6826 msg.obj = app; 6827 msg.arg1 = waiting ? 1 : 0; 6828 mUiHandler.sendMessage(msg); 6829 } 6830 } 6831 6832 @Override getMemoryInfo(ActivityManager.MemoryInfo outInfo)6833 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 6834 mProcessList.getMemoryInfo(outInfo); 6835 } 6836 6837 // ========================================================= 6838 // TASK MANAGEMENT 6839 // ========================================================= 6840 6841 @Override getTasks(int maxNum)6842 public List<RunningTaskInfo> getTasks(int maxNum) { 6843 return mActivityTaskManager.getTasks(maxNum); 6844 } 6845 6846 @Override cancelTaskWindowTransition(int taskId)6847 public void cancelTaskWindowTransition(int taskId) { 6848 mActivityTaskManager.cancelTaskWindowTransition(taskId); 6849 } 6850 6851 @Override setTaskResizeable(int taskId, int resizeableMode)6852 public void setTaskResizeable(int taskId, int resizeableMode) { 6853 mActivityTaskManager.setTaskResizeable(taskId, resizeableMode); 6854 } 6855 6856 @Override resizeTask(int taskId, Rect bounds, int resizeMode)6857 public void resizeTask(int taskId, Rect bounds, int resizeMode) { 6858 mActivityTaskManager.resizeTask(taskId, bounds, resizeMode); 6859 } 6860 6861 @Override getTaskBounds(int taskId)6862 public Rect getTaskBounds(int taskId) { 6863 return mActivityTaskManager.getTaskBounds(taskId); 6864 } 6865 6866 @Override removeTask(int taskId)6867 public boolean removeTask(int taskId) { 6868 return mActivityTaskManager.removeTask(taskId); 6869 } 6870 6871 @Override moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6872 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, 6873 int flags, Bundle bOptions) { 6874 mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions); 6875 } 6876 6877 /** 6878 * Attempts to move a task backwards in z-order (the order of activities within the task is 6879 * unchanged). 6880 * 6881 * There are several possible results of this call: 6882 * - if the task is locked, then we will show the lock toast 6883 * - if there is a task behind the provided task, then that task is made visible and resumed as 6884 * this task is moved to the back 6885 * - otherwise, if there are no other tasks in the stack: 6886 * - if this task is in the pinned stack, then we remove the stack completely, which will 6887 * have the effect of moving the task to the top or bottom of the fullscreen stack 6888 * (depending on whether it is visible) 6889 * - otherwise, we simply return home and hide this task 6890 * 6891 * @param token A reference to the activity we wish to move 6892 * @param nonRoot If false then this only works if the activity is the root 6893 * of a task; if true it will work for any activity in a task. 6894 * @return Returns true if the move completed, false if not. 6895 */ 6896 @Override moveActivityTaskToBack(IBinder token, boolean nonRoot)6897 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 6898 return ActivityClient.getInstance().moveActivityTaskToBack(token, nonRoot); 6899 } 6900 6901 @Override moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)6902 public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) { 6903 mActivityTaskManager.moveTaskToRootTask(taskId, rootTaskId, toTop); 6904 } 6905 6906 @Override getRecentTasks(int maxNum, int flags, int userId)6907 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, 6908 int userId) { 6909 return mActivityTaskManager.getRecentTasks(maxNum, flags, userId); 6910 } 6911 6912 @Override getAllRootTaskInfos()6913 public List<RootTaskInfo> getAllRootTaskInfos() { 6914 return mActivityTaskManager.getAllRootTaskInfos(); 6915 } 6916 6917 @Override getTaskForActivity(IBinder token, boolean onlyRoot)6918 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 6919 return ActivityClient.getInstance().getTaskForActivity(token, onlyRoot); 6920 } 6921 6922 @Override updateLockTaskPackages(int userId, String[] packages)6923 public void updateLockTaskPackages(int userId, String[] packages) { 6924 mActivityTaskManager.updateLockTaskPackages(userId, packages); 6925 } 6926 6927 @Override isInLockTaskMode()6928 public boolean isInLockTaskMode() { 6929 return mActivityTaskManager.isInLockTaskMode(); 6930 } 6931 6932 @Override getLockTaskModeState()6933 public int getLockTaskModeState() { 6934 return mActivityTaskManager.getLockTaskModeState(); 6935 } 6936 6937 @Override startSystemLockTaskMode(int taskId)6938 public void startSystemLockTaskMode(int taskId) throws RemoteException { 6939 mActivityTaskManager.startSystemLockTaskMode(taskId); 6940 } 6941 6942 /** 6943 * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The 6944 * PackageManager could be unavailable at construction time and therefore needs to be accessed 6945 * on demand. 6946 */ 6947 @VisibleForTesting getPackageManager()6948 public IPackageManager getPackageManager() { 6949 return AppGlobals.getPackageManager(); 6950 } 6951 6952 @VisibleForTesting getPackageManagerInternal()6953 public PackageManagerInternal getPackageManagerInternal() { 6954 // Intentionally hold no locks: in case of race conditions, the mPackageManagerInt will 6955 // be set to the same value anyway. 6956 if (mPackageManagerInt == null) { 6957 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class); 6958 } 6959 return mPackageManagerInt; 6960 } 6961 getPermissionManagerInternal()6962 private PermissionManagerServiceInternal getPermissionManagerInternal() { 6963 // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will 6964 // be set to the same value anyway. 6965 if (mPermissionManagerInt == null) { 6966 mPermissionManagerInt = 6967 LocalServices.getService(PermissionManagerServiceInternal.class); 6968 } 6969 return mPermissionManagerInt; 6970 } 6971 getAccessCheckDelegateHelper()6972 private AccessCheckDelegateHelper getAccessCheckDelegateHelper() { 6973 // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will 6974 // be set to the same value anyway. 6975 if (mAccessCheckDelegateHelper == null) { 6976 mAccessCheckDelegateHelper = new AccessCheckDelegateHelper(mProcLock, 6977 mActiveInstrumentation, mAppOpsService, getPermissionManagerInternal()); 6978 } 6979 return mAccessCheckDelegateHelper; 6980 } 6981 6982 /** Returns whether the given package was ever launched since install */ wasPackageEverLaunched(String packageName, @UserIdInt int userId)6983 boolean wasPackageEverLaunched(String packageName, @UserIdInt int userId) { 6984 boolean wasLaunched = false; 6985 try { 6986 wasLaunched = getPackageManagerInternal().wasPackageEverLaunched(packageName, userId); 6987 } catch (Exception e) { 6988 // If the package state record doesn't exist yet, assume it was never launched 6989 } 6990 return wasLaunched; 6991 } 6992 getTestUtilityServiceLocked()6993 private TestUtilityService getTestUtilityServiceLocked() { 6994 if (mTestUtilityService == null) { 6995 mTestUtilityService = 6996 LocalServices.getService(TestUtilityService.class); 6997 } 6998 return mTestUtilityService; 6999 } 7000 7001 @Override appNotResponding(final String reason)7002 public void appNotResponding(final String reason) { 7003 appNotResponding(reason, /*isContinuousAnr*/ false); 7004 } 7005 appNotResponding(final String reason, boolean isContinuousAnr)7006 public void appNotResponding(final String reason, boolean isContinuousAnr) { 7007 TimeoutRecord timeoutRecord = TimeoutRecord.forApp("App requested: " + reason); 7008 final int callingPid = Binder.getCallingPid(); 7009 7010 timeoutRecord.mLatencyTracker.waitingOnPidLockStarted(); 7011 synchronized (mPidsSelfLocked) { 7012 timeoutRecord.mLatencyTracker.waitingOnPidLockEnded(); 7013 final ProcessRecord app = mPidsSelfLocked.get(callingPid); 7014 if (app == null) { 7015 throw new SecurityException("Unknown process: " + callingPid); 7016 } 7017 7018 mAnrHelper.appNotResponding(app, null, app.info, null, null, false, 7019 timeoutRecord, isContinuousAnr); 7020 } 7021 } 7022 appNotResponding(@onNull ProcessRecord anrProcess, @NonNull TimeoutRecord timeoutRecord)7023 void appNotResponding(@NonNull ProcessRecord anrProcess, @NonNull TimeoutRecord timeoutRecord) { 7024 mAnrHelper.appNotResponding(anrProcess, timeoutRecord); 7025 } 7026 appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)7027 private void appNotResponding(@NonNull String processName, int uid, 7028 @NonNull TimeoutRecord timeoutRecord) { 7029 Objects.requireNonNull(processName); 7030 Objects.requireNonNull(timeoutRecord); 7031 7032 synchronized (this) { 7033 final ProcessRecord app = getProcessRecordLocked(processName, uid); 7034 if (app == null) { 7035 Slog.e(TAG, "Unknown process: " + processName); 7036 return; 7037 } 7038 mAnrHelper.appNotResponding(app, timeoutRecord); 7039 } 7040 } 7041 startPersistentApps(int matchFlags)7042 void startPersistentApps(int matchFlags) { 7043 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return; 7044 7045 synchronized (this) { 7046 try { 7047 final List<ApplicationInfo> apps = AppGlobals.getPackageManager() 7048 .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList(); 7049 for (ApplicationInfo app : apps) { 7050 if (!"android".equals(app.packageName)) { 7051 final ProcessRecord proc = addAppLocked( 7052 app, null, false, null /* ABI override */, 7053 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 7054 if (proc != null) { 7055 proc.mProfile.addHostingComponentType( 7056 HOSTING_COMPONENT_TYPE_PERSISTENT); 7057 } 7058 } 7059 } 7060 } catch (RemoteException ex) { 7061 } 7062 } 7063 } 7064 7065 // ========================================================= 7066 // CONTENT PROVIDERS 7067 // ========================================================= 7068 getContentProviderHelper()7069 public ContentProviderHelper getContentProviderHelper() { 7070 return mCpHelper; 7071 } 7072 7073 @Override getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)7074 public final ContentProviderHolder getContentProvider( 7075 IApplicationThread caller, String callingPackage, String name, int userId, 7076 boolean stable) { 7077 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProvider: ", name); 7078 try { 7079 return mCpHelper.getContentProvider(caller, callingPackage, name, userId, stable); 7080 } finally { 7081 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7082 } 7083 } 7084 7085 @Override getContentProviderExternal( String name, int userId, IBinder token, String tag)7086 public ContentProviderHolder getContentProviderExternal( 7087 String name, int userId, IBinder token, String tag) { 7088 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProviderExternal: ", name); 7089 try { 7090 return mCpHelper.getContentProviderExternal(name, userId, token, tag); 7091 } finally { 7092 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7093 } 7094 } 7095 7096 /** 7097 * Drop a content provider from a ProcessRecord's bookkeeping 7098 */ 7099 @Override removeContentProvider(IBinder connection, boolean stable)7100 public void removeContentProvider(IBinder connection, boolean stable) { 7101 mCpHelper.removeContentProvider(connection, stable); 7102 } 7103 7104 /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */ 7105 @Deprecated 7106 @Override removeContentProviderExternal(String name, IBinder token)7107 public void removeContentProviderExternal(String name, IBinder token) { 7108 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternal: ", name); 7109 try { 7110 removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId()); 7111 } finally { 7112 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7113 } 7114 } 7115 7116 @Override removeContentProviderExternalAsUser(String name, IBinder token, int userId)7117 public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) { 7118 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternalAsUser: ", name); 7119 try { 7120 mCpHelper.removeContentProviderExternalAsUser(name, token, userId); 7121 } finally { 7122 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7123 } 7124 } 7125 7126 @Override publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)7127 public final void publishContentProviders(IApplicationThread caller, 7128 List<ContentProviderHolder> providers) { 7129 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 7130 final int maxLength = 256; 7131 final StringBuilder sb = new StringBuilder(maxLength); 7132 sb.append("publishContentProviders: "); 7133 if (providers != null) { 7134 boolean first = true; 7135 for (int i = 0, size = providers.size(); i < size; i++) { 7136 final ContentProviderHolder holder = providers.get(i); 7137 if (holder != null && holder.info != null && holder.info.authority != null) { 7138 final int len = holder.info.authority.length(); 7139 if (sb.length() + len > maxLength) { 7140 sb.append("[[TRUNCATED]]"); 7141 break; 7142 } 7143 if (!first) { 7144 sb.append(';'); 7145 } else { 7146 first = false; 7147 } 7148 sb.append(holder.info.authority); 7149 } 7150 } 7151 } 7152 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString()); 7153 } 7154 try { 7155 mCpHelper.publishContentProviders(caller, providers); 7156 } finally { 7157 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 7158 } 7159 } 7160 7161 @Override refContentProvider(IBinder connection, int stable, int unstable)7162 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 7163 return mCpHelper.refContentProvider(connection, stable, unstable); 7164 } 7165 7166 @Override unstableProviderDied(IBinder connection)7167 public void unstableProviderDied(IBinder connection) { 7168 mCpHelper.unstableProviderDied(connection); 7169 } 7170 7171 @Override appNotRespondingViaProvider(IBinder connection)7172 public void appNotRespondingViaProvider(IBinder connection) { 7173 mCpHelper.appNotRespondingViaProvider(connection); 7174 } 7175 7176 /** 7177 * Filters calls to getType based on permission. If the caller has required permission, 7178 * then it returns the contentProvider#getType. 7179 * Else, it returns the contentProvider#getTypeAnonymous, which does not 7180 * reveal any internal information which should be protected by any permission. 7181 */ 7182 @Override getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback)7183 public void getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback) { 7184 mCpHelper.getMimeTypeFilterAsync(uri, userId, resultCallback); 7185 } 7186 7187 // ========================================================= 7188 // GLOBAL MANAGEMENT 7189 // ========================================================= 7190 7191 @GuardedBy(anyOf = {"this", "mProcLock"}) uidOnBackgroundAllowlistLOSP(final int uid)7192 private boolean uidOnBackgroundAllowlistLOSP(final int uid) { 7193 final int appId = UserHandle.getAppId(uid); 7194 final int[] allowlist = mBackgroundAppIdAllowlist; 7195 for (int i = 0, len = allowlist.length; i < len; i++) { 7196 if (appId == allowlist[i]) { 7197 return true; 7198 } 7199 } 7200 return false; 7201 } 7202 7203 @Override isBackgroundRestricted(String packageName)7204 public boolean isBackgroundRestricted(String packageName) { 7205 final int callingUid = Binder.getCallingUid(); 7206 final IPackageManager pm = AppGlobals.getPackageManager(); 7207 try { 7208 final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 7209 UserHandle.getUserId(callingUid)); 7210 if (packageUid != callingUid) { 7211 throw new IllegalArgumentException("Uid " + callingUid 7212 + " cannot query restriction state for package " + packageName); 7213 } 7214 } catch (RemoteException exc) { 7215 // Ignore. 7216 } 7217 return isBackgroundRestrictedNoCheck(callingUid, packageName); 7218 } 7219 7220 @VisibleForTesting isBackgroundRestrictedNoCheck(final int uid, final String packageName)7221 public boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) { 7222 final int mode = getAppOpsManager().checkOpNoThrow(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, 7223 uid, packageName); 7224 return mode != AppOpsManager.MODE_ALLOWED; 7225 } 7226 7227 @Override backgroundAllowlistUid(final int uid)7228 public void backgroundAllowlistUid(final int uid) { 7229 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 7230 throw new SecurityException("Only the OS may call backgroundAllowlistUid()"); 7231 } 7232 7233 if (DEBUG_BACKGROUND_CHECK) { 7234 Slog.i(TAG, "Adding uid " + uid + " to bg uid allowlist"); 7235 } 7236 synchronized (this) { 7237 synchronized (mProcLock) { 7238 final int num = mBackgroundAppIdAllowlist.length; 7239 int[] newList = new int[num + 1]; 7240 System.arraycopy(mBackgroundAppIdAllowlist, 0, newList, 0, num); 7241 newList[num] = UserHandle.getAppId(uid); 7242 mBackgroundAppIdAllowlist = newList; 7243 } 7244 } 7245 } 7246 7247 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)7248 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 7249 String abiOverride, int zygotePolicyFlags) { 7250 return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */, 7251 abiOverride, zygotePolicyFlags); 7252 } 7253 7254 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags)7255 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 7256 boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags) { 7257 return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks, 7258 false /* disableTestApiChecks */, abiOverride, zygotePolicyFlags); 7259 } 7260 7261 // TODO: Move to ProcessList? 7262 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)7263 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 7264 boolean disableHiddenApiChecks, boolean disableTestApiChecks, 7265 String abiOverride, int zygotePolicyFlags) { 7266 return addAppLocked( 7267 info, 7268 customProcess, 7269 isolated, 7270 /* isSdkSandbox= */ false, 7271 /* sdkSandboxUid= */ 0, 7272 /* sdkSandboxClientAppPackage= */ null, 7273 disableHiddenApiChecks, 7274 disableTestApiChecks, 7275 abiOverride, 7276 zygotePolicyFlags); 7277 } 7278 addAppLocked( ApplicationInfo info, String customProcess, boolean isolated, boolean isSdkSandbox, int sdkSandboxUid, @Nullable String sdkSandboxClientAppPackage, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)7279 final ProcessRecord addAppLocked( 7280 ApplicationInfo info, 7281 String customProcess, 7282 boolean isolated, 7283 boolean isSdkSandbox, 7284 int sdkSandboxUid, 7285 @Nullable String sdkSandboxClientAppPackage, 7286 boolean disableHiddenApiChecks, 7287 boolean disableTestApiChecks, 7288 String abiOverride, 7289 int zygotePolicyFlags) { 7290 ProcessRecord app; 7291 if (!isolated) { 7292 app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName, 7293 info.uid); 7294 } else { 7295 app = null; 7296 } 7297 7298 if (app == null) { 7299 app = mProcessList.newProcessRecordLocked( 7300 info, 7301 customProcess, 7302 isolated, 7303 /* isolatedUid= */0, 7304 isSdkSandbox, 7305 sdkSandboxUid, 7306 sdkSandboxClientAppPackage, 7307 new HostingRecord(HostingRecord.HOSTING_TYPE_ADDED_APPLICATION, 7308 customProcess != null ? customProcess : info.processName)); 7309 updateLruProcessLocked(app, false, null); 7310 updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN); 7311 } 7312 7313 // Report usage as process is persistent and being started. 7314 mUsageStatsService.reportEvent(info.packageName, UserHandle.getUserId(app.uid), 7315 Event.APP_COMPONENT_USED); 7316 7317 // This package really, really can not be stopped. 7318 // TODO: how set package stopped state should work for sdk sandboxes? 7319 if (!isSdkSandbox) { 7320 try { 7321 mPackageManagerInt.setPackageStoppedState( 7322 info.packageName, false, UserHandle.getUserId(app.uid)); 7323 } catch (IllegalArgumentException e) { 7324 Slog.w(TAG, "Failed trying to unstop package " 7325 + info.packageName + ": " + e); 7326 } 7327 } 7328 7329 if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 7330 app.setPersistent(true); 7331 mProcessStateController.setMaxAdj(app, ProcessList.PERSISTENT_PROC_ADJ); 7332 } 7333 if (app.getThread() == null && mPersistentStartingProcesses.indexOf(app) < 0) { 7334 mPersistentStartingProcesses.add(app); 7335 mProcessList.startProcessLocked(app, new HostingRecord( 7336 HostingRecord.HOSTING_TYPE_ADDED_APPLICATION, 7337 customProcess != null ? customProcess : app.processName), 7338 zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks, 7339 abiOverride); 7340 } 7341 7342 return app; 7343 } 7344 unhandledBack()7345 public void unhandledBack() { 7346 mActivityTaskManager.unhandledBack(); 7347 } 7348 7349 // TODO: Replace this method with one that returns a bound IContentProvider. openContentUri(String uriString)7350 public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException { 7351 enforceNotIsolatedCaller("openContentUri"); 7352 final int userId = UserHandle.getCallingUserId(); 7353 final Uri uri = Uri.parse(uriString); 7354 String name = uri.getAuthority(); 7355 ContentProviderHolder cph = mCpHelper.getContentProviderExternalUnchecked(name, null, 7356 Binder.getCallingUid(), "*opencontent*", userId); 7357 ParcelFileDescriptor pfd = null; 7358 if (cph != null) { 7359 try { 7360 // This method is exposed to the VNDK and to avoid changing its 7361 // signature we just use the first package in the UID. For shared 7362 // UIDs we may blame the wrong app but that is Okay as they are 7363 // in the same security/privacy sandbox. 7364 final int uid = Binder.getCallingUid(); 7365 // Here we handle some of the special UIDs (mediaserver, systemserver, etc) 7366 final String packageName = AppOpsManager.resolvePackageName(uid, 7367 /*packageName*/ null); 7368 final AndroidPackage androidPackage; 7369 if (packageName != null) { 7370 androidPackage = mPackageManagerInt.getPackage(packageName); 7371 } else { 7372 androidPackage = mPackageManagerInt.getPackage(uid); 7373 } 7374 if (androidPackage == null) { 7375 Log.e(TAG, "Cannot find package for uid: " + uid); 7376 return null; 7377 } 7378 7379 final ApplicationInfo appInfo = mPackageManagerInt.getApplicationInfo( 7380 androidPackage.getPackageName(), /*flags*/0, Process.SYSTEM_UID, 7381 UserHandle.USER_SYSTEM); 7382 if (!appInfo.isVendor() && !appInfo.isSystemApp() && !appInfo.isSystemExt() 7383 && !appInfo.isProduct()) { 7384 Log.e(TAG, "openContentUri may only be used by vendor/system/product."); 7385 return null; 7386 } 7387 7388 final AttributionSource attributionSource = new AttributionSource( 7389 Binder.getCallingUid(), androidPackage.getPackageName(), null); 7390 pfd = cph.provider.openFile(attributionSource, uri, "r", null); 7391 } catch (FileNotFoundException e) { 7392 // do nothing; pfd will be returned null 7393 } finally { 7394 // Ensure we're done with the provider. 7395 mCpHelper.removeContentProviderExternalUnchecked(name, null, userId); 7396 } 7397 } else { 7398 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 7399 } 7400 return pfd; 7401 } 7402 reportGlobalUsageEvent(int event)7403 void reportGlobalUsageEvent(int event) { 7404 final int currentUserId = mUserController.getCurrentUserId(); 7405 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, currentUserId, event); 7406 int[] profiles = mUserController.getCurrentProfileIds(); 7407 if (profiles != null) { 7408 for (int i = profiles.length - 1; i >= 0; i--) { 7409 if (profiles[i] == currentUserId) { 7410 continue; 7411 } 7412 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, profiles[i], event); 7413 } 7414 } 7415 } 7416 reportCurWakefulnessUsageEvent()7417 void reportCurWakefulnessUsageEvent() { 7418 reportGlobalUsageEvent(mWakefulness.get() == PowerManagerInternal.WAKEFULNESS_AWAKE 7419 ? UsageEvents.Event.SCREEN_INTERACTIVE 7420 : UsageEvents.Event.SCREEN_NON_INTERACTIVE); 7421 } 7422 onWakefulnessChanged(int wakefulness)7423 void onWakefulnessChanged(int wakefulness) { 7424 synchronized (this) { 7425 boolean wasAwake = mWakefulness.getAndSet(wakefulness) 7426 == PowerManagerInternal.WAKEFULNESS_AWAKE; 7427 boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE; 7428 7429 if (wasAwake != isAwake) { 7430 // Also update state in a special way for running foreground services UI. 7431 mServices.updateScreenStateLocked(isAwake); 7432 reportCurWakefulnessUsageEvent(); 7433 mActivityTaskManager.onScreenAwakeChanged(isAwake); 7434 mProcessStateController.setWakefulness(wakefulness); 7435 7436 updateOomAdjLocked(OOM_ADJ_REASON_UI_VISIBILITY); 7437 } 7438 } 7439 } 7440 7441 @Override notifyCleartextNetwork(int uid, byte[] firstPacket)7442 public void notifyCleartextNetwork(int uid, byte[] firstPacket) { 7443 mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget(); 7444 } 7445 7446 @Override shutdown(int timeout)7447 public boolean shutdown(int timeout) { 7448 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 7449 != PackageManager.PERMISSION_GRANTED) { 7450 throw new SecurityException("Requires permission " 7451 + android.Manifest.permission.SHUTDOWN); 7452 } 7453 7454 final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout); 7455 7456 mAppOpsService.shutdown(); 7457 if (mUsageStatsService != null) { 7458 mUsageStatsService.prepareShutdown(); 7459 } 7460 mBatteryStatsService.shutdown(); 7461 mProcessStats.shutdown(); 7462 7463 return timedout; 7464 } 7465 7466 @Override notifyLockedProfile(@serIdInt int userId)7467 public void notifyLockedProfile(@UserIdInt int userId) { 7468 mAtmInternal.notifyLockedProfile(userId); 7469 } 7470 7471 @Override startConfirmDeviceCredentialIntent(Intent intent, Bundle options)7472 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) { 7473 mAtmInternal.startConfirmDeviceCredentialIntent(intent, options); 7474 } 7475 7476 @Override stopAppSwitches()7477 public void stopAppSwitches() { 7478 mActivityTaskManager.stopAppSwitches(); 7479 } 7480 7481 @Override resumeAppSwitches()7482 public void resumeAppSwitches() { 7483 mActivityTaskManager.resumeAppSwitches(); 7484 } 7485 setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)7486 public void setDebugApp(String packageName, boolean waitForDebugger, 7487 boolean persistent) { 7488 setDebugApp(packageName, waitForDebugger, persistent, false); 7489 } 7490 setDebugApp(String packageName, boolean waitForDebugger, boolean persistent, boolean suspendUponWait)7491 private void setDebugApp(String packageName, boolean waitForDebugger, 7492 boolean persistent, boolean suspendUponWait) { 7493 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 7494 "setDebugApp()"); 7495 7496 final long ident = Binder.clearCallingIdentity(); 7497 try { 7498 // Note that this is not really thread safe if there are multiple 7499 // callers into it at the same time, but that's not a situation we 7500 // care about. 7501 if (persistent) { 7502 final ContentResolver resolver = mContext.getContentResolver(); 7503 Settings.Global.putString( 7504 resolver, Settings.Global.DEBUG_APP, 7505 packageName); 7506 Settings.Global.putInt( 7507 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 7508 waitForDebugger ? 1 : 0); 7509 } 7510 7511 synchronized (this) { 7512 if (!persistent) { 7513 mOrigDebugApp = mDebugApp; 7514 mOrigWaitForDebugger = mWaitForDebugger; 7515 } 7516 mDebugApp = packageName; 7517 mWaitForDebugger = waitForDebugger; 7518 mSuspendUponWait = suspendUponWait; 7519 mDebugTransient = !persistent; 7520 if (packageName != null) { 7521 forceStopPackageLocked(packageName, -1, false, false, true, true, 7522 false, false, UserHandle.USER_ALL, "set debug app"); 7523 } 7524 } 7525 } finally { 7526 Binder.restoreCallingIdentity(ident); 7527 } 7528 } 7529 7530 /** 7531 * Set or remove an agent to be run whenever an app with the given process name starts. 7532 * 7533 * This method will not check whether the given process name matches a debuggable app. That 7534 * would require scanning all current packages, and a rescan when new packages are installed 7535 * or updated. 7536 * 7537 * Instead, do the check when an application is started and matched to a stored agent. 7538 * 7539 * @param packageName the process name of the app. 7540 * @param agent the agent string to be used, or null to remove any previously set agent. 7541 */ 7542 @Override setAgentApp(@onNull String packageName, @Nullable String agent)7543 public void setAgentApp(@NonNull String packageName, @Nullable String agent) { 7544 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 7545 // its own permission. 7546 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7547 != PackageManager.PERMISSION_GRANTED) { 7548 throw new SecurityException( 7549 "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7550 } 7551 7552 synchronized (mAppProfiler.mProfilerLock) { 7553 mAppProfiler.setAgentAppLPf(packageName, agent); 7554 } 7555 } 7556 setTrackAllocationApp(ApplicationInfo app, String processName)7557 void setTrackAllocationApp(ApplicationInfo app, String processName) { 7558 enforceDebuggable(app); 7559 7560 synchronized (mProcLock) { 7561 mTrackAllocationApp = processName; 7562 } 7563 } 7564 setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo, ApplicationInfo sdkSandboxClientApp, int profileType)7565 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo, 7566 ApplicationInfo sdkSandboxClientApp, int profileType) { 7567 synchronized (mAppProfiler.mProfilerLock) { 7568 if (!Build.IS_DEBUGGABLE) { 7569 boolean isAppDebuggable = (app.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 7570 boolean isAppProfileable = app.isProfileableByShell(); 7571 7572 if (sdkSandboxClientApp != null) { 7573 isAppDebuggable |= 7574 (sdkSandboxClientApp.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 7575 isAppProfileable |= sdkSandboxClientApp.isProfileableByShell(); 7576 } 7577 if (!isAppDebuggable && !isAppProfileable) { 7578 throw new SecurityException("Process not debuggable, " 7579 + "and not profileable by shell: " + app.packageName); 7580 } 7581 } 7582 mAppProfiler.setProfileAppLPf(processName, profilerInfo, profileType); 7583 } 7584 } 7585 setNativeDebuggingAppLocked(ApplicationInfo app, String processName)7586 void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) { 7587 enforceDebuggable(app); 7588 mNativeDebuggingApp = processName; 7589 } 7590 7591 @Override setAlwaysFinish(boolean enabled)7592 public void setAlwaysFinish(boolean enabled) { 7593 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 7594 "setAlwaysFinish()"); 7595 7596 final long ident = Binder.clearCallingIdentity(); 7597 try { 7598 Settings.Global.putInt( 7599 mContext.getContentResolver(), 7600 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 7601 7602 synchronized (this) { 7603 mAlwaysFinishActivities = enabled; 7604 } 7605 } finally { 7606 Binder.restoreCallingIdentity(ident); 7607 } 7608 } 7609 7610 @Override setActivityController(IActivityController controller, boolean imAMonkey)7611 public void setActivityController(IActivityController controller, boolean imAMonkey) { 7612 if (controller != null) { 7613 Binder.allowBlocking(controller.asBinder()); 7614 } 7615 mActivityTaskManager.setActivityController(controller, imAMonkey); 7616 } 7617 7618 @Override setUserIsMonkey(boolean userIsMonkey)7619 public void setUserIsMonkey(boolean userIsMonkey) { 7620 synchronized (mProcLock) { 7621 synchronized (mPidsSelfLocked) { 7622 final int callingPid = Binder.getCallingPid(); 7623 ProcessRecord proc = mPidsSelfLocked.get(callingPid); 7624 if (proc == null) { 7625 throw new SecurityException("Unknown process: " + callingPid); 7626 } 7627 if (proc.getActiveInstrumentation() == null 7628 || proc.getActiveInstrumentation().mUiAutomationConnection == null) { 7629 throw new SecurityException("Only an instrumentation process " 7630 + "with a UiAutomation can call setUserIsMonkey"); 7631 } 7632 } 7633 mUserIsMonkey = userIsMonkey; 7634 } 7635 } 7636 7637 @Override isUserAMonkey()7638 public boolean isUserAMonkey() { 7639 synchronized (mProcLock) { 7640 // If there is a controller also implies the user is a monkey. 7641 return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey(); 7642 } 7643 } 7644 7645 @Override requestSystemServerHeapDump()7646 public void requestSystemServerHeapDump() { 7647 if (!Build.IS_DEBUGGABLE) { 7648 Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build"); 7649 return; 7650 } 7651 if (Binder.getCallingUid() != SYSTEM_UID) { 7652 // This also intentionally excludes secondary profiles from calling this. 7653 throw new SecurityException( 7654 "Only the system process is allowed to request a system heap dump"); 7655 } 7656 ProcessRecord pr; 7657 synchronized (mPidsSelfLocked) { 7658 pr = mPidsSelfLocked.get(myPid()); 7659 } 7660 if (pr == null) { 7661 Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid()); 7662 return; 7663 } 7664 synchronized (mAppProfiler.mProfilerLock) { 7665 mAppProfiler.startHeapDumpLPf(pr.mProfile, true); 7666 } 7667 } 7668 7669 /** 7670 * Takes a bugreport using bug report API ({@code BugreportManager}) with no pre-set 7671 * title and description 7672 */ 7673 @Override requestBugReport(@ugreportParams.BugreportMode int bugreportType)7674 public void requestBugReport(@BugreportParams.BugreportMode int bugreportType) { 7675 requestBugReportWithDescription(null, null, bugreportType, 0L); 7676 } 7677 7678 /** 7679 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 7680 * triggered by sending a broadcast to Shell. 7681 */ 7682 @Override requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType)7683 public void requestBugReportWithDescription(@Nullable String shareTitle, 7684 @Nullable String shareDescription, int bugreportType) { 7685 requestBugReportWithDescription(shareTitle, shareDescription, bugreportType, /*nonce*/ 0L); 7686 } 7687 7688 /** 7689 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 7690 * triggered by sending a broadcast to Shell. 7691 */ requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType, long nonce)7692 public void requestBugReportWithDescription(@Nullable String shareTitle, 7693 @Nullable String shareDescription, int bugreportType, long nonce) { 7694 requestBugReportWithDescription(shareTitle, shareDescription, bugreportType, nonce, null); 7695 } 7696 7697 /** 7698 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 7699 * triggered by sending a broadcast to Shell. Optionally adds an extra attachment. 7700 */ requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType, long nonce, @Nullable List<Uri> extraAttachments)7701 public void requestBugReportWithDescription(@Nullable String shareTitle, 7702 @Nullable String shareDescription, int bugreportType, long nonce, 7703 @Nullable List<Uri> extraAttachments) { 7704 String type = null; 7705 switch (bugreportType) { 7706 case BugreportParams.BUGREPORT_MODE_FULL: 7707 type = "bugreportfull"; 7708 break; 7709 case BugreportParams.BUGREPORT_MODE_INTERACTIVE: 7710 type = "bugreportplus"; 7711 break; 7712 case BugreportParams.BUGREPORT_MODE_REMOTE: 7713 type = "bugreportremote"; 7714 break; 7715 case BugreportParams.BUGREPORT_MODE_WEAR: 7716 type = "bugreportwear"; 7717 break; 7718 case BugreportParams.BUGREPORT_MODE_TELEPHONY: 7719 type = "bugreporttelephony"; 7720 break; 7721 case BugreportParams.BUGREPORT_MODE_WIFI: 7722 type = "bugreportwifi"; 7723 break; 7724 case BugreportParams.BUGREPORT_MODE_ONBOARDING: 7725 type = "bugreportonboarding"; 7726 break; 7727 default: 7728 throw new IllegalArgumentException( 7729 "Provided bugreport type is not correct, value: " 7730 + bugreportType); 7731 } 7732 // Always log caller, even if it does not have permission to dump. 7733 Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid()); 7734 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 7735 7736 if (!TextUtils.isEmpty(shareTitle)) { 7737 if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) { 7738 String errorStr = "shareTitle should be less than " 7739 + MAX_BUGREPORT_TITLE_SIZE + " characters"; 7740 throw new IllegalArgumentException(errorStr); 7741 } 7742 if (!TextUtils.isEmpty(shareDescription)) { 7743 if (shareDescription.length() > MAX_BUGREPORT_DESCRIPTION_SIZE) { 7744 String errorStr = "shareDescription should be less than " 7745 + MAX_BUGREPORT_DESCRIPTION_SIZE + " characters"; 7746 throw new IllegalArgumentException(errorStr); 7747 } 7748 } 7749 Slog.d(TAG, "Bugreport notification title " + shareTitle 7750 + " description " + shareDescription); 7751 } 7752 // Create intent to trigger Bugreport API via Shell 7753 Intent triggerShellBugreport = new Intent(); 7754 triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED); 7755 triggerShellBugreport.setPackage(SHELL_APP_PACKAGE); 7756 triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType); 7757 triggerShellBugreport.putExtra(EXTRA_BUGREPORT_NONCE, nonce); 7758 if (extraAttachments != null && !extraAttachments.isEmpty()) { 7759 triggerShellBugreport.putParcelableArrayListExtra(EXTRA_EXTRA_ATTACHMENT_URIS, 7760 new ArrayList(extraAttachments)); 7761 triggerShellBugreport.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7762 } 7763 triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 7764 triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 7765 if (shareTitle != null) { 7766 triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle); 7767 } 7768 if (shareDescription != null) { 7769 triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription); 7770 } 7771 final long identity = Binder.clearCallingIdentity(); 7772 try { 7773 // Send broadcast to shell to trigger bugreport using Bugreport API 7774 // Always start the shell process on the current user to ensure that 7775 // the foreground user can see all bugreport notifications. 7776 // In case of BUGREPORT_MODE_REMOTE send the broadcast to SYSTEM user as the device 7777 // owner apps are running on the SYSTEM user. 7778 if (bugreportType == BugreportParams.BUGREPORT_MODE_REMOTE) { 7779 mContext.sendBroadcastAsUser(triggerShellBugreport, UserHandle.SYSTEM); 7780 } else { 7781 mContext.sendBroadcastAsUser(triggerShellBugreport, 7782 getCurrentUser().getUserHandle()); 7783 } 7784 } finally { 7785 Binder.restoreCallingIdentity(identity); 7786 } 7787 } 7788 7789 /** 7790 * Takes a telephony bugreport with title and description 7791 */ 7792 @Override requestTelephonyBugReport(String shareTitle, String shareDescription)7793 public void requestTelephonyBugReport(String shareTitle, String shareDescription) { 7794 requestBugReportWithDescription(shareTitle, shareDescription, 7795 BugreportParams.BUGREPORT_MODE_TELEPHONY); 7796 } 7797 7798 /** 7799 * Takes a minimal bugreport of Wifi-related state with pre-set title and description 7800 */ 7801 @Override requestWifiBugReport(String shareTitle, String shareDescription)7802 public void requestWifiBugReport(String shareTitle, String shareDescription) { 7803 requestBugReportWithDescription(shareTitle, shareDescription, 7804 BugreportParams.BUGREPORT_MODE_WIFI); 7805 } 7806 7807 /** 7808 * Takes an interactive bugreport with a progress notification 7809 */ 7810 @Override requestInteractiveBugReport()7811 public void requestInteractiveBugReport() { 7812 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE); 7813 } 7814 7815 /** 7816 * Takes an interactive bugreport with a progress notification. Also attaches given file uri. 7817 */ 7818 @Override requestBugReportWithExtraAttachments(@onNull List<Uri> extraAttachments)7819 public void requestBugReportWithExtraAttachments(@NonNull List<Uri> extraAttachments) { 7820 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE, 0L, 7821 extraAttachments); 7822 } 7823 7824 /** 7825 * Takes an interactive bugreport with a progress notification. Also, shows the given title and 7826 * description on the final share notification 7827 */ 7828 @Override requestInteractiveBugReportWithDescription(String shareTitle, String shareDescription)7829 public void requestInteractiveBugReportWithDescription(String shareTitle, 7830 String shareDescription) { 7831 requestBugReportWithDescription(shareTitle, shareDescription, 7832 BugreportParams.BUGREPORT_MODE_INTERACTIVE); 7833 } 7834 7835 /** 7836 * Takes a bugreport with minimal user interference 7837 */ 7838 @Override requestFullBugReport()7839 public void requestFullBugReport() { 7840 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_FULL); 7841 } 7842 7843 /** 7844 * Takes a bugreport remotely 7845 */ 7846 @Override requestRemoteBugReport(long nonce)7847 public void requestRemoteBugReport(long nonce) { 7848 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE, nonce); 7849 } 7850 7851 /** 7852 * Launches a bugreport-whitelisted app to handle a bugreport. 7853 * 7854 * <p>Allows a bug report handler app to take bugreports on the user's behalf. The handler can 7855 * be predefined in the config, meant to be launched with the primary user. The user can 7856 * override this with a different (or same) handler app on possibly a different user. This is 7857 * useful for capturing bug reports from work profile, for instance. 7858 * 7859 * @return true if there is a bugreport-whitelisted app to handle a bugreport, or false 7860 * otherwise. 7861 */ 7862 @Override launchBugReportHandlerApp()7863 public boolean launchBugReportHandlerApp() { 7864 7865 Context currentUserContext = mContext.createContextAsUser(getCurrentUser().getUserHandle(), 7866 /* flags= */ 0); 7867 if (!BugReportHandlerUtil.isBugReportHandlerEnabled(currentUserContext)) { 7868 return false; 7869 } 7870 7871 // Always log caller, even if it does not have permission to dump. 7872 Slog.i(TAG, "launchBugReportHandlerApp requested by UID " + Binder.getCallingUid()); 7873 enforceCallingPermission(android.Manifest.permission.DUMP, 7874 "launchBugReportHandlerApp"); 7875 7876 return BugReportHandlerUtil.launchBugReportHandlerApp(currentUserContext); 7877 } 7878 7879 /** 7880 * Get packages of bugreport-whitelisted apps to handle a bug report. 7881 * 7882 * @return packages of bugreport-whitelisted apps to handle a bug report. 7883 */ 7884 @Override getBugreportWhitelistedPackages()7885 public List<String> getBugreportWhitelistedPackages() { 7886 enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING, 7887 "getBugreportWhitelistedPackages"); 7888 return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages()); 7889 } 7890 registerProcessObserver(IProcessObserver observer)7891 public void registerProcessObserver(IProcessObserver observer) { 7892 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 7893 "registerProcessObserver()"); 7894 mProcessList.registerProcessObserver(observer); 7895 } 7896 7897 @Override unregisterProcessObserver(IProcessObserver observer)7898 public void unregisterProcessObserver(IProcessObserver observer) { 7899 mProcessList.unregisterProcessObserver(observer); 7900 } 7901 7902 @Override getUidProcessState(int uid, String callingPackage)7903 public int getUidProcessState(int uid, String callingPackage) { 7904 if (!hasUsageStatsPermission(callingPackage)) { 7905 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 7906 "getUidProcessState"); 7907 } 7908 // In case the caller is requesting processState of an app in a different user, 7909 // then verify the caller has INTERACT_ACROSS_USERS_FULL permission 7910 mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 7911 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY, 7912 "getUidProcessState", callingPackage); // Ignore return value 7913 7914 synchronized (mProcLock) { 7915 return getUidProcessStateInnerLOSP(uid); 7916 } 7917 } 7918 7919 @Override getBindingUidProcessState(int targetUid, String callingPackage)7920 public int getBindingUidProcessState(int targetUid, String callingPackage) { 7921 if (!hasUsageStatsPermission(callingPackage)) { 7922 enforceCallingPermission(android.Manifest.permission.GET_BINDING_UID_IMPORTANCE, 7923 "getBindingUidProcessState"); 7924 } 7925 // We don't need to do a cross-user check here (unlike getUidProcessState), 7926 // because we only allow to see UIDs that are actively communicating with the caller. 7927 7928 final int callingUid = Binder.getCallingUid(); 7929 final long token = Binder.clearCallingIdentity(); 7930 try { 7931 synchronized (this) { 7932 final boolean allowed = (callingUid == targetUid) 7933 || hasServiceBindingOrProviderUseLocked(callingUid, targetUid); 7934 if (!allowed) { 7935 return PROCESS_STATE_NONEXISTENT; 7936 } 7937 return getUidProcessStateInnerLOSP(targetUid); 7938 } 7939 } finally { 7940 Binder.restoreCallingIdentity(token); 7941 } 7942 } 7943 7944 @GuardedBy(anyOf = {"this", "mProcLock"}) getUidProcessStateInnerLOSP(int uid)7945 private int getUidProcessStateInnerLOSP(int uid) { 7946 if (mPendingStartActivityUids.isPendingTopUid(uid)) { 7947 return PROCESS_STATE_TOP; 7948 } 7949 return mProcessList.getUidProcStateLOSP(uid); 7950 } 7951 7952 /** 7953 * Ensure that {@code clientUid} has a bound service client to {@code callingUid} 7954 */ 7955 @GuardedBy("this") hasServiceBindingOrProviderUseLocked(int callingUid, int clientUid)7956 private boolean hasServiceBindingOrProviderUseLocked(int callingUid, int clientUid) { 7957 // See if there's a service binding 7958 final Boolean hasBinding = mProcessList.searchEachLruProcessesLOSP( 7959 false, pr -> { 7960 if (pr.uid == callingUid) { 7961 final ProcessServiceRecord psr = pr.mServices; 7962 final int serviceCount = psr.mServices.size(); 7963 for (int svc = 0; svc < serviceCount; svc++) { 7964 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns = 7965 psr.mServices.valueAt(svc).getConnections(); 7966 final int size = conns.size(); 7967 for (int conni = 0; conni < size; conni++) { 7968 final ArrayList<ConnectionRecord> crs = conns.valueAt(conni); 7969 for (int con = 0; con < crs.size(); con++) { 7970 final ConnectionRecord cr = crs.get(con); 7971 final ProcessRecord clientPr = cr.binding.client; 7972 7973 if (clientPr.uid == clientUid) { 7974 return Boolean.TRUE; 7975 } 7976 } 7977 } 7978 } 7979 } 7980 return null; 7981 }); 7982 if (Boolean.TRUE.equals(hasBinding)) { 7983 return true; 7984 } 7985 7986 final Boolean hasProviderClient = mProcessList.searchEachLruProcessesLOSP( 7987 false, pr -> { 7988 if (pr.uid == callingUid) { 7989 final ProcessProviderRecord ppr = pr.mProviders; 7990 for (int provi = ppr.numberOfProviders() - 1; provi >= 0; provi--) { 7991 ContentProviderRecord cpr = ppr.getProviderAt(provi); 7992 7993 for (int i = cpr.connections.size() - 1; i >= 0; i--) { 7994 ContentProviderConnection conn = cpr.connections.get(i); 7995 ProcessRecord client = conn.client; 7996 if (client.uid == clientUid) { 7997 return Boolean.TRUE; 7998 } 7999 } 8000 } 8001 } 8002 return null; 8003 }); 8004 8005 return Boolean.TRUE.equals(hasProviderClient); 8006 } 8007 8008 @Override getUidProcessCapabilities(int uid, String callingPackage)8009 public @ProcessCapability int getUidProcessCapabilities(int uid, String callingPackage) { 8010 if (!hasUsageStatsPermission(callingPackage)) { 8011 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8012 "getUidProcessState"); 8013 } 8014 // In case the caller is requesting processCapabilities of an app in a different user, 8015 // then verify the caller has INTERACT_ACROSS_USERS_FULL permission 8016 mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 8017 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY, 8018 "getUidProcessCapabilities", callingPackage); // Ignore return value 8019 8020 synchronized (mProcLock) { 8021 return mProcessList.getUidProcessCapabilityLOSP(uid); 8022 } 8023 } 8024 8025 @Override registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)8026 public void registerUidObserver(IUidObserver observer, int which, int cutpoint, 8027 String callingPackage) { 8028 registerUidObserverForUids(observer, which, cutpoint, callingPackage, null /* uids */); 8029 } 8030 8031 /** 8032 * Registers a UidObserver with a uid filter. 8033 * 8034 * @param observer The UidObserver implementation to register. 8035 * @param which A bitmask of events to observe. See ActivityManager.UID_OBSERVER_*. 8036 * @param cutpoint The cutpoint for onUidStateChanged events. When the state crosses this 8037 * threshold in either direction, onUidStateChanged will be called. 8038 * @param callingPackage The name of the calling package. 8039 * @param uids A list of uids to watch. If all uids are to be watched, use 8040 * registerUidObserver instead. 8041 * @throws RemoteException 8042 * @return Returns A binder token identifying the UidObserver registration. 8043 */ 8044 @Override registerUidObserverForUids(IUidObserver observer, int which, int cutpoint, String callingPackage, int[] uids)8045 public IBinder registerUidObserverForUids(IUidObserver observer, int which, int cutpoint, 8046 String callingPackage, int[] uids) { 8047 if (!hasUsageStatsPermission(callingPackage)) { 8048 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8049 "registerUidObserver"); 8050 } 8051 return mUidObserverController.register(observer, which, cutpoint, callingPackage, 8052 Binder.getCallingUid(), uids); 8053 } 8054 8055 @Override unregisterUidObserver(IUidObserver observer)8056 public void unregisterUidObserver(IUidObserver observer) { 8057 mUidObserverController.unregister(observer); 8058 } 8059 8060 /** 8061 * Adds a uid to the list of uids that a UidObserver will receive updates about. 8062 * 8063 * @param observerToken The binder token identifying the UidObserver registration. 8064 * @param callingPackage The name of the calling package. 8065 * @param uid The uid to watch. 8066 * @throws RemoteException 8067 */ 8068 @Override addUidToObserver(IBinder observerToken, String callingPackage, int uid)8069 public void addUidToObserver(IBinder observerToken, String callingPackage, int uid) { 8070 if (!hasUsageStatsPermission(callingPackage)) { 8071 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8072 "registerUidObserver"); 8073 } 8074 mUidObserverController.addUidToObserver(observerToken, uid); 8075 } 8076 8077 /** 8078 * Removes a uid from the list of uids that a UidObserver will receive updates about. 8079 * 8080 * @param observerToken The binder token identifying the UidObserver registration. 8081 * @param callingPackage The name of the calling package. 8082 * @param uid The uid to stop watching. 8083 * @throws RemoteException 8084 */ 8085 @Override removeUidFromObserver(IBinder observerToken, String callingPackage, int uid)8086 public void removeUidFromObserver(IBinder observerToken, String callingPackage, int uid) { 8087 if (!hasUsageStatsPermission(callingPackage)) { 8088 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8089 "registerUidObserver"); 8090 } 8091 mUidObserverController.removeUidFromObserver(observerToken, uid); 8092 } 8093 8094 @Override isUidActive(int uid, String callingPackage)8095 public boolean isUidActive(int uid, String callingPackage) { 8096 if (!hasUsageStatsPermission(callingPackage)) { 8097 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8098 "isUidActive"); 8099 } 8100 synchronized (mProcLock) { 8101 if (isUidActiveLOSP(uid)) { 8102 return true; 8103 } 8104 } 8105 return mInternal.isPendingTopUid(uid); 8106 } 8107 8108 @GuardedBy(anyOf = {"this", "mProcLock"}) isUidActiveLOSP(int uid)8109 boolean isUidActiveLOSP(int uid) { 8110 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 8111 return uidRecord != null && !uidRecord.isSetIdle(); 8112 } 8113 8114 @Override getUidLastIdleElapsedTime(int uid, String callingPackage)8115 public long getUidLastIdleElapsedTime(int uid, String callingPackage) { 8116 if (!hasUsageStatsPermission(callingPackage)) { 8117 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8118 "getUidLastIdleElapsedTime"); 8119 } 8120 synchronized (mProcLock) { 8121 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 8122 return uidRecord != null ? uidRecord.getRealLastIdleTime() : 0; 8123 } 8124 } 8125 8126 @GuardedBy("mUidFrozenStateChangedCallbackList") 8127 private final RemoteCallbackList<IUidFrozenStateChangedCallback> 8128 mUidFrozenStateChangedCallbackList = new RemoteCallbackList<>(); 8129 8130 /** 8131 * Register a {@link IUidFrozenStateChangedCallback} to receive Uid frozen state events. 8132 * 8133 * @param callback remote callback object to be registered 8134 */ 8135 @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS) 8136 @Override registerUidFrozenStateChangedCallback( @onNull IUidFrozenStateChangedCallback callback)8137 public void registerUidFrozenStateChangedCallback( 8138 @NonNull IUidFrozenStateChangedCallback callback) { 8139 Preconditions.checkNotNull(callback, "callback cannot be null"); 8140 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8141 "registerUidFrozenStateChangedCallback()"); 8142 synchronized (mUidFrozenStateChangedCallbackList) { 8143 final boolean registered = mUidFrozenStateChangedCallbackList.register(callback); 8144 if (!registered) { 8145 Slog.w(TAG, "Failed to register with RemoteCallbackList!"); 8146 } 8147 } 8148 } 8149 8150 /** 8151 * Unregister a {@link IUidFrozenStateChangedCallback}. 8152 * 8153 * @param callback remote callback object to be unregistered 8154 */ 8155 @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS) 8156 @Override unregisterUidFrozenStateChangedCallback( @onNull IUidFrozenStateChangedCallback callback)8157 public void unregisterUidFrozenStateChangedCallback( 8158 @NonNull IUidFrozenStateChangedCallback callback) { 8159 Preconditions.checkNotNull(callback, "callback cannot be null"); 8160 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8161 "unregisterUidFrozenStateChangedCallback()"); 8162 synchronized (mUidFrozenStateChangedCallbackList) { 8163 mUidFrozenStateChangedCallbackList.unregister(callback); 8164 } 8165 } 8166 8167 /** 8168 * Query the frozen state of a list of UIDs. 8169 * 8170 * @param uids the array of UIDs which the client would like to know the frozen state of. 8171 * @return An array containing the frozen state for each requested UID, by index. Will be set 8172 * to {@link UidFrozenStateChangedCallback#UID_FROZEN_STATE_FROZEN} 8173 * if the UID is frozen. If the UID is not frozen or not found, 8174 * {@link UidFrozenStateChangedCallback#UID_FROZEN_STATE_UNFROZEN} 8175 * will be set. 8176 * 8177 * @hide 8178 */ 8179 @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS) 8180 @Override getUidFrozenState(@onNull int[] uids)8181 public @NonNull int[] getUidFrozenState(@NonNull int[] uids) { 8182 Preconditions.checkNotNull(uids, "uid array cannot be null"); 8183 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 8184 "getUidFrozenState()"); 8185 8186 final int[] frozenStates = new int[uids.length]; 8187 synchronized (mProcLock) { 8188 for (int i = 0; i < uids.length; i++) { 8189 final UidRecord uidRec = mProcessList.mActiveUids.get(uids[i]); 8190 if (uidRec != null && uidRec.areAllProcessesFrozen()) { 8191 frozenStates[i] = UID_FROZEN_STATE_FROZEN; 8192 } else { 8193 frozenStates[i] = UID_FROZEN_STATE_UNFROZEN; 8194 } 8195 } 8196 } 8197 return frozenStates; 8198 } 8199 8200 /** 8201 * Notify the system that a UID has been frozen or unfrozen. 8202 * 8203 * @param uids The Uid(s) in question 8204 * @param frozenStates Frozen state for each UID index 8205 * 8206 * @hide 8207 */ reportUidFrozenStateChanged(@onNull int[] uids, @UidFrozenState int[] frozenStates)8208 public void reportUidFrozenStateChanged(@NonNull int[] uids, 8209 @UidFrozenState int[] frozenStates) { 8210 synchronized (mUidFrozenStateChangedCallbackList) { 8211 final int n = mUidFrozenStateChangedCallbackList.beginBroadcast(); 8212 for (int i = 0; i < n; i++) { 8213 try { 8214 mUidFrozenStateChangedCallbackList.getBroadcastItem(i).onUidFrozenStateChanged( 8215 uids, frozenStates); 8216 } catch (RemoteException e) { 8217 /* 8218 * The process at the other end has died or otherwise gone away. 8219 * According to spec, RemoteCallbacklist will take care of unregistering any 8220 * object associated with that process - we are safe to ignore the exception 8221 * here. 8222 */ 8223 } 8224 } 8225 mUidFrozenStateChangedCallbackList.finishBroadcast(); 8226 } 8227 } 8228 8229 @Override setPersistentVrThread(int tid)8230 public void setPersistentVrThread(int tid) { 8231 mActivityTaskManager.setPersistentVrThread(tid); 8232 } 8233 8234 /** 8235 * Schedule the given thread a normal scheduling priority. 8236 * 8237 * @param tid the tid of the thread to adjust the scheduling of. 8238 * @param suppressLogs {@code true} if any error logging should be disabled. 8239 * 8240 * @return {@code true} if this succeeded. 8241 */ scheduleAsRegularPriority(int tid, boolean suppressLogs)8242 public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) { 8243 try { 8244 Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0); 8245 return true; 8246 } catch (IllegalArgumentException e) { 8247 if (!suppressLogs) { 8248 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 8249 } 8250 } catch (SecurityException e) { 8251 if (!suppressLogs) { 8252 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 8253 } 8254 } 8255 return false; 8256 } 8257 8258 /** 8259 * Schedule the given thread an FIFO scheduling priority. 8260 * 8261 * @param tid the tid of the thread to adjust the scheduling of. 8262 * @param suppressLogs {@code true} if any error logging should be disabled. 8263 * 8264 * @return {@code true} if this succeeded. 8265 */ scheduleAsFifoPriority(int tid, boolean suppressLogs)8266 public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) { 8267 try { 8268 Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1); 8269 return true; 8270 } catch (IllegalArgumentException e) { 8271 if (!suppressLogs) { 8272 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 8273 } 8274 } catch (SecurityException e) { 8275 if (!suppressLogs) { 8276 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 8277 } 8278 } 8279 return false; 8280 } 8281 8282 /** 8283 * Switches the priority between SCHED_FIFO and SCHED_OTHER for the main thread and render 8284 * thread of the given process. 8285 */ 8286 @GuardedBy("mProcLock") setFifoPriority(@onNull ProcessRecord app, boolean enable)8287 static void setFifoPriority(@NonNull ProcessRecord app, boolean enable) { 8288 final int pid = app.getPid(); 8289 final int renderThreadTid = app.getRenderThreadTid(); 8290 if (enable) { 8291 scheduleAsFifoPriority(pid, true /* suppressLogs */); 8292 if (renderThreadTid != 0) { 8293 scheduleAsFifoPriority(renderThreadTid, true /* suppressLogs */); 8294 } 8295 } else { 8296 scheduleAsRegularPriority(pid, true /* suppressLogs */); 8297 if (renderThreadTid != 0) { 8298 scheduleAsRegularPriority(renderThreadTid, true /* suppressLogs */); 8299 } 8300 } 8301 } 8302 8303 @Override setRenderThread(int tid)8304 public void setRenderThread(int tid) { 8305 synchronized (mProcLock) { 8306 ProcessRecord proc; 8307 int pid = Binder.getCallingPid(); 8308 if (pid == Process.myPid()) { 8309 demoteSystemServerRenderThread(tid); 8310 return; 8311 } 8312 synchronized (mPidsSelfLocked) { 8313 proc = mPidsSelfLocked.get(pid); 8314 } 8315 if (proc != null && proc.getRenderThreadTid() == 0 && tid > 0) { 8316 // ensure the tid belongs to the process 8317 if (!isThreadInProcess(pid, tid)) { 8318 throw new IllegalArgumentException( 8319 "Render thread does not belong to process"); 8320 } 8321 proc.setRenderThreadTid(tid); 8322 if (DEBUG_OOM_ADJ) { 8323 Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid); 8324 } 8325 // promote to FIFO now 8326 if (proc.mState.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) { 8327 if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band"); 8328 if (proc.useFifoUiScheduling()) { 8329 setThreadScheduler(proc.getRenderThreadTid(), 8330 SCHED_FIFO | SCHED_RESET_ON_FORK, 1); 8331 } else { 8332 setThreadPriority(proc.getRenderThreadTid(), 8333 THREAD_PRIORITY_TOP_APP_BOOST); 8334 } 8335 } 8336 } else { 8337 if (DEBUG_OOM_ADJ) { 8338 Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " 8339 + "PID: " + pid + ", TID: " + tid + " FIFO: " + mUseFifoUiScheduling); 8340 } 8341 } 8342 } 8343 } 8344 8345 /** 8346 * We only use RenderThread in system_server to store task snapshots to the disk, which should 8347 * happen in the background. Thus, demote render thread from system_server to a lower priority. 8348 * 8349 * @param tid the tid of the RenderThread 8350 */ demoteSystemServerRenderThread(int tid)8351 private void demoteSystemServerRenderThread(int tid) { 8352 setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND); 8353 } 8354 8355 @Override isVrModePackageEnabled(ComponentName packageName)8356 public boolean isVrModePackageEnabled(ComponentName packageName) { 8357 mActivityTaskManager.enforceSystemHasVrFeature(); 8358 8359 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); 8360 8361 return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) == 8362 VrManagerInternal.NO_ERROR; 8363 } 8364 isTopActivityImmersive()8365 public boolean isTopActivityImmersive() { 8366 return mActivityTaskManager.isTopActivityImmersive(); 8367 } 8368 8369 @Override isTopOfTask(IBinder token)8370 public boolean isTopOfTask(IBinder token) { 8371 return ActivityClient.getInstance().isTopOfTask(token); 8372 } 8373 8374 @Override setHasTopUi(boolean hasTopUi)8375 public void setHasTopUi(boolean hasTopUi) throws RemoteException { 8376 if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) { 8377 String msg = "Permission Denial: setHasTopUi() from pid=" 8378 + Binder.getCallingPid() 8379 + ", uid=" + Binder.getCallingUid() 8380 + " requires " + permission.INTERNAL_SYSTEM_WINDOW; 8381 Slog.w(TAG, msg); 8382 throw new SecurityException(msg); 8383 } 8384 final int pid = Binder.getCallingPid(); 8385 final long origId = Binder.clearCallingIdentity(); 8386 try { 8387 synchronized (this) { 8388 boolean changed = false; 8389 ProcessRecord pr; 8390 synchronized (mPidsSelfLocked) { 8391 pr = mPidsSelfLocked.get(pid); 8392 if (pr == null) { 8393 Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid); 8394 return; 8395 } 8396 changed = mProcessStateController.setHasTopUi(pr, hasTopUi); 8397 } 8398 if (changed) { 8399 mProcessStateController.runUpdate(pr, OOM_ADJ_REASON_UI_VISIBILITY); 8400 } 8401 } 8402 } finally { 8403 Binder.restoreCallingIdentity(origId); 8404 } 8405 } 8406 enterSafeMode()8407 public final void enterSafeMode() { 8408 synchronized(this) { 8409 // It only makes sense to do this before the system is ready 8410 // and started launching other packages. 8411 if (!mSystemReady) { 8412 try { 8413 AppGlobals.getPackageManager().enterSafeMode(); 8414 } catch (RemoteException e) { 8415 } 8416 } 8417 8418 mSafeMode = true; 8419 } 8420 } 8421 showSafeModeOverlay()8422 public final void showSafeModeOverlay() { 8423 View v = LayoutInflater.from(mContext).inflate( 8424 com.android.internal.R.layout.safe_mode, null); 8425 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 8426 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 8427 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 8428 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 8429 lp.gravity = Gravity.BOTTOM | Gravity.START; 8430 lp.format = v.getBackground().getOpacity(); 8431 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 8432 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 8433 lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS; 8434 ((WindowManager)mContext.getSystemService( 8435 Context.WINDOW_SERVICE)).addView(v, lp); 8436 } 8437 8438 @Override noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)8439 public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, 8440 String sourcePkg, String tag) { 8441 if (workSource != null && workSource.isEmpty()) { 8442 workSource = null; 8443 } 8444 8445 if (sourceUid <= 0 && workSource == null) { 8446 // Try and derive a UID to attribute things to based on the caller. 8447 if (sender != null) { 8448 if (!(sender instanceof PendingIntentRecord)) { 8449 return; 8450 } 8451 8452 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8453 final int callerUid = Binder.getCallingUid(); 8454 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8455 } else { 8456 // TODO(narayan): Should we throw an exception in this case ? It means that we 8457 // haven't been able to derive a UID to attribute things to. 8458 return; 8459 } 8460 } 8461 8462 int standbyBucket = 0; 8463 8464 mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag); 8465 if (workSource != null) { 8466 String workSourcePackage = workSource.getPackageName(0); 8467 int workSourceUid = workSource.getAttributionUid(); 8468 if (workSourcePackage == null) { 8469 workSourcePackage = sourcePkg; 8470 workSourceUid = sourceUid; 8471 } 8472 8473 if (mUsageStatsService != null) { 8474 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage, 8475 UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime()); 8476 } 8477 8478 FrameworkStatsLog.write(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag, 8479 sourcePkg, standbyBucket); 8480 if (DEBUG_POWER) { 8481 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 8482 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 8483 + standbyBucket + " wsName=" + workSourcePackage + ")]"); 8484 } 8485 } else { 8486 if (mUsageStatsService != null) { 8487 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg, 8488 UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime()); 8489 } 8490 FrameworkStatsLog.write_non_chained(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, sourceUid, 8491 null, tag, sourcePkg, standbyBucket); 8492 if (DEBUG_POWER) { 8493 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 8494 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 8495 + standbyBucket + "]"); 8496 } 8497 } 8498 8499 } 8500 8501 @Override noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8502 public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, 8503 String tag) { 8504 if (workSource != null && workSource.isEmpty()) { 8505 workSource = null; 8506 } 8507 8508 if (sourceUid <= 0 && workSource == null) { 8509 // Try and derive a UID to attribute things to based on the caller. 8510 if (sender != null) { 8511 if (!(sender instanceof PendingIntentRecord)) { 8512 return; 8513 } 8514 8515 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8516 final int callerUid = Binder.getCallingUid(); 8517 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8518 } else { 8519 // TODO(narayan): Should we throw an exception in this case ? It means that we 8520 // haven't been able to derive a UID to attribute things to. 8521 return; 8522 } 8523 } 8524 8525 if (DEBUG_POWER) { 8526 Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource + 8527 ", tag=" + tag + "]"); 8528 } 8529 8530 mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid); 8531 } 8532 8533 @Override noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8534 public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, 8535 String tag) { 8536 if (workSource != null && workSource.isEmpty()) { 8537 workSource = null; 8538 } 8539 8540 if (sourceUid <= 0 && workSource == null) { 8541 // Try and derive a UID to attribute things to based on the caller. 8542 if (sender != null) { 8543 if (!(sender instanceof PendingIntentRecord)) { 8544 return; 8545 } 8546 8547 final PendingIntentRecord rec = (PendingIntentRecord) sender; 8548 final int callerUid = Binder.getCallingUid(); 8549 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 8550 } else { 8551 // TODO(narayan): Should we throw an exception in this case ? It means that we 8552 // haven't been able to derive a UID to attribute things to. 8553 return; 8554 } 8555 } 8556 8557 if (DEBUG_POWER) { 8558 Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource + 8559 ", tag=" + tag + "]"); 8560 } 8561 8562 mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid); 8563 } 8564 killPids(int[] pids, String pReason, boolean secure)8565 public boolean killPids(int[] pids, String pReason, boolean secure) { 8566 if (Binder.getCallingUid() != SYSTEM_UID) { 8567 throw new SecurityException("killPids only available to the system"); 8568 } 8569 final String reason = (pReason == null) ? "Unknown" : pReason; 8570 // XXX Note: don't acquire main activity lock here, because the window 8571 // manager calls in with its locks held. 8572 8573 boolean killed = false; 8574 final ArrayList<ProcessRecord> killCandidates = new ArrayList<>(); 8575 synchronized (mPidsSelfLocked) { 8576 int worstType = 0; 8577 for (int i = 0; i < pids.length; i++) { 8578 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 8579 if (proc != null) { 8580 int type = proc.mState.getSetAdj(); 8581 if (type > worstType) { 8582 worstType = type; 8583 } 8584 } 8585 } 8586 8587 // If the worst oom_adj is somewhere in the cached proc LRU range, 8588 // then constrain it so we will kill all cached procs. 8589 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 8590 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 8591 worstType = ProcessList.CACHED_APP_MIN_ADJ; 8592 } 8593 8594 // If this is not a secure call, don't let it kill processes that 8595 // are important. 8596 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 8597 worstType = ProcessList.SERVICE_ADJ; 8598 } 8599 8600 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 8601 for (int i = 0; i < pids.length; i++) { 8602 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 8603 if (proc == null) { 8604 continue; 8605 } 8606 int adj = proc.mState.getSetAdj(); 8607 if (adj >= worstType && !proc.isKilledByAm()) { 8608 killCandidates.add(proc); 8609 killed = true; 8610 } 8611 } 8612 } 8613 if (!killCandidates.isEmpty()) { 8614 mHandler.post(() -> { 8615 synchronized (ActivityManagerService.this) { 8616 for (int i = 0, size = killCandidates.size(); i < size; i++) { 8617 killCandidates.get(i).killLocked(reason, 8618 ApplicationExitInfo.REASON_OTHER, 8619 ApplicationExitInfo.SUBREASON_KILL_PID, true); 8620 } 8621 } 8622 }); 8623 } 8624 return killed; 8625 } 8626 killUid(int appId, int userId, int reason, int subReason, String reasonAsString)8627 private void killUid(int appId, int userId, int reason, int subReason, 8628 String reasonAsString) { 8629 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 8630 synchronized (this) { 8631 final long identity = Binder.clearCallingIdentity(); 8632 try { 8633 synchronized (mProcLock) { 8634 mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId, 8635 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 8636 true /* callerWillRestart */, true /* doit */, 8637 true /* evenPersistent */, false /* setRemoved */, 8638 false /* uninstalling */, 8639 reason, 8640 subReason, 8641 reasonAsString != null ? reasonAsString : "kill uid"); 8642 } 8643 } finally { 8644 Binder.restoreCallingIdentity(identity); 8645 } 8646 } 8647 } 8648 8649 @Override killUid(int appId, int userId, String reason)8650 public void killUid(int appId, int userId, String reason) { 8651 killUid(appId, userId, ApplicationExitInfo.REASON_OTHER, 8652 ApplicationExitInfo.SUBREASON_KILL_UID, reason); 8653 } 8654 8655 @Override killUidForPermissionChange(int appId, int userId, String reason)8656 public void killUidForPermissionChange(int appId, int userId, String reason) { 8657 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 8658 synchronized (this) { 8659 final long identity = Binder.clearCallingIdentity(); 8660 try { 8661 synchronized (mProcLock) { 8662 mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId, 8663 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 8664 true /* callerWillRestart */, true /* doit */, 8665 true /* evenPersistent */, false /* setRemoved */, 8666 false /* uninstalling */, 8667 ApplicationExitInfo.REASON_PERMISSION_CHANGE, 8668 ApplicationExitInfo.SUBREASON_UNKNOWN, 8669 reason != null ? reason : "kill uid"); 8670 } 8671 } finally { 8672 Binder.restoreCallingIdentity(identity); 8673 } 8674 } 8675 } 8676 8677 @Override killProcessesBelowForeground(String reason)8678 public boolean killProcessesBelowForeground(String reason) { 8679 if (Binder.getCallingUid() != SYSTEM_UID) { 8680 throw new SecurityException("killProcessesBelowForeground() only available to system"); 8681 } 8682 8683 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 8684 } 8685 killProcessesBelowAdj(int belowAdj, String reason)8686 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 8687 if (Binder.getCallingUid() != SYSTEM_UID) { 8688 throw new SecurityException("killProcessesBelowAdj() only available to system"); 8689 } 8690 8691 boolean killed = false; 8692 synchronized (this) { 8693 synchronized (mProcLock) { 8694 synchronized (mPidsSelfLocked) { 8695 final int size = mPidsSelfLocked.size(); 8696 for (int i = 0; i < size; i++) { 8697 final int pid = mPidsSelfLocked.keyAt(i); 8698 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 8699 if (proc == null) continue; 8700 8701 final int adj = proc.mState.getSetAdj(); 8702 if (adj > belowAdj && !proc.isKilledByAm()) { 8703 proc.killLocked(reason, ApplicationExitInfo.REASON_PERMISSION_CHANGE, 8704 true); 8705 killed = true; 8706 } 8707 } 8708 } 8709 } 8710 } 8711 return killed; 8712 } 8713 8714 /** 8715 * Similar to {@link #killPids} but killing will be delayed until the device is idle 8716 * and the given process is imperceptible. 8717 */ 8718 @Override killProcessesWhenImperceptible(int[] pids, String reason)8719 public void killProcessesWhenImperceptible(int[] pids, String reason) { 8720 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 8721 != PackageManager.PERMISSION_GRANTED) { 8722 throw new SecurityException("Requires permission " 8723 + android.Manifest.permission.FORCE_STOP_PACKAGES); 8724 } 8725 int callerUid = Binder.getCallingUid(); 8726 final long iden = Binder.clearCallingIdentity(); 8727 try { 8728 mProcessList.killProcessesWhenImperceptible(pids, reason, callerUid); 8729 } finally { 8730 Binder.restoreCallingIdentity(iden); 8731 } 8732 } 8733 8734 @Override hang(final IBinder who, boolean allowRestart)8735 public void hang(final IBinder who, boolean allowRestart) { 8736 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8737 != PackageManager.PERMISSION_GRANTED) { 8738 throw new SecurityException("Requires permission " 8739 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8740 } 8741 8742 final IBinder.DeathRecipient death = new DeathRecipient() { 8743 @Override 8744 public void binderDied() { 8745 synchronized (this) { 8746 notifyAll(); 8747 } 8748 } 8749 }; 8750 8751 try { 8752 who.linkToDeath(death, 0); 8753 } catch (RemoteException e) { 8754 Slog.w(TAG, "hang: given caller IBinder is already dead."); 8755 return; 8756 } 8757 8758 synchronized (this) { 8759 Watchdog.getInstance().setAllowRestart(allowRestart); 8760 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 8761 synchronized (death) { 8762 while (who.isBinderAlive()) { 8763 try { 8764 death.wait(); 8765 } catch (InterruptedException e) { 8766 } 8767 } 8768 } 8769 Watchdog.getInstance().setAllowRestart(true); 8770 } 8771 } 8772 8773 @Override restart()8774 public void restart() { 8775 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8776 != PackageManager.PERMISSION_GRANTED) { 8777 throw new SecurityException("Requires permission " 8778 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8779 } 8780 8781 Log.i(TAG, "Sending shutdown broadcast..."); 8782 8783 BroadcastReceiver br = new BroadcastReceiver() { 8784 @Override public void onReceive(Context context, Intent intent) { 8785 // Now the broadcast is done, finish up the low-level shutdown. 8786 Log.i(TAG, "Shutting down activity manager..."); 8787 shutdown(10000); 8788 Log.i(TAG, "Shutdown complete, restarting!"); 8789 killProcess(myPid()); 8790 System.exit(10); 8791 } 8792 }; 8793 8794 // First send the high-level shut down broadcast. 8795 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 8796 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8797 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 8798 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 8799 mContext.sendOrderedBroadcastAsUser(intent, 8800 UserHandle.ALL, null, br, mHandler, 0, null, null); 8801 */ 8802 br.onReceive(mContext, intent); 8803 } 8804 8805 @Override performIdleMaintenance()8806 public void performIdleMaintenance() { 8807 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8808 != PackageManager.PERMISSION_GRANTED) { 8809 throw new SecurityException("Requires permission " 8810 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8811 } 8812 8813 synchronized (mProcLock) { 8814 final long now = SystemClock.uptimeMillis(); 8815 final long timeSinceLastIdle = now - mLastIdleTime; 8816 8817 if (!disableSystemCompaction()) { 8818 // Compact all non-zygote processes to freshen up the page cache. 8819 mOomAdjuster.mCachedAppOptimizer.compactAllSystem(); 8820 } 8821 8822 final long lowRamSinceLastIdle = mAppProfiler.getLowRamTimeSinceIdleLPr(now); 8823 mLastIdleTime = now; 8824 mAppProfiler.updateLowRamTimestampLPr(now); 8825 8826 StringBuilder sb = new StringBuilder(128); 8827 sb.append("Idle maintenance over "); 8828 TimeUtils.formatDuration(timeSinceLastIdle, sb); 8829 sb.append(" low RAM for "); 8830 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 8831 Slog.i(TAG, sb.toString()); 8832 8833 // If at least 1/3 of our time since the last idle period has been spent 8834 // with RAM low, then we want to kill processes. 8835 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 8836 // If the processes' memory has increased by more than 1% of the total memory, 8837 // or 10 MB, whichever is greater, then the processes' are eligible to be killed. 8838 final long totalMemoryInKb = getTotalMemory() / 1000; 8839 8840 // This threshold should be applicable to both PSS and RSS because the value is absolute 8841 // and represents an increase in process memory relative to its own previous state. 8842 // 8843 // TODO(b/296454553): Tune this value during the flag rollout process if more processes 8844 // seem to be getting killed than before. 8845 final long memoryGrowthThreshold = 8846 Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD); 8847 mProcessList.forEachLruProcessesLOSP(false, proc -> { 8848 if (proc.getThread() == null) { 8849 return; 8850 } 8851 final ProcessProfileRecord pr = proc.mProfile; 8852 final ProcessStateRecord state = proc.mState; 8853 final int setProcState = state.getSetProcState(); 8854 if (state.isNotCachedSinceIdle()) { 8855 if (setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE 8856 && setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 8857 final long initialIdlePssOrRss, lastPssOrRss, lastSwapPss; 8858 synchronized (mAppProfiler.mProfilerLock) { 8859 initialIdlePssOrRss = pr.getInitialIdlePssOrRss(); 8860 lastPssOrRss = mAppProfiler.isProfilingPss() 8861 ? pr.getLastPss() : pr.getLastRss(); 8862 lastSwapPss = pr.getLastSwapPss(); 8863 } 8864 if (doKilling && initialIdlePssOrRss != 0 8865 && lastPssOrRss > (initialIdlePssOrRss * 3 / 2) 8866 && lastPssOrRss > (initialIdlePssOrRss + memoryGrowthThreshold)) { 8867 final StringBuilder sb2 = new StringBuilder(128); 8868 sb2.append("Kill"); 8869 sb2.append(proc.processName); 8870 if (mAppProfiler.isProfilingPss()) { 8871 sb2.append(" in idle maint: pss="); 8872 } else { 8873 sb2.append(" in idle maint: rss="); 8874 } 8875 sb2.append(lastPssOrRss); 8876 8877 if (mAppProfiler.isProfilingPss()) { 8878 sb2.append(", swapPss="); 8879 sb2.append(lastSwapPss); 8880 sb2.append(", initialPss="); 8881 } else { 8882 sb2.append(", initialRss="); 8883 } 8884 sb2.append(initialIdlePssOrRss); 8885 sb2.append(", period="); 8886 TimeUtils.formatDuration(timeSinceLastIdle, sb2); 8887 sb2.append(", lowRamPeriod="); 8888 TimeUtils.formatDuration(lowRamSinceLastIdle, sb2); 8889 Slog.wtfQuiet(TAG, sb2.toString()); 8890 mHandler.post(() -> { 8891 synchronized (ActivityManagerService.this) { 8892 proc.killLocked(mAppProfiler.isProfilingPss() 8893 ? "idle maint (pss " : "idle maint (rss " + lastPssOrRss 8894 + " from " + initialIdlePssOrRss + ")", 8895 ApplicationExitInfo.REASON_OTHER, 8896 ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE, 8897 true); 8898 } 8899 }); 8900 } 8901 } 8902 } else if (setProcState < ActivityManager.PROCESS_STATE_HOME 8903 && setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) { 8904 state.setNotCachedSinceIdle(true); 8905 synchronized (mAppProfiler.mProfilerLock) { 8906 pr.setInitialIdlePssOrRss(0); 8907 mAppProfiler.updateNextPssTimeLPf( 8908 state.getSetProcState(), proc.mProfile, now, true); 8909 } 8910 } 8911 }); 8912 } 8913 } 8914 8915 @Override sendIdleJobTrigger()8916 public void sendIdleJobTrigger() { 8917 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8918 != PackageManager.PERMISSION_GRANTED) { 8919 throw new SecurityException("Requires permission " 8920 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8921 } 8922 8923 final long ident = Binder.clearCallingIdentity(); 8924 try { 8925 Intent intent = new Intent(ACTION_TRIGGER_IDLE) 8926 .setPackage("android") 8927 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 8928 broadcastIntent(null, intent, null, null, 0, null, null, null, 8929 OP_NONE, null, false, false, UserHandle.USER_ALL); 8930 } finally { 8931 Binder.restoreCallingIdentity(ident); 8932 } 8933 } 8934 retrieveSettings()8935 private void retrieveSettings() { 8936 final ContentResolver resolver = mContext.getContentResolver(); 8937 mActivityTaskManager.retrieveSettings(resolver); 8938 8939 final String debugApp = Settings.Global.getString(resolver, DEBUG_APP); 8940 final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0; 8941 final boolean alwaysFinishActivities = 8942 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0; 8943 mHiddenApiBlacklist.registerObserver(); 8944 mPlatformCompat.registerContentObserver(); 8945 8946 mAppProfiler.retrieveSettings(); 8947 8948 final Resources res; 8949 synchronized (this) { 8950 mDebugApp = mOrigDebugApp = debugApp; 8951 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 8952 mAlwaysFinishActivities = alwaysFinishActivities; 8953 // Load resources only after the current configuration has been set. 8954 res = mContext.getResources(); 8955 final boolean userSwitchUiEnabled = !res.getBoolean( 8956 com.android.internal.R.bool.config_customUserSwitchUi); 8957 final int maxRunningUsers = res.getInteger( 8958 com.android.internal.R.integer.config_multiuserMaxRunningUsers); 8959 final boolean delayUserDataLocking = res.getBoolean( 8960 com.android.internal.R.bool.config_multiuserDelayUserDataLocking); 8961 final int backgroundUserScheduledStopTimeSecs = res.getInteger( 8962 com.android.internal.R.integer.config_backgroundUserScheduledStopTimeSecs); 8963 mUserController.setInitialConfig(userSwitchUiEnabled, maxRunningUsers, 8964 delayUserDataLocking, backgroundUserScheduledStopTimeSecs); 8965 } 8966 mAppErrors.loadAppsNotReportingCrashesFromConfig(res.getString( 8967 com.android.internal.R.string.config_appsNotReportingCrashes)); 8968 } 8969 8970 /** 8971 * Ready. Set. Go! 8972 */ systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t)8973 public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) { 8974 t.traceBegin("PhaseActivityManagerReady"); 8975 mSystemServiceManager.preSystemReady(); 8976 synchronized(this) { 8977 if (mSystemReady) { 8978 // If we're done calling all the receivers, run the next "boot phase" passed in 8979 // by the SystemServer 8980 if (goingCallback != null) { 8981 goingCallback.run(); 8982 } 8983 t.traceEnd(); // PhaseActivityManagerReady 8984 return; 8985 } 8986 8987 t.traceBegin("controllersReady"); 8988 mLocalDeviceIdleController = 8989 LocalServices.getService(DeviceIdleInternal.class); 8990 mActivityTaskManager.onSystemReady(); 8991 // Make sure we have the current profile info, since it is needed for security checks. 8992 mUserController.onSystemReady(); 8993 mAppOpsService.systemReady(); 8994 mProcessList.onSystemReady(); 8995 mAppRestrictionController.onSystemReady(); 8996 mSystemReady = true; 8997 t.traceEnd(); 8998 } 8999 9000 try { 9001 sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface( 9002 ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE)) 9003 .getSerial(); 9004 } catch (RemoteException e) {} 9005 9006 t.traceBegin("killProcesses"); 9007 ArrayList<ProcessRecord> procsToKill = null; 9008 synchronized(mPidsSelfLocked) { 9009 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 9010 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 9011 if (!isAllowedWhileBooting(proc.info)) { 9012 if (procsToKill == null) { 9013 procsToKill = new ArrayList<ProcessRecord>(); 9014 } 9015 procsToKill.add(proc); 9016 } 9017 } 9018 } 9019 9020 synchronized(this) { 9021 if (procsToKill != null) { 9022 for (int i = procsToKill.size() - 1; i >= 0; i--) { 9023 ProcessRecord proc = procsToKill.get(i); 9024 Slog.i(TAG, "Removing system update proc: " + proc); 9025 mProcessList.removeProcessLocked(proc, true, false, 9026 ApplicationExitInfo.REASON_OTHER, 9027 ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE, 9028 "system update done"); 9029 } 9030 } 9031 9032 // Now that we have cleaned up any update processes, we 9033 // are ready to start launching real processes and know that 9034 // we won't trample on them any more. 9035 mProcessesReady = true; 9036 } 9037 t.traceEnd(); // KillProcesses 9038 9039 Slog.i(TAG, "System now ready"); 9040 9041 EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis()); 9042 9043 t.traceBegin("updateTopComponentForFactoryTest"); 9044 mAtmInternal.updateTopComponentForFactoryTest(); 9045 t.traceEnd(); 9046 9047 t.traceBegin("registerActivityLaunchObserver"); 9048 mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver); 9049 t.traceEnd(); 9050 9051 t.traceBegin("watchDeviceProvisioning"); 9052 watchDeviceProvisioning(mContext); 9053 t.traceEnd(); 9054 9055 t.traceBegin("retrieveSettings"); 9056 retrieveSettings(); 9057 t.traceEnd(); 9058 9059 t.traceBegin("Ugm.onSystemReady"); 9060 mUgmInternal.onSystemReady(); 9061 t.traceEnd(); 9062 9063 t.traceBegin("updateForceBackgroundCheck"); 9064 final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class); 9065 if (pmi != null) { 9066 pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK, 9067 state -> updateForceBackgroundCheck(state.batterySaverEnabled)); 9068 updateForceBackgroundCheck( 9069 pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled); 9070 } else { 9071 Slog.wtf(TAG, "PowerManagerInternal not found."); 9072 } 9073 t.traceEnd(); 9074 9075 if (goingCallback != null) goingCallback.run(); 9076 9077 t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks 9078 // Check the current user here as a user can be started inside goingCallback.run() from 9079 // other system services. 9080 final int currentUserId = mUserController.getCurrentUserId(); 9081 Slog.i(TAG, "Current user:" + currentUserId); 9082 if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) { 9083 // User other than system user has started. Make sure that system user is already 9084 // started before switching user. 9085 throw new RuntimeException("System user not started while current user is:" 9086 + currentUserId); 9087 } 9088 t.traceEnd(); 9089 9090 t.traceBegin("ActivityManagerStartApps"); 9091 mBatteryStatsService.onSystemReady(); 9092 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 9093 Integer.toString(currentUserId), currentUserId); 9094 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 9095 Integer.toString(currentUserId), currentUserId); 9096 9097 // On Automotive / Headless System User Mode, at this point the system user has already been 9098 // started and unlocked, and some of the tasks we do here have already been done. So skip 9099 // those in that case. The duplicate system user start is guarded in SystemServiceManager. 9100 // TODO(b/266158156): this workaround shouldn't be necessary once we move the headless-user 9101 // start logic to UserManager-land. 9102 mUserController.onSystemUserStarting(); 9103 9104 synchronized (this) { 9105 // Only start up encryption-aware persistent apps; once user is 9106 // unlocked we'll come back around and start unaware apps 9107 t.traceBegin("startPersistentApps"); 9108 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE); 9109 t.traceEnd(); 9110 9111 // Start up initial activity. 9112 mBooting = true; 9113 // Enable home activity for system user, so that the system can always boot. We don't 9114 // do this when the system user is not setup since the setup wizard should be the one 9115 // to handle home activity in this case. 9116 if (SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) { 9117 t.traceBegin("enableHomeActivity"); 9118 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class); 9119 try { 9120 AppGlobals.getPackageManager().setComponentEnabledSetting(cName, 9121 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0, 9122 UserHandle.USER_SYSTEM, "am"); 9123 } catch (RemoteException e) { 9124 throw e.rethrowAsRuntimeException(); 9125 } 9126 t.traceEnd(); 9127 } 9128 9129 boolean isBootingSystemUser = currentUserId == UserHandle.USER_SYSTEM; 9130 9131 // Some systems - like automotive - will explicitly unlock system user then switch 9132 // to a secondary user. 9133 // TODO(b/266158156): this workaround shouldn't be necessary once we move 9134 // the headless-user start logic to UserManager-land. 9135 if (isBootingSystemUser && !UserManager.isHeadlessSystemUserMode()) { 9136 t.traceBegin("startHomeOnAllDisplays"); 9137 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady"); 9138 t.traceEnd(); 9139 } 9140 9141 mHandler.post(mAtmInternal::showSystemReadyErrorDialogsIfNeeded); 9142 9143 if (isBootingSystemUser) { 9144 // Need to send the broadcasts for the system user here because 9145 // UserController#startUserInternal will not send them for the system user starting, 9146 // It checks if the user state already exists, which is always the case for the 9147 // system user. 9148 t.traceBegin("sendUserStartBroadcast"); 9149 final int callingUid = Binder.getCallingUid(); 9150 final int callingPid = Binder.getCallingPid(); 9151 final long ident = Binder.clearCallingIdentity(); 9152 try { 9153 mUserController.sendUserStartedBroadcast( 9154 currentUserId, callingUid, callingPid); 9155 mUserController.sendUserStartingBroadcast( 9156 currentUserId, callingUid, callingPid); 9157 } catch (Throwable e) { 9158 Slog.wtf(TAG, "Failed sending first user broadcasts", e); 9159 } finally { 9160 Binder.restoreCallingIdentity(ident); 9161 } 9162 t.traceEnd(); 9163 } else { 9164 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user " 9165 + currentUserId); 9166 } 9167 9168 t.traceBegin("resumeTopActivities"); 9169 mAtmInternal.resumeTopActivities(false /* scheduleIdle */); 9170 t.traceEnd(); 9171 9172 if (isBootingSystemUser) { 9173 t.traceBegin("sendUserSwitchBroadcasts"); 9174 mUserController.sendUserSwitchBroadcasts(-1, currentUserId); 9175 t.traceEnd(); 9176 } 9177 9178 t.traceBegin("setBinderProxies"); 9179 BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK, 9180 BINDER_PROXY_LOW_WATERMARK, BINDER_PROXY_WARNING_WATERMARK); 9181 BinderInternal.nSetBinderProxyCountEnabled(true); 9182 BinderInternal.setBinderProxyCountCallback(new MyBinderProxyCountEventListener(), 9183 mHandler); 9184 t.traceEnd(); // setBinderProxies 9185 9186 t.traceEnd(); // ActivityManagerStartApps 9187 9188 // Load the component aliases. 9189 t.traceBegin("componentAlias"); 9190 mComponentAliasResolver.onSystemReady(mConstants.mEnableComponentAlias, 9191 mConstants.mComponentAliasOverrides); 9192 t.traceEnd(); // componentAlias 9193 9194 t.traceEnd(); // PhaseActivityManagerReady 9195 } 9196 } 9197 9198 private class MyBinderProxyCountEventListener implements BinderProxyCountEventListener { 9199 @Override onLimitReached(int uid)9200 public void onLimitReached(int uid) { 9201 // Spawn a new thread for the dump as it'll take long time. 9202 new Thread(() -> handleLimitReached(uid), "BinderProxy Dump: " + uid).start(); 9203 } 9204 handleLimitReached(int uid)9205 private void handleLimitReached(int uid) { 9206 Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid " 9207 + Process.myUid()); 9208 BinderProxy.dumpProxyDebugInfo(); 9209 CriticalEventLog.getInstance().logExcessiveBinderCalls(uid); 9210 if (uid == Process.SYSTEM_UID) { 9211 Slog.i(TAG, "Skipping kill (uid is SYSTEM)"); 9212 } else { 9213 killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid), 9214 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 9215 ApplicationExitInfo.SUBREASON_EXCESSIVE_BINDER_OBJECTS, 9216 "Too many Binders sent to SYSTEM"); 9217 // We need to run a GC here, because killing the processes involved 9218 // actually isn't guaranteed to free up the proxies; in fact, if the 9219 // GC doesn't run for a long time, we may even exceed the global 9220 // proxy limit for a process (20000), resulting in system_server itself 9221 // being killed. 9222 // Note that the GC here might not actually clean up all the proxies, 9223 // because the binder reference decrements will come in asynchronously; 9224 // but if new processes belonging to the UID keep adding proxies, we 9225 // will get another callback here, and run the GC again - this time 9226 // cleaning up the old proxies. 9227 VMRuntime.getRuntime().requestConcurrentGC(); 9228 } 9229 } 9230 9231 @Override onWarningThresholdReached(int uid)9232 public void onWarningThresholdReached(int uid) { 9233 if (Flags.logExcessiveBinderProxies()) { 9234 Slog.w(TAG, "Uid " + uid + " sent too many (" 9235 + BINDER_PROXY_WARNING_WATERMARK + ") Binders to uid " + Process.myUid()); 9236 FrameworkStatsLog.write( 9237 FrameworkStatsLog.EXCESSIVE_BINDER_PROXY_COUNT_REPORTED, 9238 uid); 9239 } 9240 } 9241 } 9242 watchDeviceProvisioning(Context context)9243 private void watchDeviceProvisioning(Context context) { 9244 // setting system property based on whether device is provisioned 9245 9246 if (isDeviceProvisioned(context)) { 9247 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 9248 } else { 9249 // watch for device provisioning change 9250 context.getContentResolver().registerContentObserver( 9251 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false, 9252 new ContentObserver(new Handler(Looper.getMainLooper())) { 9253 @Override 9254 public void onChange(boolean selfChange) { 9255 if (isDeviceProvisioned(context)) { 9256 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 9257 context.getContentResolver().unregisterContentObserver(this); 9258 } 9259 } 9260 }); 9261 } 9262 } 9263 isDeviceProvisioned(Context context)9264 private boolean isDeviceProvisioned(Context context) { 9265 return Settings.Global.getInt(context.getContentResolver(), 9266 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 9267 } 9268 updateForceBackgroundCheck(boolean enabled)9269 private void updateForceBackgroundCheck(boolean enabled) { 9270 synchronized (this) { 9271 synchronized (mProcLock) { 9272 if (mForceBackgroundCheck != enabled) { 9273 mForceBackgroundCheck = enabled; 9274 9275 if (DEBUG_BACKGROUND_CHECK) { 9276 Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled")); 9277 } 9278 9279 if (mForceBackgroundCheck) { 9280 // Stop background services for idle UIDs. 9281 mProcessList.doStopUidForIdleUidsLocked(); 9282 } 9283 } 9284 } 9285 } 9286 } 9287 killAppAtUsersRequest(ProcessRecord app)9288 void killAppAtUsersRequest(ProcessRecord app) { 9289 synchronized (this) { 9290 mAppErrors.killAppAtUserRequestLocked(app); 9291 } 9292 } 9293 9294 /** 9295 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 9296 * The application process will exit immediately after this call returns. 9297 * @param app object of the crashing app, null for the system server 9298 * @param crashInfo describing the exception 9299 */ handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)9300 public void handleApplicationCrash(IBinder app, 9301 ApplicationErrorReport.ParcelableCrashInfo crashInfo) { 9302 ProcessRecord r = findAppProcess(app, "Crash"); 9303 final String processName = app == null ? "system_server" 9304 : (r == null ? "unknown" : r.processName); 9305 9306 handleApplicationCrashInner("crash", r, processName, crashInfo); 9307 } 9308 9309 /* Native crash reporting uses this inner version because it needs to be somewhat 9310 * decoupled from the AM-managed cleanup lifecycle 9311 */ handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)9312 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 9313 ApplicationErrorReport.CrashInfo crashInfo) { 9314 float loadingProgress = 1; 9315 IncrementalMetrics incrementalMetrics = null; 9316 // Obtain Incremental information if available 9317 if (r != null && r.info != null && r.info.packageName != null) { 9318 IncrementalStatesInfo incrementalStatesInfo = 9319 mPackageManagerInt.getIncrementalStatesInfo(r.info.packageName, SYSTEM_UID, 9320 r.userId); 9321 if (incrementalStatesInfo != null) { 9322 loadingProgress = incrementalStatesInfo.getProgress(); 9323 } 9324 final String codePath = r.info.getCodePath(); 9325 if (codePath != null && !codePath.isEmpty() 9326 && IncrementalManager.isIncrementalPath(codePath)) { 9327 // Report in the main log about the incremental package 9328 Slog.e(TAG, "App crashed on incremental package " + r.info.packageName 9329 + " which is " + ((int) (loadingProgress * 100)) + "% loaded."); 9330 final IBinder incrementalService = ServiceManager.getService( 9331 Context.INCREMENTAL_SERVICE); 9332 if (incrementalService != null) { 9333 final IncrementalManager incrementalManager = new IncrementalManager( 9334 IIncrementalService.Stub.asInterface(incrementalService)); 9335 incrementalMetrics = incrementalManager.getMetrics(codePath); 9336 } 9337 } 9338 } 9339 9340 boolean recoverable = eventType.equals("native_recoverable_crash"); 9341 9342 EventLogTags.writeAmCrash(Binder.getCallingPid(), 9343 UserHandle.getUserId(Binder.getCallingUid()), processName, 9344 r == null ? -1 : r.info.flags, 9345 crashInfo.exceptionClassName, 9346 crashInfo.exceptionMessage, 9347 crashInfo.throwFileName, 9348 crashInfo.throwLineNumber, 9349 recoverable ? 1 : 0); 9350 9351 int processClassEnum = processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER 9352 : (r != null) ? r.getProcessClassEnum() 9353 : ServerProtoEnums.ERROR_SOURCE_UNKNOWN; 9354 int uid = (r != null) ? r.uid : -1; 9355 int pid = (r != null) ? r.getPid() : -1; 9356 FrameworkStatsLog.write(FrameworkStatsLog.APP_CRASH_OCCURRED, 9357 uid, 9358 eventType, 9359 processName, 9360 pid, 9361 (r != null && r.info != null) ? r.info.packageName : "", 9362 (r != null && r.info != null) ? (r.info.isInstantApp() 9363 ? FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE 9364 : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE) 9365 : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE, 9366 r != null ? (r.isInterestingToUserLocked() 9367 ? FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND 9368 : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND) 9369 : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN, 9370 processClassEnum, 9371 incrementalMetrics != null /* isIncremental */, loadingProgress, 9372 incrementalMetrics != null ? incrementalMetrics.getMillisSinceOldestPendingRead() 9373 : -1, 9374 incrementalMetrics != null ? incrementalMetrics.getStorageHealthStatusCode() 9375 : -1, 9376 incrementalMetrics != null ? incrementalMetrics.getDataLoaderStatusCode() 9377 : -1, 9378 incrementalMetrics != null && incrementalMetrics.getReadLogsEnabled(), 9379 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastDataLoaderBind() 9380 : -1, 9381 incrementalMetrics != null ? incrementalMetrics.getDataLoaderBindDelayMillis() 9382 : -1, 9383 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReads() 9384 : -1, 9385 incrementalMetrics != null ? incrementalMetrics.getTotalFailedReads() 9386 : -1, 9387 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorUid() 9388 : -1, 9389 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastReadError() 9390 : -1, 9391 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorNumber() 9392 : 0, 9393 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReadsDurationMillis() 9394 : -1 9395 ); 9396 9397 if (eventType.equals("native_crash")) { 9398 CriticalEventLog.getInstance().logNativeCrash(processClassEnum, processName, uid, pid); 9399 } else if (eventType.equals("crash")) { 9400 CriticalEventLog.getInstance().logJavaCrash(crashInfo.exceptionClassName, 9401 processClassEnum, processName, uid, pid); 9402 } 9403 9404 final int relaunchReason = r == null ? RELAUNCH_REASON_NONE 9405 : r.getWindowProcessController().computeRelaunchReason(); 9406 final String relaunchReasonString = relaunchReasonToString(relaunchReason); 9407 if (crashInfo.crashTag == null) { 9408 crashInfo.crashTag = relaunchReasonString; 9409 } else { 9410 crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString; 9411 } 9412 9413 addErrorToDropBox( 9414 eventType, r, processName, null, null, null, null, null, null, crashInfo, 9415 new Float(loadingProgress), incrementalMetrics, null, null); 9416 9417 // For GWP-ASan recoverable crashes, don't make the app crash (the whole point of 9418 // 'recoverable' is that the app doesn't crash). Normally, for nonrecoreable native crashes, 9419 // debuggerd will terminate the process, but there's a backup where ActivityManager will 9420 // also kill it. Avoid that. 9421 if (recoverable) { 9422 mAppErrors.sendRecoverableCrashToAppExitInfo(r, crashInfo); 9423 } else { 9424 mAppErrors.crashApplication(r, crashInfo); 9425 } 9426 } 9427 handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)9428 public void handleApplicationStrictModeViolation( 9429 IBinder app, 9430 int penaltyMask, 9431 StrictMode.ViolationInfo info) { 9432 // We're okay if the ProcessRecord is missing; it probably means that 9433 // we're reporting a violation from the system process itself. 9434 final ProcessRecord r = findAppProcess(app, "StrictMode"); 9435 9436 if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) { 9437 Integer stackFingerprint = info.hashCode(); 9438 boolean logIt = true; 9439 synchronized (mAlreadyLoggedViolatedStacks) { 9440 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 9441 logIt = false; 9442 // TODO: sub-sample into EventLog for these, with 9443 // the info.durationMillis? Then we'd get 9444 // the relative pain numbers, without logging all 9445 // the stack traces repeatedly. We'd want to do 9446 // likewise in the client code, which also does 9447 // dup suppression, before the Binder call. 9448 } else { 9449 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 9450 mAlreadyLoggedViolatedStacks.clear(); 9451 } 9452 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 9453 } 9454 } 9455 if (logIt) { 9456 logStrictModeViolationToDropBox(r, info); 9457 } 9458 } 9459 9460 if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) { 9461 AppErrorResult result = new AppErrorResult(); 9462 final long origId = Binder.clearCallingIdentity(); 9463 try { 9464 Message msg = Message.obtain(); 9465 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG; 9466 HashMap<String, Object> data = new HashMap<String, Object>(); 9467 data.put("result", result); 9468 data.put("app", r); 9469 data.put("info", info); 9470 msg.obj = data; 9471 mUiHandler.sendMessage(msg); 9472 } finally { 9473 Binder.restoreCallingIdentity(origId); 9474 } 9475 int res = result.get(); 9476 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 9477 } 9478 } 9479 9480 /** 9481 * Register a callback to raise strict mode violations. 9482 * @param callback The binder used to communicate the violations. 9483 */ 9484 @Override registerStrictModeCallback(IBinder callback)9485 public void registerStrictModeCallback(IBinder callback) { 9486 final int callingPid = Binder.getCallingPid(); 9487 synchronized (mStrictModeCallbacks) { 9488 mStrictModeCallbacks.put(callingPid, 9489 IUnsafeIntentStrictModeCallback.Stub.asInterface(callback)); 9490 try { 9491 callback.linkToDeath(() -> { 9492 synchronized (mStrictModeCallbacks) { 9493 mStrictModeCallbacks.remove(callingPid); 9494 } 9495 }, 0); 9496 } catch (RemoteException e) { 9497 mStrictModeCallbacks.remove(callingPid); 9498 } 9499 } 9500 } 9501 9502 // Depending on the policy in effect, there could be a bunch of 9503 // these in quick succession so we try to batch these together to 9504 // minimize disk writes, number of dropbox entries, and maximize 9505 // compression, by having more fewer, larger records. logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)9506 private void logStrictModeViolationToDropBox( 9507 ProcessRecord process, 9508 StrictMode.ViolationInfo info) { 9509 if (info == null) { 9510 return; 9511 } 9512 final boolean isSystemApp = process == null || 9513 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 9514 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 9515 final String processName = process != null && process.getPid() == MY_PID 9516 ? "system_server" 9517 : (process == null ? "unknown" : process.processName); 9518 final DropBoxManager dbox = (DropBoxManager) 9519 mContext.getSystemService(Context.DROPBOX_SERVICE); 9520 9521 // Exit early if the dropbox isn't configured to accept this report type. 9522 final String dropboxTag = processClass(process) + "_strictmode"; 9523 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 9524 9525 final StringBuilder sb = new StringBuilder(1024); 9526 synchronized (sb) { 9527 appendDropBoxProcessHeaders(process, processName, null, sb); 9528 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 9529 sb.append("System-App: ").append(isSystemApp).append("\n"); 9530 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 9531 if (info.violationNumThisLoop != 0) { 9532 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 9533 } 9534 if (info.numAnimationsRunning != 0) { 9535 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 9536 } 9537 if (info.broadcastIntentAction != null) { 9538 sb.append("Broadcast-Intent-Action: ") 9539 .append(info.broadcastIntentAction) 9540 .append("\n"); 9541 } 9542 if (info.durationMillis != -1) { 9543 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 9544 } 9545 if (info.numInstances != -1) { 9546 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 9547 } 9548 if (info.tags != null) { 9549 for (String tag : info.tags) { 9550 sb.append("Span-Tag: ").append(tag).append("\n"); 9551 } 9552 } 9553 sb.append("\n"); 9554 sb.append(info.getStackTrace()); 9555 sb.append("\n"); 9556 if (info.getViolationDetails() != null) { 9557 sb.append(info.getViolationDetails()); 9558 sb.append("\n"); 9559 } 9560 } 9561 9562 final String res = sb.toString(); 9563 IoThread.getHandler().post(() -> { 9564 dbox.addText(dropboxTag, res); 9565 }); 9566 } 9567 9568 /** 9569 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 9570 * @param app object of the crashing app, null for the system server 9571 * @param tag reported by the caller 9572 * @param system whether this wtf is coming from the system 9573 * @param crashInfo describing the context of the error 9574 * @return true if the process should exit immediately (WTF is fatal) 9575 */ 9576 @Override handleApplicationWtf(@ullable final IBinder app, @Nullable final String tag, boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)9577 public boolean handleApplicationWtf(@Nullable final IBinder app, @Nullable final String tag, 9578 boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, 9579 int immediateCallerPid) { 9580 final int callingUid = Binder.getCallingUid(); 9581 final int callingPid = Binder.getCallingPid(); 9582 9583 // Internal callers in RuntimeInit should always generate a crashInfo. 9584 Preconditions.checkNotNull(crashInfo); 9585 9586 // If this is coming from the system, we could very well have low-level 9587 // system locks held, so we want to do this all asynchronously. And we 9588 // never want this to become fatal, so there is that too. 9589 // 9590 // Note: "callingPid == Process.myPid())" wouldn't be reliable because even if the caller 9591 // is within the system server, if it calls Log.wtf() without clearning the calling 9592 // identity, callingPid would still be of a remote caller. So we explicltly pass the 9593 // process PID from the caller. 9594 if (system || (immediateCallerPid == Process.myPid())) { 9595 mHandler.post(new Runnable() { 9596 @Override public void run() { 9597 handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo); 9598 } 9599 }); 9600 return false; 9601 } 9602 9603 final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag, 9604 crashInfo); 9605 9606 final boolean isFatal = Build.IS_ENG || Settings.Global 9607 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0; 9608 final boolean isSystem = (r == null) || r.isPersistent(); 9609 9610 if (isFatal && !isSystem) { 9611 mAppErrors.crashApplication(r, crashInfo); 9612 return true; 9613 } else { 9614 return false; 9615 } 9616 } 9617 handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo)9618 ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, 9619 @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo) { 9620 final ProcessRecord r = findAppProcess(app, "WTF"); 9621 final String processName = app == null ? "system_server" 9622 : (r == null ? "unknown" : r.processName); 9623 9624 EventLogTags.writeAmWtf(UserHandle.getUserId(callingUid), callingPid, 9625 processName, r == null ? -1 : r.info.flags, tag, 9626 crashInfo == null ? "unknown" : crashInfo.exceptionMessage); 9627 9628 FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, callingUid, tag, processName, 9629 callingPid, (r != null) ? r.getProcessClassEnum() : 0); 9630 9631 addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo, 9632 null, null, null, null); 9633 9634 return r; 9635 } 9636 9637 /** 9638 * Schedule to handle any pending system_server WTFs. 9639 */ schedulePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)9640 public void schedulePendingSystemServerWtfs( 9641 final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) { 9642 mHandler.post(() -> handlePendingSystemServerWtfs(list)); 9643 } 9644 9645 /** 9646 * Handle any pending system_server WTFs, add into the dropbox 9647 */ handlePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)9648 private void handlePendingSystemServerWtfs( 9649 final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) { 9650 ProcessRecord proc; 9651 synchronized (mPidsSelfLocked) { 9652 proc = mPidsSelfLocked.get(MY_PID); 9653 } 9654 for (Pair<String, ApplicationErrorReport.CrashInfo> p = list.poll(); 9655 p != null; p = list.poll()) { 9656 addErrorToDropBox("wtf", proc, "system_server", null, null, null, p.first, null, null, 9657 p.second, null, null, null, null); 9658 } 9659 } 9660 9661 /** 9662 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 9663 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 9664 */ findAppProcess(IBinder app, String reason)9665 private ProcessRecord findAppProcess(IBinder app, String reason) { 9666 if (app == null) { 9667 return null; 9668 } 9669 9670 synchronized (mProcLock) { 9671 return mProcessList.findAppProcessLOSP(app, reason); 9672 } 9673 } 9674 9675 /** 9676 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 9677 * to append various headers to the dropbox log text. 9678 */ appendDropBoxProcessHeaders(ProcessRecord process, String processName, final VolatileDropboxEntryStates volatileStates, final StringBuilder sb)9679 void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 9680 final VolatileDropboxEntryStates volatileStates, final StringBuilder sb) { 9681 sb.append("SystemUptimeMs: ").append(SystemClock.uptimeMillis()).append("\n"); 9682 9683 // Watchdog thread ends up invoking this function (with 9684 // a null ProcessRecord) to add the stack file to dropbox. 9685 // Do not acquire a lock on this (am) in such cases, as it 9686 // could cause a potential deadlock, if and when watchdog 9687 // is invoked due to unavailability of lock on am and it 9688 // would prevent watchdog from killing system_server. 9689 if (process == null) { 9690 sb.append("Process: ").append(processName).append("\n"); 9691 return; 9692 } 9693 // Note: ProcessRecord 'process' is guarded by the service 9694 // instance. (notably process.pkgList, which could otherwise change 9695 // concurrently during execution of this method) 9696 synchronized (mProcLock) { 9697 sb.append("Process: ").append(processName).append("\n"); 9698 sb.append("PID: ").append(process.getPid()).append("\n"); 9699 sb.append("UID: ").append(process.uid).append("\n"); 9700 if (process.mOptRecord != null) { 9701 // Use 'isProcessFrozen' from 'volatileStates' if it'snon-null (present), 9702 // otherwise use 'isFrozen' from 'mOptRecord'. 9703 sb.append("Frozen: ").append( 9704 (volatileStates != null && volatileStates.isProcessFrozen() != null) 9705 ? volatileStates.isProcessFrozen() : process.mOptRecord.isFrozen() 9706 ).append("\n"); 9707 } 9708 if (volatileStates != null && volatileStates.getTimestamp() != null) { 9709 String formattedTime = DROPBOX_TIME_FORMATTER.format( 9710 volatileStates.getTimestamp()); 9711 sb.append("Timestamp: ").append(formattedTime).append("\n"); 9712 } 9713 int flags = process.info.flags; 9714 final IPackageManager pm = AppGlobals.getPackageManager(); 9715 sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n"); 9716 final int callingUserId = UserHandle.getCallingUserId(); 9717 process.getPkgList().forEachPackage(pkg -> { 9718 sb.append("Package: ").append(pkg); 9719 try { 9720 final PackageInfo pi = pm.getPackageInfo(pkg, 0, callingUserId); 9721 if (pi != null) { 9722 sb.append(" v").append(pi.getLongVersionCode()); 9723 if (pi.versionName != null) { 9724 sb.append(" (").append(pi.versionName).append(")"); 9725 } 9726 } 9727 } catch (RemoteException e) { 9728 Slog.e(TAG, "Error getting package info: " + pkg, e); 9729 } 9730 sb.append("\n"); 9731 }); 9732 if (process.info.isInstantApp()) { 9733 sb.append("Instant-App: true\n"); 9734 } 9735 9736 if (process.isSdkSandbox) { 9737 final String clientPackage = process.sdkSandboxClientAppPackage; 9738 try { 9739 final PackageInfo pi = pm.getPackageInfo(clientPackage, 9740 PackageManager.GET_SHARED_LIBRARY_FILES, callingUserId); 9741 if (pi != null) { 9742 appendSdkSandboxClientPackageHeader(sb, pi); 9743 appendSdkSandboxLibraryHeaders(sb, pi); 9744 } else { 9745 Slog.e(TAG, 9746 "PackageInfo is null for SDK sandbox client: " + clientPackage); 9747 } 9748 } catch (RemoteException e) { 9749 Slog.e(TAG, 9750 "Error getting package info for SDK sandbox client: " + clientPackage, 9751 e); 9752 } 9753 sb.append("SdkSandbox: true\n"); 9754 } 9755 } 9756 } 9757 appendSdkSandboxClientPackageHeader(StringBuilder sb, PackageInfo clientPackageInfo)9758 private void appendSdkSandboxClientPackageHeader(StringBuilder sb, 9759 PackageInfo clientPackageInfo) { 9760 sb.append("SdkSandbox-Client-Package: ").append(clientPackageInfo.packageName); 9761 sb.append(" v").append(clientPackageInfo.getLongVersionCode()); 9762 if (clientPackageInfo.versionName != null) { 9763 sb.append(" (").append(clientPackageInfo.versionName).append(")"); 9764 } 9765 sb.append("\n"); 9766 } 9767 appendSdkSandboxLibraryHeaders(StringBuilder sb, PackageInfo clientPackageInfo)9768 private void appendSdkSandboxLibraryHeaders(StringBuilder sb, 9769 PackageInfo clientPackageInfo) { 9770 final ApplicationInfo info = clientPackageInfo.applicationInfo; 9771 final List<SharedLibraryInfo> sharedLibraries = info.getSharedLibraryInfos(); 9772 for (int j = 0, size = sharedLibraries.size(); j < size; j++) { 9773 final SharedLibraryInfo sharedLibrary = sharedLibraries.get(j); 9774 if (!sharedLibrary.isSdk()) { 9775 continue; 9776 } 9777 9778 sb.append("SdkSandbox-Library: ").append(sharedLibrary.getPackageName()); 9779 final VersionedPackage versionedPackage = sharedLibrary.getDeclaringPackage(); 9780 sb.append(" v").append(versionedPackage.getLongVersionCode()); 9781 sb.append("\n"); 9782 } 9783 } 9784 processClass(ProcessRecord process)9785 private static String processClass(ProcessRecord process) { 9786 if (process == null || process.getPid() == MY_PID) { 9787 return "system_server"; 9788 } else if (process.info.isSystemApp() || process.info.isSystemExt()) { 9789 return "system_app"; 9790 } else { 9791 return "data_app"; 9792 } 9793 } 9794 9795 private final DropboxRateLimiter mDropboxRateLimiter = new DropboxRateLimiter(); 9796 9797 /** Initializes the Dropbox Rate Limiter parameters from flags. */ initDropboxRateLimiter()9798 public void initDropboxRateLimiter() { 9799 mDropboxRateLimiter.init(); 9800 } 9801 9802 /** 9803 * Write a description of an error (crash, WTF, ANR) to the drop box. 9804 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 9805 * @param process which caused the error, null means the system server 9806 * @param activityShortComponentName which triggered the error, null if unknown 9807 * @param parentShortComponentName activity related to the error, null if unknown 9808 * @param parentProcess parent process 9809 * @param subject line related to the error, null if absent 9810 * @param report in long form describing the error, null if absent 9811 * @param dataFile text file to include in the report, null if none 9812 * @param crashInfo giving an application stack trace, null if absent 9813 * @param loadingProgress the loading progress of an installed package, range in [0, 1]. 9814 * @param incrementalMetrics metrics for apps installed on Incremental. 9815 * @param errorId a unique id to append to the dropbox headers. 9816 */ 9817 @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)9818 public void addErrorToDropBox(String eventType, 9819 ProcessRecord process, String processName, String activityShortComponentName, 9820 String parentShortComponentName, ProcessRecord parentProcess, 9821 String subject, final String report, final File dataFile, 9822 final ApplicationErrorReport.CrashInfo crashInfo, 9823 @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics, 9824 @Nullable UUID errorId, @Nullable VolatileDropboxEntryStates volatileStates) { 9825 // NOTE -- this must never acquire the ActivityManagerService lock, 9826 // otherwise the watchdog may be prevented from resetting the system. 9827 9828 // Bail early if not published yet 9829 final DropBoxManager dbox; 9830 try { 9831 dbox = mContext.getSystemService(DropBoxManager.class); 9832 } catch (Exception e) { 9833 return; 9834 } 9835 9836 // Exit early if the dropbox isn't configured to accept this report type. 9837 final String dropboxTag = processClass(process) + "_" + eventType; 9838 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 9839 9840 // Check if we should rate limit and abort early if needed. 9841 final DropboxRateLimiter.RateLimitResult rateLimitResult = 9842 mDropboxRateLimiter.shouldRateLimit(eventType, processName); 9843 if (rateLimitResult.shouldRateLimit()) return; 9844 9845 final StringBuilder sb = new StringBuilder(1024); 9846 appendDropBoxProcessHeaders(process, processName, volatileStates, sb); 9847 if (process != null) { 9848 sb.append("Foreground: ") 9849 .append(process.isInterestingToUserLocked() ? "Yes" : "No") 9850 .append("\n"); 9851 if (process.getStartUptime() > 0) { 9852 long runtimeMillis = SystemClock.uptimeMillis() - process.getStartUptime(); 9853 sb.append("Process-Runtime: ").append(runtimeMillis).append("\n"); 9854 } 9855 } 9856 if (eventType.equals("crash")) { 9857 String formattedTime = DROPBOX_TIME_FORMATTER.format( 9858 Instant.now().atZone(ZoneId.systemDefault())); 9859 sb.append("Timestamp: ").append(formattedTime).append("\n"); 9860 } 9861 if (activityShortComponentName != null) { 9862 sb.append("Activity: ").append(activityShortComponentName).append("\n"); 9863 } 9864 if (parentShortComponentName != null) { 9865 if (parentProcess != null && parentProcess.getPid() != process.getPid()) { 9866 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n"); 9867 } 9868 if (!parentShortComponentName.equals(activityShortComponentName)) { 9869 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n"); 9870 } 9871 } 9872 if (subject != null) { 9873 sb.append("Subject: ").append(subject).append("\n"); 9874 } 9875 if (errorId != null) { 9876 sb.append("ErrorId: ").append(errorId.toString()).append("\n"); 9877 } 9878 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 9879 9880 // If device is not using 4KB pages, add the PageSize 9881 long pageSize = Os.sysconf(OsConstants._SC_PAGESIZE); 9882 if (pageSize != 4096) { 9883 sb.append("PageSize: ").append(pageSize).append("\n"); 9884 } 9885 9886 if (Debug.isDebuggerConnected()) { 9887 sb.append("Debugger: Connected\n"); 9888 } 9889 if (crashInfo != null && crashInfo.exceptionHandlerClassName != null 9890 && !crashInfo.exceptionHandlerClassName.isEmpty()) { 9891 sb.append("Crash-Handler: ").append(crashInfo.exceptionHandlerClassName).append("\n"); 9892 } 9893 if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) { 9894 sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n"); 9895 } 9896 if (loadingProgress != null) { 9897 sb.append("Loading-Progress: ").append(loadingProgress.floatValue()).append("\n"); 9898 } 9899 if (incrementalMetrics != null) { 9900 sb.append("Incremental: Yes").append("\n"); 9901 final long millisSinceOldestPendingRead = 9902 incrementalMetrics.getMillisSinceOldestPendingRead(); 9903 if (millisSinceOldestPendingRead > 0) { 9904 sb.append("Millis-Since-Oldest-Pending-Read: ").append( 9905 millisSinceOldestPendingRead).append("\n"); 9906 } 9907 } 9908 sb.append(rateLimitResult.createHeader()); 9909 sb.append("\n"); 9910 9911 // Do the rest in a worker thread to avoid blocking the caller on I/O 9912 // (After this point, we shouldn't access AMS internal data structures.) 9913 // 9914 // If process is null, we are being called from some internal code 9915 // and may be about to die -- run this synchronously. 9916 final boolean runSynchronously = process == null; 9917 Thread worker = new Thread("Error dump: " + dropboxTag) { 9918 @Override 9919 public void run() { 9920 if (report != null) { 9921 sb.append(report); 9922 } 9923 9924 String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 9925 String kerLogSetting = Settings.Global.ERROR_KERNEL_LOG_PREFIX + dropboxTag; 9926 String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag; 9927 int logcatLines = Build.IS_USER 9928 ? 0 9929 : Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0); 9930 int kernelLogLines = Build.IS_USER 9931 ? 0 9932 : Settings.Global.getInt(mContext.getContentResolver(), kerLogSetting, 0); 9933 int dropboxMaxSize = Settings.Global.getInt( 9934 mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE); 9935 9936 if (dataFile != null) { 9937 // Attach the stack traces file to the report so collectors can load them 9938 // by file if they have access. 9939 sb.append(DATA_FILE_PATH_HEADER) 9940 .append(dataFile.getAbsolutePath()).append('\n'); 9941 9942 int maxDataFileSize = dropboxMaxSize 9943 - sb.length() 9944 - logcatLines * RESERVED_BYTES_PER_LOGCAT_LINE 9945 - kernelLogLines * RESERVED_BYTES_PER_LOGCAT_LINE 9946 - DATA_FILE_PATH_FOOTER.length(); 9947 9948 if (maxDataFileSize > 0) { 9949 // Inline dataFile contents if there is room. 9950 try { 9951 sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize, 9952 "\n\n[[TRUNCATED]]\n")); 9953 } catch (IOException e) { 9954 Slog.e(TAG, "Error reading " + dataFile, e); 9955 } 9956 } 9957 // Always append the footer, even there wasn't enough space to inline the 9958 // dataFile contents. 9959 sb.append(DATA_FILE_PATH_FOOTER); 9960 } 9961 9962 if (crashInfo != null && crashInfo.stackTrace != null) { 9963 sb.append(crashInfo.stackTrace); 9964 } 9965 boolean shouldAddLogs = (logcatLines > 0 || kernelLogLines > 0) 9966 && (Flags.collectLogcatOnRunSynchronously() || !runSynchronously); 9967 if (shouldAddLogs) { 9968 sb.append("\n"); 9969 if (logcatLines > 0) { 9970 fetchLogcatBuffers(sb, logcatLines, LOGCAT_TIMEOUT_SEC, 9971 List.of("events", "system", "main", "crash")); 9972 } 9973 if (kernelLogLines > 0) { 9974 fetchLogcatBuffers(sb, kernelLogLines, LOGCAT_TIMEOUT_SEC / 2, 9975 List.of("kernel")); 9976 } 9977 } 9978 9979 dbox.addText(dropboxTag, sb.toString()); 9980 } 9981 }; 9982 9983 if (runSynchronously) { 9984 final int oldMask = StrictMode.allowThreadDiskWritesMask(); 9985 try { 9986 worker.run(); 9987 } finally { 9988 StrictMode.setThreadPolicyMask(oldMask); 9989 } 9990 } else { 9991 worker.start(); 9992 if (process != null && process.mPid == MY_PID && "crash".equals(eventType)) { 9993 // We're actually crashing, let's wait for up to 2 seconds before killing ourselves, 9994 // so the data could be persisted into the dropbox. 9995 try { 9996 worker.join(2000); 9997 } catch (InterruptedException ignored) { 9998 } 9999 } 10000 } 10001 } 10002 10003 @Override getProcessesInErrorState()10004 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 10005 enforceNotIsolatedCaller("getProcessesInErrorState"); 10006 // assume our apps are happy - lazy create the list 10007 final List<ActivityManager.ProcessErrorStateInfo>[] errList = new List[1]; 10008 10009 final int callingUid = Binder.getCallingUid(); 10010 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 10011 callingUid) == PackageManager.PERMISSION_GRANTED; 10012 int userId = UserHandle.getUserId(callingUid); 10013 10014 final boolean hasDumpPermission = ActivityManager.checkUidPermission( 10015 android.Manifest.permission.DUMP, callingUid) == PackageManager.PERMISSION_GRANTED; 10016 10017 synchronized (mProcLock) { 10018 // iterate across all processes 10019 mProcessList.forEachLruProcessesLOSP(false, app -> { 10020 if (!allUsers && app.userId != userId) { 10021 return; 10022 } 10023 if (!hasDumpPermission && app.info.uid != callingUid) { 10024 return; 10025 } 10026 final ProcessErrorStateRecord errState = app.mErrorState; 10027 final boolean crashing = errState.isCrashing(); 10028 final boolean notResponding = errState.isNotResponding(); 10029 if ((app.getThread() != null) && (crashing || notResponding)) { 10030 // This one's in trouble, so we'll generate a report for it 10031 // crashes are higher priority (in case there's a crash *and* an anr) 10032 ActivityManager.ProcessErrorStateInfo report = null; 10033 if (crashing) { 10034 report = errState.getCrashingReport(); 10035 } else if (notResponding) { 10036 report = errState.getNotRespondingReport(); 10037 } 10038 10039 if (report != null) { 10040 if (errList[0] == null) { 10041 errList[0] = new ArrayList<>(1); 10042 } 10043 errList[0].add(report); 10044 } else { 10045 Slog.w(TAG, "Missing app error report, app = " + app.processName + 10046 " crashing = " + crashing + 10047 " notResponding = " + notResponding); 10048 } 10049 } 10050 }); 10051 } 10052 10053 return errList[0]; 10054 } 10055 10056 @Override getRunningAppProcesses()10057 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 10058 enforceNotIsolatedCaller("getRunningAppProcesses"); 10059 10060 final int callingUid = Binder.getCallingUid(); 10061 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 10062 10063 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 10064 callingUid) == PackageManager.PERMISSION_GRANTED; 10065 final int userId = UserHandle.getUserId(callingUid); 10066 final boolean allUids = mAtmInternal.isGetTasksAllowed( 10067 "getRunningAppProcesses", Binder.getCallingPid(), callingUid); 10068 10069 synchronized (mProcLock) { 10070 // Iterate across all processes 10071 return mProcessList.getRunningAppProcessesLOSP(allUsers, userId, allUids, 10072 callingUid, clientTargetSdk); 10073 } 10074 } 10075 10076 @Override getRunningExternalApplications()10077 public List<ApplicationInfo> getRunningExternalApplications() { 10078 enforceNotIsolatedCaller("getRunningExternalApplications"); 10079 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 10080 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 10081 if (runningApps != null && runningApps.size() > 0) { 10082 Set<String> extList = new HashSet<String>(); 10083 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 10084 if (app.pkgList != null) { 10085 for (String pkg : app.pkgList) { 10086 extList.add(pkg); 10087 } 10088 } 10089 } 10090 IPackageManager pm = AppGlobals.getPackageManager(); 10091 for (String pkg : extList) { 10092 try { 10093 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 10094 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 10095 retList.add(info); 10096 } 10097 } catch (RemoteException e) { 10098 } 10099 } 10100 } 10101 return retList; 10102 } 10103 10104 @Override getHistoricalProcessStartReasons( String packageName, int maxNum, int userId)10105 public ParceledListSlice<ApplicationStartInfo> getHistoricalProcessStartReasons( 10106 String packageName, int maxNum, int userId) { 10107 enforceNotIsolatedCaller("getHistoricalProcessStartReasons"); 10108 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10109 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10110 throw new IllegalArgumentException("Unsupported userId"); 10111 } 10112 10113 final int callingPid = Binder.getCallingPid(); 10114 final int callingUid = Binder.getCallingUid(); 10115 mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL, 10116 "getHistoricalProcessStartReasons", null); 10117 10118 final ArrayList<ApplicationStartInfo> results = new ArrayList<ApplicationStartInfo>(); 10119 if (!TextUtils.isEmpty(packageName)) { 10120 final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid, 10121 "getHistoricalProcessStartReasons"); 10122 if (uid != INVALID_UID) { 10123 mProcessList.getAppStartInfoTracker().getStartInfo( 10124 packageName, uid, callingPid, maxNum, results); 10125 } 10126 } else { 10127 // If no package name is given, use the caller's uid as the filter uid. 10128 mProcessList.getAppStartInfoTracker().getStartInfo( 10129 packageName, callingUid, callingPid, maxNum, results); 10130 } 10131 return new ParceledListSlice<ApplicationStartInfo>(results); 10132 } 10133 10134 10135 @Override addApplicationStartInfoCompleteListener( IApplicationStartInfoCompleteListener listener, int userId)10136 public void addApplicationStartInfoCompleteListener( 10137 IApplicationStartInfoCompleteListener listener, int userId) { 10138 enforceNotIsolatedCaller("setApplicationStartInfoCompleteListener"); 10139 10140 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10141 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10142 throw new IllegalArgumentException("Unsupported userId"); 10143 } 10144 10145 final int callingUid = Binder.getCallingUid(); 10146 mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, true, 10147 ALLOW_NON_FULL, "addApplicationStartInfoCompleteListener", null); 10148 10149 mProcessList.getAppStartInfoTracker().addStartInfoCompleteListener(listener, 10150 UserHandle.getUid(userId, UserHandle.getAppId(callingUid))); 10151 } 10152 10153 10154 @Override removeApplicationStartInfoCompleteListener( IApplicationStartInfoCompleteListener listener, int userId)10155 public void removeApplicationStartInfoCompleteListener( 10156 IApplicationStartInfoCompleteListener listener, int userId) { 10157 enforceNotIsolatedCaller("clearApplicationStartInfoCompleteListener"); 10158 10159 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10160 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10161 throw new IllegalArgumentException("Unsupported userId"); 10162 } 10163 10164 final int callingUid = Binder.getCallingUid(); 10165 mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, true, 10166 ALLOW_NON_FULL, "removeApplicationStartInfoCompleteListener", null); 10167 10168 mProcessList.getAppStartInfoTracker().removeStartInfoCompleteListener(listener, 10169 UserHandle.getUid(userId, UserHandle.getAppId(callingUid)), true); 10170 } 10171 10172 @Override addStartInfoTimestamp(int key, long timestampNs, int userId)10173 public void addStartInfoTimestamp(int key, long timestampNs, int userId) { 10174 enforceNotIsolatedCaller("addStartInfoTimestamp"); 10175 10176 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10177 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10178 throw new IllegalArgumentException("Unsupported userId"); 10179 } 10180 10181 final int callingUid = Binder.getCallingUid(); 10182 mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, true, 10183 ALLOW_NON_FULL, "addStartInfoTimestamp", null); 10184 10185 addStartInfoTimestampInternal(key, timestampNs, userId, callingUid); 10186 } 10187 10188 @Override reportStartInfoViewTimestamps(long renderThreadDrawStartTimeNs, long framePresentedTimeNs)10189 public void reportStartInfoViewTimestamps(long renderThreadDrawStartTimeNs, 10190 long framePresentedTimeNs) { 10191 int callingUid = Binder.getCallingUid(); 10192 int userId = UserHandle.getUserId(callingUid); 10193 addStartInfoTimestampInternal( 10194 ApplicationStartInfo.START_TIMESTAMP_INITIAL_RENDERTHREAD_FRAME, 10195 renderThreadDrawStartTimeNs, userId, callingUid); 10196 addStartInfoTimestampInternal( 10197 ApplicationStartInfo.START_TIMESTAMP_SURFACEFLINGER_COMPOSITION_COMPLETE, 10198 framePresentedTimeNs, userId, callingUid); 10199 } 10200 addStartInfoTimestampInternal(int key, long timestampNs, int userId, int uid)10201 private void addStartInfoTimestampInternal(int key, long timestampNs, int userId, int uid) { 10202 mProcessList.getAppStartInfoTracker().addTimestampToStart( 10203 Settings.getPackageNameForUid(mContext, uid), 10204 UserHandle.getUid(userId, UserHandle.getAppId(uid)), 10205 timestampNs, 10206 key); 10207 } 10208 10209 @Override getHistoricalProcessExitReasons( String packageName, int pid, int maxNum, int userId)10210 public ParceledListSlice<ApplicationExitInfo> getHistoricalProcessExitReasons( 10211 String packageName, int pid, int maxNum, int userId) { 10212 enforceNotIsolatedCaller("getHistoricalProcessExitReasons"); 10213 10214 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 10215 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 10216 throw new IllegalArgumentException("Unsupported userId"); 10217 } 10218 10219 final int callingPid = Binder.getCallingPid(); 10220 final int callingUid = Binder.getCallingUid(); 10221 final int callingUserId = UserHandle.getCallingUserId(); 10222 mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL, 10223 "getHistoricalProcessExitReasons", null); 10224 10225 NativeTombstoneManager tombstoneService = LocalServices.getService( 10226 NativeTombstoneManager.class); 10227 10228 final ArrayList<ApplicationExitInfo> results = new ArrayList<ApplicationExitInfo>(); 10229 if (!TextUtils.isEmpty(packageName)) { 10230 final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid, 10231 "getHistoricalProcessExitReasons"); 10232 if (uid != INVALID_UID) { 10233 mProcessList.mAppExitInfoTracker.getExitInfo( 10234 packageName, uid, pid, maxNum, results); 10235 tombstoneService.collectTombstones(results, uid, pid, maxNum); 10236 } 10237 } else { 10238 // If no package name is given, use the caller's uid as the filter uid. 10239 mProcessList.mAppExitInfoTracker.getExitInfo( 10240 packageName, callingUid, pid, maxNum, results); 10241 tombstoneService.collectTombstones(results, callingUid, pid, maxNum); 10242 } 10243 10244 return new ParceledListSlice<ApplicationExitInfo>(results); 10245 } 10246 10247 @Override setProcessStateSummary(@ullable byte[] state)10248 public void setProcessStateSummary(@Nullable byte[] state) { 10249 if (state != null && state.length > MAX_STATE_DATA_SIZE) { 10250 throw new IllegalArgumentException("Data size is too large"); 10251 } 10252 mProcessList.mAppExitInfoTracker.setProcessStateSummary(Binder.getCallingUid(), 10253 Binder.getCallingPid(), state); 10254 } 10255 10256 /** 10257 * Retrieves logs from specified logcat buffers and appends them to a StringBuilder 10258 * in the supplied order. The method executes a logcat command to fetch specific 10259 * log entries from the supplied buffers. 10260 * 10261 * @param sb the StringBuilder to append the logcat output to. 10262 * @param lines the number of lines to retrieve. 10263 * @param timeout the maximum allowed time in seconds for logcat to run before being terminated. 10264 * @param buffers the list of log buffers from which to retrieve logs. 10265 */ fetchLogcatBuffers(StringBuilder sb, int lines, int timeout, List<String> buffers)10266 private static void fetchLogcatBuffers(StringBuilder sb, int lines, 10267 int timeout, List<String> buffers) { 10268 10269 if (buffers.size() == 0 || lines <= 0 || timeout <= 0) { 10270 return; 10271 } 10272 10273 List<String> command = new ArrayList<>(10 + (2 * buffers.size())); 10274 // Time out after 10s of inactivity, but kill logcat with SEGV 10275 // so we can investigate why it didn't finish. 10276 command.add("/system/bin/timeout"); 10277 command.add("-i"); 10278 command.add("-s"); 10279 command.add("SEGV"); 10280 command.add(timeout + "s"); 10281 10282 // Merge several logcat streams, and take the last N lines. 10283 command.add("/system/bin/logcat"); 10284 command.add("-v"); 10285 // This adds a timestamp and thread info to each log line. 10286 // Also change the timestamps to use UTC time. 10287 command.add("threadtime,UTC"); 10288 for (String buffer : buffers) { 10289 command.add("-b"); 10290 command.add(buffer); 10291 } 10292 // Limit the output to the last N lines. 10293 command.add("-t"); 10294 command.add(String.valueOf(lines)); 10295 10296 try { 10297 java.lang.Process proc = 10298 new ProcessBuilder(command).redirectErrorStream(true).start(); 10299 10300 // Close the output stream immediately as we do not send input to the process. 10301 try { 10302 proc.getOutputStream().close(); 10303 } catch (IOException e) { 10304 } 10305 10306 try (InputStreamReader reader = new InputStreamReader(proc.getInputStream())) { 10307 char[] buffer = new char[8192]; 10308 int numRead; 10309 while ((numRead = reader.read(buffer, 0, buffer.length)) > 0) { 10310 sb.append(buffer, 0, numRead); 10311 } 10312 } 10313 } catch (IOException e) { 10314 Slog.e(TAG, "Error running logcat", e); 10315 } 10316 } 10317 10318 /** 10319 * Check if the calling process has the permission to dump given package, 10320 * throw SecurityException if it doesn't have the permission. 10321 * 10322 * @return The real UID of process that can be dumped, or {@link android.os.Process#INVALID_UID} 10323 * if the package is not found. 10324 */ enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, String function)10325 int enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, 10326 String function) { 10327 // Allow SDK sandbox process to dump for its own process (under SDK sandbox package) 10328 try { 10329 if (Process.isSdkSandboxUid(callingUid) 10330 && getPackageManager().getSdkSandboxPackageName().equals(packageName)) { 10331 return callingUid; 10332 } 10333 } catch (RemoteException e) { 10334 Log.e(TAG, "Could not get SDK sandbox package name"); 10335 } 10336 final long identity = Binder.clearCallingIdentity(); 10337 int uid = INVALID_UID; 10338 try { 10339 uid = mPackageManagerInt.getPackageUid(packageName, 10340 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId); 10341 } finally { 10342 Binder.restoreCallingIdentity(identity); 10343 } 10344 // If the uid is Process.INVALID_UID, the below 'if' check will be always true 10345 if (UserHandle.getAppId(uid) != UserHandle.getAppId(callingUid)) { 10346 // Requires the DUMP permission if the target package doesn't belong 10347 // to the caller or it doesn't exist. 10348 enforceCallingPermission(android.Manifest.permission.DUMP, function); 10349 } 10350 return uid; 10351 } 10352 10353 @Override getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)10354 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) { 10355 if (outState == null) { 10356 throw new IllegalArgumentException("outState is null"); 10357 } 10358 enforceNotIsolatedCaller("getMyMemoryState"); 10359 10360 final int callingUid = Binder.getCallingUid(); 10361 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 10362 10363 synchronized (mProcLock) { 10364 ProcessRecord proc; 10365 synchronized (mPidsSelfLocked) { 10366 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 10367 } 10368 if (proc != null) { 10369 mProcessList.fillInProcMemInfoLOSP(proc, outState, clientTargetSdk); 10370 } 10371 } 10372 } 10373 10374 @Override getMemoryTrimLevel()10375 public @MemFactor int getMemoryTrimLevel() { 10376 enforceNotIsolatedCaller("getMyMemoryState"); 10377 synchronized (this) { 10378 return mAppProfiler.getLastMemoryLevelLocked(); 10379 } 10380 } 10381 setMemFactorOverride(@emFactor int level)10382 void setMemFactorOverride(@MemFactor int level) { 10383 synchronized (this) { 10384 if (level == mAppProfiler.getLastMemoryLevelLocked()) { 10385 return; 10386 } 10387 10388 mAppProfiler.setMemFactorOverrideLocked(level); 10389 // Kick off an oom adj update since we forced a mem factor update. 10390 updateOomAdjLocked(OOM_ADJ_REASON_SHELL); 10391 } 10392 } 10393 10394 /** 10395 * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}. 10396 */ setServiceRestartBackoffEnabled(@onNull String packageName, boolean enable, @NonNull String reason)10397 void setServiceRestartBackoffEnabled(@NonNull String packageName, boolean enable, 10398 @NonNull String reason) { 10399 synchronized (this) { 10400 mServices.setServiceRestartBackoffEnabledLocked(packageName, enable, reason); 10401 } 10402 } 10403 10404 /** 10405 * @return {@code false} if the given package has been disable from enforcing the service 10406 * restart backoff policy, used by {@link ActivityManagerShellCommand}. 10407 */ isServiceRestartBackoffEnabled(@onNull String packageName)10408 boolean isServiceRestartBackoffEnabled(@NonNull String packageName) { 10409 synchronized (this) { 10410 return mServices.isServiceRestartBackoffEnabledLocked(packageName); 10411 } 10412 } 10413 10414 @Override onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)10415 public void onShellCommand(FileDescriptor in, FileDescriptor out, 10416 FileDescriptor err, String[] args, ShellCallback callback, 10417 ResultReceiver resultReceiver) { 10418 (new ActivityManagerShellCommand(this, false)).exec( 10419 this, in, out, err, args, callback, resultReceiver); 10420 } 10421 10422 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)10423 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 10424 PriorityDump.dump(mPriorityDumper, fd, pw, args); 10425 } 10426 10427 private static final String TICK = 10428 "---------------------------------------" 10429 + "----------------------------------------"; 10430 dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, int displayIdFilter, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies)10431 private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, 10432 boolean dumpAll, String dumpPackage, int displayIdFilter, boolean dumpClient, 10433 boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies) { 10434 10435 ActiveServices.ServiceDumper sdumper; 10436 10437 synchronized(this) { 10438 mConstants.dump(pw); 10439 mOomAdjuster.dumpCachedAppOptimizerSettings(pw); 10440 mOomAdjuster.dumpCacheOomRankerSettings(pw); 10441 pw.println(); 10442 if (dumpAll) { 10443 pw.println( 10444 "-------------------------------------------------------------------------------"); 10445 } 10446 dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10447 pw.println(); 10448 if (dumpAll) { 10449 pw.println( 10450 "-------------------------------------------------------------------------------"); 10451 } 10452 mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage); 10453 pw.println(); 10454 if (dumpAll) { 10455 pw.println( 10456 "-------------------------------------------------------------------------------"); 10457 } 10458 mBroadcastController.dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10459 pw.println(); 10460 if (dumpAll) { 10461 pw.println( 10462 "-------------------------------------------------------------------------------"); 10463 } 10464 if (dumpAll || dumpPackage != null) { 10465 mBroadcastController.dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, 10466 dumpPackage); 10467 pw.println(); 10468 if (dumpAll) { 10469 pw.println( 10470 "-------------------------------------------------------------------------------"); 10471 } 10472 } 10473 mCpHelper.dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10474 pw.println(); 10475 if (dumpAll) { 10476 pw.println( 10477 "-------------------------------------------------------------------------------"); 10478 } 10479 dumpPermissions(fd, pw, args, opti, dumpAll, dumpPackage); 10480 pw.println(); 10481 sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage); 10482 if (!dumpClient) { 10483 if (dumpAll) { 10484 pw.println( 10485 "-------------------------------------------------------------------------------"); 10486 } 10487 sdumper.dumpLocked(); 10488 } 10489 } 10490 10491 // No need to hold the lock. 10492 pw.println(TICK); 10493 AnrTimer.dump(pw, false); 10494 10495 // We drop the lock here because we can't call dumpWithClient() with the lock held; 10496 // if the caller wants a consistent state for the !dumpClient case, it can call this 10497 // method with the lock held. 10498 if (dumpClient) { 10499 if (dumpAll) { 10500 pw.println( 10501 "-------------------------------------------------------------------------------"); 10502 } 10503 sdumper.dumpWithClient(); 10504 } 10505 if (dumpPackage == null && dumpProxies) { 10506 // Intentionally dropping the lock for this, because dumpBinderProxies() will make many 10507 // outgoing binder calls to retrieve interface descriptors; while that is system code, 10508 // there is nothing preventing an app from overriding this implementation by talking to 10509 // the binder driver directly, and hang up system_server in the process. So, dump 10510 // without locks held, and even then only when there is an unreasonably large number of 10511 // proxies in the first place. 10512 pw.println(); 10513 if (dumpAll) { 10514 pw.println( 10515 "-------------------------------------------------------------------------------"); 10516 } 10517 dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */); 10518 } 10519 synchronized(this) { 10520 pw.println(); 10521 if (dumpAll) { 10522 pw.println( 10523 "-------------------------------------------------------------------------------"); 10524 } 10525 mAtmInternal.dump(DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10526 dumpPackage, displayIdFilter); 10527 pw.println(); 10528 if (dumpAll) { 10529 pw.println( 10530 "-------------------------------------------------------------------------------"); 10531 } 10532 mAtmInternal.dump(DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10533 dumpPackage, displayIdFilter); 10534 pw.println(); 10535 if (dumpAll) { 10536 pw.println( 10537 "-------------------------------------------------------------------------------"); 10538 } 10539 mAtmInternal.dump(DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10540 dumpPackage, displayIdFilter); 10541 if (dumpPackage == null) { 10542 pw.println(); 10543 if (dumpAll) { 10544 pw.println( 10545 "-------------------------------------------------------------------------------"); 10546 } 10547 mAtmInternal.dump(DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10548 dumpPackage, displayIdFilter); 10549 } 10550 // Activities section is dumped as part of the Critical priority dump. Exclude the 10551 // section if priority is Normal. 10552 if (!dumpNormalPriority) { 10553 pw.println(); 10554 if (dumpAll) { 10555 pw.println( 10556 "-------------------------------------------------------------------------------"); 10557 } 10558 mAtmInternal.dump(DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, 10559 dumpPackage, displayIdFilter); 10560 } 10561 if (mAssociations.size() > 0) { 10562 pw.println(); 10563 if (dumpAll) { 10564 pw.println( 10565 "-------------------------------------------------------------------------------"); 10566 } 10567 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 10568 } 10569 pw.println(); 10570 if (dumpAll) { 10571 pw.println( 10572 "-------------------------------------------------------------------------------"); 10573 mProcessList.getAppStartInfoTracker().dumpHistoryProcessStartInfo(pw, dumpPackage); 10574 pw.println( 10575 "-------------------------------------------------------------------------------"); 10576 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage); 10577 } 10578 if (dumpPackage == null) { 10579 pw.println(); 10580 if (dumpAll) { 10581 pw.println( 10582 "-------------------------------------------------------------------------------"); 10583 } 10584 dumpLmkLocked(pw); 10585 } 10586 pw.println(); 10587 if (dumpAll) { 10588 pw.println( 10589 "-------------------------------------------------------------------------------"); 10590 } 10591 synchronized (mProcLock) { 10592 mProcessList.dumpProcessesLSP(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId); 10593 } 10594 pw.println(); 10595 if (dumpAll) { 10596 pw.println( 10597 "-------------------------------------------------------------------------------"); 10598 } 10599 dumpUsers(pw); 10600 10601 pw.println(); 10602 if (dumpAll) { 10603 pw.println( 10604 "-------------------------------------------------------------------------------"); 10605 } 10606 mComponentAliasResolver.dump(pw); 10607 } 10608 } 10609 10610 /** 10611 * Dump the app restriction controller, it's required not to hold the global lock here. 10612 */ dumpAppRestrictionController(PrintWriter pw)10613 private void dumpAppRestrictionController(PrintWriter pw) { 10614 pw.println( 10615 "-------------------------------------------------------------------------------"); 10616 mAppRestrictionController.dump(pw, ""); 10617 } 10618 dumpAppRestrictionController(ProtoOutputStream proto, int uid)10619 void dumpAppRestrictionController(ProtoOutputStream proto, int uid) { 10620 mAppRestrictionController.dumpAsProto(proto, uid); 10621 } 10622 10623 /** 10624 * Wrapper function to print out debug data filtered by specified arguments. 10625 */ 10626 @NeverCompile // Avoid size overhead of debugging code. doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)10627 private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) { 10628 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 10629 10630 boolean dumpAll = false; 10631 boolean dumpClient = false; 10632 boolean dumpCheckin = false; 10633 boolean dumpCheckinFormat = false; 10634 boolean dumpNormalPriority = false; 10635 boolean dumpVisibleStacksOnly = false; 10636 boolean dumpFocusedStackOnly = false; 10637 int dumpDisplayId = INVALID_DISPLAY; 10638 String dumpPackage = null; 10639 int dumpUserId = UserHandle.USER_ALL; 10640 10641 int opti = 0; 10642 while (opti < args.length) { 10643 String opt = args[opti]; 10644 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 10645 break; 10646 } 10647 opti++; 10648 if ("-a".equals(opt)) { 10649 dumpAll = true; 10650 } else if ("-c".equals(opt)) { 10651 dumpClient = true; 10652 } else if ("-v".equals(opt)) { 10653 dumpVisibleStacksOnly = true; 10654 } else if ("-f".equals(opt)) { 10655 dumpFocusedStackOnly = true; 10656 } else if ("-p".equals(opt)) { 10657 if (opti < args.length) { 10658 dumpPackage = args[opti]; 10659 opti++; 10660 } else { 10661 pw.println("Error: -p option requires package argument"); 10662 return; 10663 } 10664 dumpClient = true; 10665 } else if ("--checkin".equals(opt)) { 10666 dumpCheckin = dumpCheckinFormat = true; 10667 } else if ("-C".equals(opt)) { 10668 dumpCheckinFormat = true; 10669 } else if ("--normal-priority".equals(opt)) { 10670 dumpNormalPriority = true; 10671 } else if ("--user".equals(opt)) { 10672 if (opti < args.length) { 10673 dumpUserId = UserHandle.parseUserArg(args[opti]); 10674 if (dumpUserId == UserHandle.USER_CURRENT) { 10675 dumpUserId = mUserController.getCurrentUserId(); 10676 } 10677 opti++; 10678 } else { 10679 pw.println("Error: --user option requires user id argument"); 10680 return; 10681 } 10682 } else if ("-d".equals(opt)) { 10683 if (opti < args.length) { 10684 dumpDisplayId = Integer.parseInt(args[opti]); 10685 if (dumpDisplayId == INVALID_DISPLAY) { 10686 pw.println("Error: -d cannot be used with INVALID_DISPLAY"); 10687 return; 10688 } 10689 opti++; 10690 } else { 10691 pw.println("Error: -d option requires display argument"); 10692 return; 10693 } 10694 dumpClient = true; 10695 } else if ("-h".equals(opt)) { 10696 ActivityManagerShellCommand.dumpHelp(pw, true); 10697 return; 10698 } else { 10699 pw.println("Unknown argument: " + opt + "; use -h for help"); 10700 return; 10701 } 10702 } 10703 10704 final long origId = Binder.clearCallingIdentity(); 10705 10706 if (useProto) { 10707 final ProtoOutputStream proto = new ProtoOutputStream(fd); 10708 String cmd = opti < args.length ? args[opti] : ""; 10709 opti++; 10710 10711 if ("activities".equals(cmd) || "a".equals(cmd)) { 10712 // output proto is ActivityManagerServiceDumpActivitiesProto 10713 mAtmInternal.writeActivitiesToProto(proto); 10714 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 10715 // output proto is ActivityManagerServiceDumpBroadcastsProto 10716 synchronized (this) { 10717 mBroadcastController.writeBroadcastsToProtoLocked(proto); 10718 } 10719 } else if ("provider".equals(cmd)) { 10720 String[] newArgs; 10721 String name; 10722 if (opti >= args.length) { 10723 name = null; 10724 newArgs = EMPTY_STRING_ARRAY; 10725 } else { 10726 name = args[opti]; 10727 opti++; 10728 newArgs = new String[args.length - opti]; 10729 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10730 args.length - opti); 10731 } 10732 if (!mCpHelper.dumpProviderProto(fd, pw, name, newArgs)) { 10733 pw.println("No providers match: " + name); 10734 pw.println("Use -h for help."); 10735 } 10736 } else if ("service".equals(cmd)) { 10737 // output proto is ActivityManagerServiceDumpServicesProto 10738 mServices.dumpDebug(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 10739 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 10740 if (opti < args.length) { 10741 dumpPackage = args[opti]; 10742 opti++; 10743 } 10744 // output proto is ProcessProto 10745 synchronized (this) { 10746 synchronized (mProcLock) { 10747 mProcessList.writeProcessesToProtoLSP(proto, dumpPackage); 10748 } 10749 } 10750 } else if ("app-restrictions".equals(cmd)) { 10751 int uid = Process.INVALID_UID; 10752 boolean error = false; 10753 for (int i = 0; i < args.length; i++) { 10754 if ("--uid".equals(args[i])) { 10755 if (i + 1 < args.length) { 10756 try { 10757 uid = Integer.parseInt(args[i + 1]); 10758 } catch (NumberFormatException e) { 10759 error = true; 10760 } 10761 } else { 10762 error = true; 10763 } 10764 break; 10765 } 10766 } 10767 if (error) { 10768 pw.println("Invalid --uid argument"); 10769 pw.println("Use -h for help."); 10770 } else { 10771 dumpAppRestrictionController(proto, uid); 10772 } 10773 } else { 10774 // default option, dump everything, output is ActivityManagerServiceProto 10775 synchronized (this) { 10776 long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES); 10777 mAtmInternal.writeActivitiesToProto(proto); 10778 proto.end(activityToken); 10779 10780 long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS); 10781 mBroadcastController.writeBroadcastsToProtoLocked(proto); 10782 proto.end(broadcastToken); 10783 10784 long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES); 10785 mServices.dumpDebug(proto, 10786 ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 10787 proto.end(serviceToken); 10788 10789 long processToken = proto.start(ActivityManagerServiceProto.PROCESSES); 10790 synchronized (mProcLock) { 10791 mProcessList.writeProcessesToProtoLSP(proto, dumpPackage); 10792 } 10793 proto.end(processToken); 10794 } 10795 } 10796 proto.flush(); 10797 Binder.restoreCallingIdentity(origId); 10798 return; 10799 } 10800 10801 int dumpAppId = getAppId(dumpPackage); 10802 boolean more = false; 10803 // Is the caller requesting to dump a particular piece of data? 10804 if (opti < args.length) { 10805 String cmd = args[opti]; 10806 opti++; 10807 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd) 10808 || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd) 10809 || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd) 10810 || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd) 10811 || DUMP_TOP_RESUMED_ACTIVITY.equals(cmd) 10812 || DUMP_VISIBLE_ACTIVITIES.equals(cmd)) { 10813 mAtmInternal.dump(cmd, fd, pw, args, opti, /* dumpAll= */ true, dumpClient, 10814 dumpPackage, dumpDisplayId); 10815 } else if ("binder-proxies".equals(cmd)) { 10816 if (opti >= args.length) { 10817 dumpBinderProxies(pw, 0 /* minToDump */); 10818 } else { 10819 String uid = args[opti]; 10820 opti++; 10821 // Ensure Binder Proxy Count is as up to date as possible 10822 System.gc(); 10823 System.runFinalization(); 10824 System.gc(); 10825 pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid))); 10826 } 10827 } else if ("allowed-associations".equals(cmd)) { 10828 if (opti < args.length) { 10829 dumpPackage = args[opti]; 10830 opti++; 10831 } 10832 synchronized (this) { 10833 dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage); 10834 } 10835 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 10836 if (opti < args.length) { 10837 dumpPackage = args[opti]; 10838 opti++; 10839 } 10840 synchronized (this) { 10841 // TODO: b/361161826 - Always pass in the dumpAll and let 10842 // BroadcastController decide how to treat it. 10843 final boolean requestDumpAll = "filter".equals(dumpPackage) 10844 ? dumpAll : true; 10845 mBroadcastController.dumpBroadcastsLocked(fd, pw, args, opti, 10846 requestDumpAll, dumpPackage); 10847 } 10848 } else if ("broadcast-stats".equals(cmd)) { 10849 if (opti < args.length) { 10850 dumpPackage = args[opti]; 10851 opti++; 10852 } 10853 synchronized (this) { 10854 if (dumpCheckinFormat) { 10855 mBroadcastController.dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, 10856 dumpCheckin, dumpPackage); 10857 } else { 10858 mBroadcastController.dumpBroadcastStatsLocked(fd, pw, args, opti, true, 10859 dumpPackage); 10860 } 10861 } 10862 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 10863 if (opti < args.length) { 10864 dumpPackage = args[opti]; 10865 opti++; 10866 } 10867 mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage); 10868 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 10869 if (opti < args.length) { 10870 dumpPackage = args[opti]; 10871 opti++; 10872 } 10873 synchronized (this) { 10874 synchronized (mProcLock) { 10875 mProcessList.dumpProcessesLSP( 10876 fd, pw, args, opti, true, dumpPackage, dumpAppId); 10877 } 10878 } 10879 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 10880 synchronized (this) { 10881 mProcessList.dumpOomLocked(fd, pw, false, args, opti, true, dumpPackage, true); 10882 } 10883 } else if ("lmk".equals(cmd)) { 10884 synchronized (this) { 10885 dumpLmkLocked(pw); 10886 } 10887 } else if ("lru".equals(cmd)) { 10888 synchronized (this) { 10889 mProcessList.dumpLruLocked(pw, dumpPackage, null); 10890 } 10891 } else if ("permissions".equals(cmd) || "perm".equals(cmd)) { 10892 dumpPermissions(fd, pw, args, opti, true, dumpPackage); 10893 } else if ("provider".equals(cmd)) { 10894 String[] newArgs; 10895 String name; 10896 if (opti >= args.length) { 10897 name = null; 10898 newArgs = EMPTY_STRING_ARRAY; 10899 } else { 10900 name = args[opti]; 10901 opti++; 10902 newArgs = new String[args.length - opti]; 10903 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10904 args.length - opti); 10905 } 10906 if (!mCpHelper.dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 10907 pw.println("No providers match: " + name); 10908 pw.println("Use -h for help."); 10909 } 10910 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 10911 synchronized (this) { 10912 mCpHelper.dumpProvidersLocked(fd, pw, args, opti, true, dumpPackage); 10913 } 10914 } else if ("service".equals(cmd)) { 10915 String[] newArgs; 10916 String name; 10917 if (opti >= args.length) { 10918 name = null; 10919 newArgs = EMPTY_STRING_ARRAY; 10920 } else { 10921 name = args[opti]; 10922 opti++; 10923 newArgs = new String[args.length - opti]; 10924 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10925 args.length - opti); 10926 } 10927 int[] users = dumpUserId == UserHandle.USER_ALL ? null : new int[]{dumpUserId}; 10928 if (!mServices.dumpService(fd, pw, name, users, newArgs, 0, dumpAll)) { 10929 pw.println("No services match: " + name); 10930 pw.println("Use -h for help."); 10931 } 10932 } else if ("package".equals(cmd)) { 10933 String[] newArgs; 10934 if (opti >= args.length) { 10935 pw.println("package: no package name specified"); 10936 pw.println("Use -h for help."); 10937 } else { 10938 dumpPackage = args[opti]; 10939 opti++; 10940 newArgs = new String[args.length - opti]; 10941 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 10942 args.length - opti); 10943 args = newArgs; 10944 opti = 0; 10945 more = true; 10946 } 10947 } else if ("associations".equals(cmd) || "as".equals(cmd)) { 10948 synchronized (this) { 10949 dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage); 10950 } 10951 } else if ("settings".equals(cmd)) { 10952 synchronized (this) { 10953 mConstants.dump(pw); 10954 } 10955 synchronized (mProcLock) { 10956 mOomAdjuster.dumpCacheOomRankerSettings(pw); 10957 } 10958 } else if ("cao".equals(cmd)) { 10959 mOomAdjuster.dumpCachedAppOptimizerSettings(pw); 10960 } else if ("timers".equals(cmd)) { 10961 AnrTimer.dump(pw, true); 10962 } else if ("services".equals(cmd) || "s".equals(cmd)) { 10963 if (dumpClient) { 10964 ActiveServices.ServiceDumper dumper; 10965 synchronized (this) { 10966 dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true, 10967 dumpPackage); 10968 } 10969 dumper.dumpWithClient(); 10970 } else { 10971 synchronized (this) { 10972 mServices.newServiceDumperLocked(fd, pw, args, opti, true, 10973 dumpPackage).dumpLocked(); 10974 } 10975 } 10976 } else if ("locks".equals(cmd)) { 10977 LockGuard.dump(fd, pw, args); 10978 } else if ("users".equals(cmd)) { 10979 dumpUsers(pw); 10980 } else if ("start-info".equals(cmd)) { 10981 if (opti < args.length) { 10982 dumpPackage = args[opti]; 10983 opti++; 10984 } 10985 mProcessList.getAppStartInfoTracker().dumpHistoryProcessStartInfo(pw, dumpPackage); 10986 } else if ("exit-info".equals(cmd)) { 10987 if (opti < args.length) { 10988 dumpPackage = args[opti]; 10989 opti++; 10990 } 10991 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage); 10992 } else if ("component-alias".equals(cmd)) { 10993 mComponentAliasResolver.dump(pw); 10994 } else { 10995 // Dumping a single activity? 10996 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll, 10997 dumpVisibleStacksOnly, dumpFocusedStackOnly, dumpDisplayId, dumpUserId)) { 10998 ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true); 10999 int res = shell.exec(this, null, fd, null, args, null, 11000 new ResultReceiver(null)); 11001 if (res < 0) { 11002 pw.println("Bad activity command, or no activities match: " + cmd); 11003 pw.println("Use -h for help."); 11004 } 11005 } 11006 } 11007 if (!more) { 11008 Binder.restoreCallingIdentity(origId); 11009 return; 11010 } 11011 } 11012 11013 // No piece of data specified, dump everything. 11014 if (dumpCheckinFormat) { 11015 mBroadcastController.dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, 11016 dumpPackage); 11017 } else { 11018 if (dumpClient) { 11019 // dumpEverything() will take the lock when needed, and momentarily drop 11020 // it for dumping client state. 11021 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpDisplayId, 11022 dumpClient, dumpNormalPriority, dumpAppId, /* dumpProxies= */ true); 11023 } else { 11024 // Take the lock here, so we get a consistent state for the entire dump; 11025 // dumpEverything() will take the lock as well, which is fine for everything 11026 // except dumping proxies, which can take a long time; exclude them. 11027 synchronized(this) { 11028 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpDisplayId, 11029 dumpClient, dumpNormalPriority, dumpAppId, /* dumpProxies= */ false); 11030 } 11031 } 11032 if (dumpAll) { 11033 dumpAppRestrictionController(pw); 11034 } 11035 } 11036 Binder.restoreCallingIdentity(origId); 11037 } 11038 dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)11039 void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11040 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 11041 pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)"); 11042 11043 int dumpUid = 0; 11044 if (dumpPackage != null) { 11045 IPackageManager pm = AppGlobals.getPackageManager(); 11046 try { 11047 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0); 11048 } catch (RemoteException e) { 11049 } 11050 } 11051 11052 boolean printedAnything = false; 11053 11054 final long now = SystemClock.uptimeMillis(); 11055 11056 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 11057 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 11058 = mAssociations.valueAt(i1); 11059 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 11060 SparseArray<ArrayMap<String, Association>> sourceUids 11061 = targetComponents.valueAt(i2); 11062 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) { 11063 ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3); 11064 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 11065 Association ass = sourceProcesses.valueAt(i4); 11066 if (dumpPackage != null) { 11067 if (!ass.mTargetComponent.getPackageName().equals(dumpPackage) 11068 && UserHandle.getAppId(ass.mSourceUid) != dumpUid) { 11069 continue; 11070 } 11071 } 11072 printedAnything = true; 11073 pw.print(" "); 11074 pw.print(ass.mTargetProcess); 11075 pw.print("/"); 11076 UserHandle.formatUid(pw, ass.mTargetUid); 11077 pw.print(" <- "); 11078 pw.print(ass.mSourceProcess); 11079 pw.print("/"); 11080 UserHandle.formatUid(pw, ass.mSourceUid); 11081 pw.println(); 11082 pw.print(" via "); 11083 pw.print(ass.mTargetComponent.flattenToShortString()); 11084 pw.println(); 11085 pw.print(" "); 11086 long dur = ass.mTime; 11087 if (ass.mNesting > 0) { 11088 dur += now - ass.mStartTime; 11089 } 11090 TimeUtils.formatDuration(dur, pw); 11091 pw.print(" ("); 11092 pw.print(ass.mCount); 11093 pw.print(" times)"); 11094 pw.print(" "); 11095 for (int i=0; i<ass.mStateTimes.length; i++) { 11096 long amt = ass.mStateTimes[i]; 11097 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 11098 amt += now - ass.mLastStateUptime; 11099 } 11100 if (amt != 0) { 11101 pw.print(" "); 11102 pw.print(ProcessList.makeProcStateString( 11103 i + ActivityManager.MIN_PROCESS_STATE)); 11104 pw.print("="); 11105 TimeUtils.formatDuration(amt, pw); 11106 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 11107 pw.print("*"); 11108 } 11109 } 11110 } 11111 pw.println(); 11112 if (ass.mNesting > 0) { 11113 pw.print(" Currently active: "); 11114 TimeUtils.formatDuration(now - ass.mStartTime, pw); 11115 pw.println(); 11116 } 11117 } 11118 } 11119 } 11120 11121 } 11122 11123 if (!printedAnything) { 11124 pw.println(" (nothing)"); 11125 } 11126 } 11127 getAppId(String dumpPackage)11128 int getAppId(String dumpPackage) { 11129 if (dumpPackage != null) { 11130 try { 11131 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 11132 dumpPackage, 0); 11133 return UserHandle.getAppId(info.uid); 11134 } catch (NameNotFoundException e) { 11135 e.printStackTrace(); 11136 } 11137 } 11138 return -1; 11139 } 11140 dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)11141 void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) { 11142 final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50); 11143 11144 pw.println(header); 11145 for (int i = 0; i < proxyCounts.length; i++) { 11146 pw.println(" #" + (i + 1) + ": " + proxyCounts[i]); 11147 } 11148 } 11149 dumpBinderProxiesCounts(PrintWriter pw, String header)11150 boolean dumpBinderProxiesCounts(PrintWriter pw, String header) { 11151 SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts(); 11152 if(counts != null) { 11153 pw.println(header); 11154 for (int i = 0; i < counts.size(); i++) { 11155 final int uid = counts.keyAt(i); 11156 final int binderCount = counts.valueAt(i); 11157 pw.print(" UID "); 11158 pw.print(uid); 11159 pw.print(", binder count = "); 11160 pw.print(binderCount); 11161 pw.print(", package(s)= "); 11162 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid); 11163 if (pkgNames != null) { 11164 for (int j = 0; j < pkgNames.length; j++) { 11165 pw.print(pkgNames[j]); 11166 pw.print("; "); 11167 } 11168 } else { 11169 pw.print("NO PACKAGE NAME FOUND"); 11170 } 11171 pw.println(); 11172 } 11173 return true; 11174 } 11175 return false; 11176 } 11177 dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)11178 void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) { 11179 pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)"); 11180 final int proxyCount = BinderProxy.getProxyCount(); 11181 if (proxyCount >= minCountToDumpInterfaces) { 11182 dumpBinderProxyInterfaceCounts(pw, 11183 "Top proxy interface names held by SYSTEM"); 11184 } else { 11185 pw.print("Not dumping proxy interface counts because size (" 11186 + Integer.toString(proxyCount) + ") looks reasonable"); 11187 pw.println(); 11188 } 11189 dumpBinderProxiesCounts(pw, 11190 " Counts of Binder Proxies held by SYSTEM"); 11191 } 11192 11193 @GuardedBy("this") dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep)11194 boolean dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep) { 11195 final int size = mActiveInstrumentation.size(); 11196 if (size > 0) { 11197 boolean printed = false; 11198 for (int i = 0; i < size; i++) { 11199 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 11200 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 11201 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 11202 continue; 11203 } 11204 if (!printed) { 11205 if (needSep) { 11206 pw.println(); 11207 } 11208 pw.println(" Active instrumentation:"); 11209 printed = true; 11210 needSep = true; 11211 } 11212 pw.print(" Instrumentation #"); pw.print(i); pw.print(": "); 11213 pw.println(ai); 11214 ai.dump(pw, " "); 11215 } 11216 } 11217 return needSep; 11218 } 11219 11220 @NeverCompile // Avoid size overhead of debugging code. 11221 @GuardedBy({"this", "mProcLock"}) dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep)11222 void dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, 11223 boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep) { 11224 if (dumpAll || dumpPackage != null) { 11225 final SparseArray<ProcessRecord> pidToProcess = new SparseArray<>(); 11226 synchronized (mPidsSelfLocked) { 11227 boolean printed = false; 11228 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 11229 ProcessRecord r = mPidsSelfLocked.valueAt(i); 11230 pidToProcess.put(r.getPid(), r); 11231 if (dumpPackage != null && !r.getPkgList().containsKey(dumpPackage)) { 11232 continue; 11233 } 11234 if (!printed) { 11235 if (needSep) pw.println(); 11236 needSep = true; 11237 pw.println(" PID mappings:"); 11238 printed = true; 11239 } 11240 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 11241 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 11242 } 11243 } 11244 11245 synchronized (sActiveProcessInfoSelfLocked) { 11246 boolean printed = false; 11247 for (int i = 0, size = sActiveProcessInfoSelfLocked.size(); i < size; i++) { 11248 ProcessInfo info = sActiveProcessInfoSelfLocked.valueAt(i); 11249 ProcessRecord r = pidToProcess.get(sActiveProcessInfoSelfLocked.keyAt(i)); 11250 if (r != null && dumpPackage != null 11251 && !r.getPkgList().containsKey(dumpPackage)) { 11252 continue; 11253 } 11254 if (!printed) { 11255 if (needSep) pw.println(); 11256 needSep = true; 11257 pw.println(" Active process infos:"); 11258 printed = true; 11259 } 11260 pw.print(" Pinfo PID #"); pw.print(sActiveProcessInfoSelfLocked.keyAt(i)); 11261 pw.println(":"); 11262 pw.print(" name="); pw.println(info.name); 11263 if (info.deniedPermissions != null) { 11264 for (int j = 0; j < info.deniedPermissions.size(); j++) { 11265 pw.print(" deny: "); 11266 pw.println(info.deniedPermissions.valueAt(j)); 11267 } 11268 } 11269 } 11270 } 11271 } 11272 11273 if (dumpAll) { 11274 mPhantomProcessList.dump(pw, " "); 11275 } 11276 11277 if (mImportantProcesses.size() > 0) { 11278 synchronized (mPidsSelfLocked) { 11279 boolean printed = false; 11280 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) { 11281 ProcessRecord r = mPidsSelfLocked.get(mImportantProcesses.valueAt(i).pid); 11282 if (dumpPackage != null && (r == null 11283 || !r.getPkgList().containsKey(dumpPackage))) { 11284 continue; 11285 } 11286 if (!printed) { 11287 if (needSep) pw.println(); 11288 needSep = true; 11289 pw.println(" Foreground Processes:"); 11290 printed = true; 11291 } 11292 pw.print(" PID #"); pw.print(mImportantProcesses.keyAt(i)); 11293 pw.print(": "); pw.println(mImportantProcesses.valueAt(i)); 11294 } 11295 } 11296 } 11297 11298 if (mPersistentStartingProcesses.size() > 0) { 11299 if (needSep) pw.println(); 11300 needSep = true; 11301 pw.println(" Persisent processes that are starting:"); 11302 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 11303 "Starting Norm", "Restarting PERS", dumpPackage); 11304 } 11305 11306 if (mProcessList.mRemovedProcesses.size() > 0) { 11307 if (needSep) pw.println(); 11308 needSep = true; 11309 pw.println(" Processes that are being removed:"); 11310 dumpProcessList(pw, this, mProcessList.mRemovedProcesses, " ", 11311 "Removed Norm", "Removed PERS", dumpPackage); 11312 } 11313 11314 if (mProcessesOnHold.size() > 0) { 11315 if (needSep) pw.println(); 11316 needSep = true; 11317 pw.println(" Processes that are on old until the system is ready:"); 11318 dumpProcessList(pw, this, mProcessesOnHold, " ", 11319 "OnHold Norm", "OnHold PERS", dumpPackage); 11320 } 11321 11322 needSep = mAppErrors.dumpLPr(fd, pw, needSep, dumpPackage); 11323 11324 needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep, 11325 mAppProfiler.getTestPssMode(), mWakefulness.get()); 11326 11327 if (dumpAll && mProcessList.mPendingStarts.size() > 0) { 11328 if (needSep) pw.println(); 11329 needSep = true; 11330 pw.println(" mPendingStarts: "); 11331 for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) { 11332 pw.println(" " + mProcessList.mPendingStarts.keyAt(i) + ": " 11333 + mProcessList.mPendingStarts.valueAt(i)); 11334 } 11335 } 11336 if (dumpAll) { 11337 mUidObserverController.dump(pw, dumpPackage); 11338 11339 pw.println(" mDeviceIdleAllowlist=" + Arrays.toString(mDeviceIdleAllowlist)); 11340 pw.println(" mDeviceIdleExceptIdleAllowlist=" 11341 + Arrays.toString(mDeviceIdleExceptIdleAllowlist)); 11342 pw.println(" mDeviceIdleTempAllowlist=" + Arrays.toString(mDeviceIdleTempAllowlist)); 11343 if (mPendingTempAllowlist.size() > 0) { 11344 pw.println(" mPendingTempAllowlist:"); 11345 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) { 11346 PendingTempAllowlist ptw = mPendingTempAllowlist.valueAt(i); 11347 pw.print(" "); 11348 UserHandle.formatUid(pw, ptw.targetUid); 11349 pw.print(": "); 11350 TimeUtils.formatDuration(ptw.duration, pw); 11351 pw.print(" "); 11352 pw.println(ptw.tag); 11353 pw.print(" "); 11354 pw.print(ptw.type); 11355 pw.print(" "); 11356 pw.print(ptw.reasonCode); 11357 pw.print(" "); 11358 pw.print(ptw.callingUid); 11359 } 11360 } 11361 pw.println(" mFgsStartTempAllowList:"); 11362 final long currentTimeNow = System.currentTimeMillis(); 11363 final long tempAllowlistCurrentTime = 11364 com.android.server.deviceidle.Flags.useCpuTimeForTempAllowlist() 11365 ? SystemClock.uptimeMillis() : SystemClock.elapsedRealtime(); 11366 mFgsStartTempAllowList.forEach((uid, entry) -> { 11367 pw.print(" " + UserHandle.formatUid(uid) + ": "); 11368 entry.second.dump(pw); 11369 pw.print(" expiration="); 11370 // Convert entry.mExpirationTime, which is an elapsed time since boot, 11371 // to a time since epoch (i.e. System.currentTimeMillis()-based time.) 11372 final long expirationInCurrentTime = 11373 currentTimeNow - tempAllowlistCurrentTime + entry.first; 11374 TimeUtils.dumpTimeWithDelta(pw, expirationInCurrentTime, currentTimeNow); 11375 pw.println(); 11376 }); 11377 11378 if (!mProcessList.mAppsInBackgroundRestricted.isEmpty()) { 11379 pw.println(" Processes that are in background restricted:"); 11380 for (int i = 0, size = mProcessList.mAppsInBackgroundRestricted.size(); 11381 i < size; i++) { 11382 pw.println(String.format("%s #%2d: %s", " ", i, 11383 mProcessList.mAppsInBackgroundRestricted.valueAt(i).toString())); 11384 } 11385 } 11386 } 11387 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 11388 || mOrigWaitForDebugger) { 11389 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 11390 || dumpPackage.equals(mOrigDebugApp)) { 11391 if (needSep) { 11392 pw.println(); 11393 needSep = false; 11394 } 11395 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 11396 + " mDebugTransient=" + mDebugTransient 11397 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 11398 } 11399 } 11400 synchronized (mAppProfiler.mProfilerLock) { 11401 needSep = mAppProfiler.dumpMemWatchProcessesLPf(pw, needSep); 11402 } 11403 if (mTrackAllocationApp != null) { 11404 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 11405 if (needSep) { 11406 pw.println(); 11407 needSep = false; 11408 } 11409 pw.println(" mTrackAllocationApp=" + mTrackAllocationApp); 11410 } 11411 } 11412 needSep = mAppProfiler.dumpProfileDataLocked(pw, dumpPackage, needSep); 11413 if (mNativeDebuggingApp != null) { 11414 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 11415 if (needSep) { 11416 pw.println(); 11417 needSep = false; 11418 } 11419 pw.println(" mNativeDebuggingApp=" + mNativeDebuggingApp); 11420 } 11421 } 11422 if (dumpPackage == null) { 11423 if (mAlwaysFinishActivities) { 11424 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities); 11425 } 11426 if (mAllowSpecifiedFifoScheduling) { 11427 pw.println(" mAllowSpecifiedFifoScheduling=true"); 11428 } 11429 if (dumpAll) { 11430 pw.println(" Total persistent processes: " + numPers); 11431 pw.println(" mProcessesReady=" + mProcessesReady 11432 + " mSystemReady=" + mSystemReady 11433 + " mBooted=" + mBooted 11434 + " mFactoryTest=" + mFactoryTest); 11435 pw.println(" mBooting=" + mBooting 11436 + " mCallFinishBooting=" + mCallFinishBooting 11437 + " mBootAnimationComplete=" + mBootAnimationComplete); 11438 pw.print(" mLastPowerCheckUptime="); 11439 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 11440 pw.println(""); 11441 mOomAdjuster.dumpSequenceNumbersLocked(pw); 11442 mOomAdjuster.dumpProcCountsLocked(pw); 11443 mAppProfiler.dumpMemoryLevelsLocked(pw); 11444 long now = SystemClock.uptimeMillis(); 11445 pw.print(" mLastIdleTime="); 11446 TimeUtils.formatDuration(now, mLastIdleTime, pw); 11447 pw.print(" mLowRamSinceLastIdle="); 11448 TimeUtils.formatDuration( 11449 mAppProfiler.getLowRamTimeSinceIdleLPr(now), pw); 11450 pw.println(); 11451 11452 pw.println(); 11453 pw.println(" ServiceManager statistics:"); 11454 ServiceManager.sStatLogger.dump(pw, " "); 11455 pw.println(); 11456 } 11457 } 11458 pw.println(" mForceBackgroundCheck=" + mForceBackgroundCheck); 11459 } 11460 dumpUsers(PrintWriter pw)11461 private void dumpUsers(PrintWriter pw) { 11462 pw.println("ACTIVITY MANAGER USERS (dumpsys activity users)"); 11463 mUserController.dump(pw); 11464 } 11465 11466 @GuardedBy({"this", "mProcLock"}) writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, int dumpAppId, int numPers)11467 void writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, 11468 int dumpAppId, int numPers) { 11469 for (int i = 0, size = mActiveInstrumentation.size(); i < size; i++) { 11470 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 11471 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 11472 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 11473 continue; 11474 } 11475 ai.dumpDebug(proto, 11476 ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS); 11477 } 11478 11479 mUidObserverController.dumpValidateUidsProto(proto, dumpPackage, dumpAppId, 11480 ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS); 11481 11482 if (dumpPackage != null) { 11483 synchronized (mPidsSelfLocked) { 11484 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 11485 ProcessRecord r = mPidsSelfLocked.valueAt(i); 11486 if (!r.getPkgList().containsKey(dumpPackage)) { 11487 continue; 11488 } 11489 r.dumpDebug(proto, 11490 ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED); 11491 } 11492 } 11493 } 11494 11495 if (mImportantProcesses.size() > 0) { 11496 synchronized (mPidsSelfLocked) { 11497 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) { 11498 ImportanceToken it = mImportantProcesses.valueAt(i); 11499 ProcessRecord r = mPidsSelfLocked.get(it.pid); 11500 if (dumpPackage != null && (r == null 11501 || !r.getPkgList().containsKey(dumpPackage))) { 11502 continue; 11503 } 11504 it.dumpDebug(proto, 11505 ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS); 11506 } 11507 } 11508 } 11509 11510 for (int i = 0, size = mPersistentStartingProcesses.size(); i < size; i++) { 11511 ProcessRecord r = mPersistentStartingProcesses.get(i); 11512 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11513 continue; 11514 } 11515 r.dumpDebug(proto, 11516 ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS); 11517 } 11518 11519 for (int i = 0, size = mProcessList.mRemovedProcesses.size(); i < size; i++) { 11520 ProcessRecord r = mProcessList.mRemovedProcesses.get(i); 11521 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11522 continue; 11523 } 11524 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS); 11525 } 11526 11527 for (int i = 0, size = mProcessesOnHold.size(); i < size; i++) { 11528 ProcessRecord r = mProcessesOnHold.get(i); 11529 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11530 continue; 11531 } 11532 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS); 11533 } 11534 11535 synchronized (mAppProfiler.mProfilerLock) { 11536 mAppProfiler.writeProcessesToGcToProto(proto, 11537 ActivityManagerServiceDumpProcessesProto.GC_PROCS, 11538 dumpPackage); 11539 } 11540 mAppErrors.dumpDebugLPr(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS, 11541 dumpPackage); 11542 mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness.get(), 11543 mAppProfiler.getTestPssMode()); 11544 11545 if (dumpPackage == null) { 11546 mUserController.dumpDebug(proto, 11547 ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER); 11548 } 11549 11550 mUidObserverController.dumpDebug(proto, dumpPackage); 11551 11552 for (int v : mDeviceIdleAllowlist) { 11553 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v); 11554 } 11555 11556 for (int v : mDeviceIdleTempAllowlist) { 11557 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v); 11558 } 11559 11560 if (mPendingTempAllowlist.size() > 0) { 11561 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) { 11562 mPendingTempAllowlist.valueAt(i).dumpDebug(proto, 11563 ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST); 11564 } 11565 } 11566 11567 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 11568 || mOrigWaitForDebugger) { 11569 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 11570 || dumpPackage.equals(mOrigDebugApp)) { 11571 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG); 11572 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp); 11573 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp); 11574 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient); 11575 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger); 11576 proto.end(debugAppToken); 11577 } 11578 } 11579 11580 synchronized (mAppProfiler.mProfilerLock) { 11581 mAppProfiler.writeMemWatchProcessToProtoLPf(proto); 11582 } 11583 11584 if (mTrackAllocationApp != null) { 11585 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 11586 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP, 11587 mTrackAllocationApp); 11588 } 11589 } 11590 11591 mAppProfiler.writeProfileDataToProtoLocked(proto, dumpPackage); 11592 11593 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 11594 proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp); 11595 } 11596 11597 if (dumpPackage == null) { 11598 proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities); 11599 proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers); 11600 proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady); 11601 proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady); 11602 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted); 11603 proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest); 11604 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting); 11605 proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting); 11606 proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete); 11607 proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime); 11608 mOomAdjuster.dumpProcessListVariablesLocked(proto); 11609 mAppProfiler.writeMemoryLevelsToProtoLocked(proto); 11610 long now = SystemClock.uptimeMillis(); 11611 ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now); 11612 proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS, 11613 mAppProfiler.getLowRamTimeSinceIdleLPr(now)); 11614 } 11615 } 11616 reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)11617 private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) { 11618 Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj); 11619 if (cnt != null) { 11620 pw.println(" kills at or below oom_adj " + oom_adj + ": " + cnt); 11621 return true; 11622 } 11623 return false; 11624 } 11625 dumpLmkLocked(PrintWriter pw)11626 boolean dumpLmkLocked(PrintWriter pw) { 11627 pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)"); 11628 Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ, 11629 ProcessList.UNKNOWN_ADJ); 11630 if (cnt == null) { 11631 return false; 11632 } 11633 pw.println(" Total number of kills: " + cnt); 11634 11635 return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) && 11636 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) && 11637 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) && 11638 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) && 11639 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) && 11640 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) && 11641 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) && 11642 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) && 11643 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) && 11644 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) && 11645 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) && 11646 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ); 11647 } 11648 11649 public static class ItemMatcher { 11650 ArrayList<ComponentName> components; 11651 ArrayList<String> strings; 11652 ArrayList<Integer> objects; 11653 boolean all; 11654 ItemMatcher()11655 public ItemMatcher() { 11656 all = true; 11657 } 11658 build(String name)11659 public void build(String name) { 11660 ComponentName componentName = ComponentName.unflattenFromString(name); 11661 if (componentName != null) { 11662 if (components == null) { 11663 components = new ArrayList<ComponentName>(); 11664 } 11665 components.add(componentName); 11666 all = false; 11667 } else { 11668 int objectId = 0; 11669 // Not a '/' separated full component name; maybe an object ID? 11670 try { 11671 objectId = Integer.parseInt(name, 16); 11672 if (objects == null) { 11673 objects = new ArrayList<Integer>(); 11674 } 11675 objects.add(objectId); 11676 all = false; 11677 } catch (RuntimeException e) { 11678 // Not an integer; just do string match. 11679 if (strings == null) { 11680 strings = new ArrayList<String>(); 11681 } 11682 strings.add(name); 11683 all = false; 11684 } 11685 } 11686 } 11687 build(String[] args, int opti)11688 public int build(String[] args, int opti) { 11689 for (; opti<args.length; opti++) { 11690 String name = args[opti]; 11691 if ("--".equals(name)) { 11692 return opti+1; 11693 } 11694 build(name); 11695 } 11696 return opti; 11697 } 11698 match(Object object, ComponentName comp)11699 public boolean match(Object object, ComponentName comp) { 11700 if (all) { 11701 return true; 11702 } 11703 if (components != null) { 11704 for (int i=0; i<components.size(); i++) { 11705 if (components.get(i).equals(comp)) { 11706 return true; 11707 } 11708 } 11709 } 11710 if (objects != null) { 11711 for (int i=0; i<objects.size(); i++) { 11712 if (System.identityHashCode(object) == objects.get(i)) { 11713 return true; 11714 } 11715 } 11716 } 11717 if (strings != null) { 11718 String flat = comp.flattenToString(); 11719 for (int i=0; i<strings.size(); i++) { 11720 if (flat.contains(strings.get(i))) { 11721 return true; 11722 } 11723 } 11724 } 11725 return false; 11726 } 11727 } 11728 dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11729 void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11730 int opti, boolean dumpAll, String dumpPackage) { 11731 pw.println( 11732 "ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity" 11733 + " allowed-associations)"); 11734 boolean printed = false; 11735 if (mAllowedAssociations != null) { 11736 for (int i = 0; i < mAllowedAssociations.size(); i++) { 11737 final String pkg = mAllowedAssociations.keyAt(i); 11738 final ArraySet<String> asc = 11739 mAllowedAssociations.valueAt(i).getAllowedPackageAssociations(); 11740 if (!printed) { 11741 pw.println(" Allowed associations (by restricted package):"); 11742 printed = true; 11743 } 11744 pw.print(" * "); 11745 pw.print(pkg); 11746 pw.println(":"); 11747 for (int j = 0; j < asc.size(); j++) { 11748 if (dumpPackage == null || pkg.equals(dumpPackage) 11749 || asc.valueAt(j).equals(dumpPackage)) { 11750 pw.print(" Allow: "); 11751 pw.println(asc.valueAt(j)); 11752 } 11753 } 11754 if (mAllowedAssociations.valueAt(i).isDebuggable()) { 11755 pw.println(" (debuggable)"); 11756 } 11757 } 11758 } 11759 if (!printed) { 11760 pw.println(" (No association restrictions)"); 11761 } 11762 } 11763 dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11764 void dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, 11765 int opti, boolean dumpAll, String dumpPackage) { 11766 11767 pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)"); 11768 11769 mUgmInternal.dump(pw, dumpAll, dumpPackage); 11770 } 11771 dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)11772 private static int dumpProcessList(PrintWriter pw, 11773 ActivityManagerService service, List list, 11774 String prefix, String normalLabel, String persistentLabel, 11775 String dumpPackage) { 11776 int numPers = 0; 11777 for (int i = list.size() - 1; i >= 0; i--) { 11778 ProcessRecord r = (ProcessRecord) list.get(i); 11779 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 11780 continue; 11781 } 11782 pw.println(String.format("%s%s #%2d: %s", 11783 prefix, (r.isPersistent() ? persistentLabel : normalLabel), 11784 i, r.toString())); 11785 if (r.isPersistent()) { 11786 numPers++; 11787 } 11788 } 11789 return numPers; 11790 } 11791 collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)11792 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs, 11793 String[] args) { 11794 synchronized (mProcLock) { 11795 return mProcessList.collectProcessesLOSP(start, allPkgs, args); 11796 } 11797 } 11798 dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)11799 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 11800 PrintWriter pw, String[] args) { 11801 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 11802 if (procs == null) { 11803 pw.println("No process found for: " + args[0]); 11804 return; 11805 } 11806 11807 long uptime = SystemClock.uptimeMillis(); 11808 long realtime = SystemClock.elapsedRealtime(); 11809 pw.println("Applications Graphics Acceleration Info:"); 11810 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 11811 11812 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 11813 ProcessRecord r = procs.get(i); 11814 final int pid = r.getPid(); 11815 final IApplicationThread thread = r.getThread(); 11816 if (thread != null) { 11817 pw.println("\n** Graphics info for pid " + pid + " [" + r.processName + "] **"); 11818 pw.flush(); 11819 try { 11820 TransferPipe tp = new TransferPipe(); 11821 try { 11822 thread.dumpGfxInfo(tp.getWriteFd(), args); 11823 tp.go(fd); 11824 } finally { 11825 tp.kill(); 11826 } 11827 } catch (IOException e) { 11828 pw.println("Failure while dumping the app: " + r); 11829 pw.flush(); 11830 } catch (RemoteException e) { 11831 pw.println("Got a RemoteException while dumping the app " + r); 11832 pw.flush(); 11833 } 11834 } 11835 } 11836 } 11837 dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args)11838 final void dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args) { 11839 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 11840 if (procs == null) { 11841 pw.println("No process found for: " + args[0]); 11842 return; 11843 } 11844 11845 pw.println("Per-process Binder Cache Contents"); 11846 11847 for (int i = procs.size() - 1; i >= 0; i--) { 11848 ProcessRecord r = procs.get(i); 11849 final int pid = r.getPid(); 11850 final IApplicationThread thread = r.getThread(); 11851 if (thread != null) { 11852 pw.println("\n\n** Cache info for pid " + pid + " [" + r.processName + "] **"); 11853 pw.flush(); 11854 try { 11855 if (pid == Process.myPid()) { 11856 // Directly dump to target fd for local dump to avoid hang. 11857 try (ParcelFileDescriptor pfd = ParcelFileDescriptor.fromFd(fd.getInt$())) { 11858 thread.dumpCacheInfo(pfd, args); 11859 } 11860 continue; 11861 } 11862 TransferPipe tp = new TransferPipe(); 11863 try { 11864 thread.dumpCacheInfo(tp.getWriteFd(), args); 11865 tp.go(fd); 11866 } finally { 11867 tp.kill(); 11868 } 11869 } catch (IOException e) { 11870 pw.println("Failure while dumping the app " + r); 11871 pw.flush(); 11872 } catch (RemoteException e) { 11873 pw.println("Got a RemoteException while dumping the app " + r); 11874 pw.flush(); 11875 } 11876 } 11877 } 11878 } 11879 dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)11880 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 11881 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 11882 if (procs == null) { 11883 pw.println("No process found for: " + args[0]); 11884 return; 11885 } 11886 11887 pw.println("Applications Database Info:"); 11888 11889 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 11890 ProcessRecord r = procs.get(i); 11891 final int pid = r.getPid(); 11892 final IApplicationThread thread = r.getThread(); 11893 if (thread != null) { 11894 pw.println("\n** Database info for pid " + pid + " [" + r.processName + "] **"); 11895 pw.flush(); 11896 try { 11897 TransferPipe tp = new TransferPipe(); 11898 try { 11899 thread.dumpDbInfo(tp.getWriteFd(), args); 11900 tp.go(fd); 11901 } finally { 11902 tp.kill(); 11903 } 11904 } catch (IOException e) { 11905 pw.println("Failure while dumping the app: " + r); 11906 pw.flush(); 11907 } catch (RemoteException e) { 11908 pw.println("Got a RemoteException while dumping the app " + r); 11909 pw.flush(); 11910 } 11911 } 11912 } 11913 } 11914 11915 final static class MemItem { 11916 final boolean isProc; 11917 final String label; 11918 final String shortLabel; 11919 final long pss; 11920 final long swapPss; 11921 final long mRss; 11922 final long mPrivateDirty; 11923 final int id; // pid 11924 final int userId; 11925 final boolean hasActivities; 11926 ArrayList<MemItem> subitems; 11927 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, long privateDirty, int id, @UserIdInt int userId, boolean hasActivities)11928 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, 11929 long privateDirty, int id, @UserIdInt int userId, 11930 boolean hasActivities) { 11931 this.isProc = true; 11932 this.label = label; 11933 this.shortLabel = shortLabel; 11934 this.pss = pss; 11935 this.swapPss = swapPss; 11936 this.mRss = rss; 11937 this.mPrivateDirty = privateDirty; 11938 this.id = id; 11939 this.userId = userId; 11940 this.hasActivities = hasActivities; 11941 } 11942 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, long privateDirty, int id)11943 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, 11944 long privateDirty, int id) { 11945 this.isProc = false; 11946 this.label = label; 11947 this.shortLabel = shortLabel; 11948 this.pss = pss; 11949 this.swapPss = swapPss; 11950 this.mRss = rss; 11951 this.mPrivateDirty = privateDirty; 11952 this.id = id; 11953 this.userId = UserHandle.USER_SYSTEM; 11954 this.hasActivities = false; 11955 } 11956 } 11957 sortMemItems(List<MemItem> items, final boolean pss)11958 private static void sortMemItems(List<MemItem> items, final boolean pss) { 11959 Collections.sort(items, new Comparator<MemItem>() { 11960 @Override 11961 public int compare(MemItem lhs, MemItem rhs) { 11962 long lss = pss ? lhs.pss : lhs.mRss; 11963 long rss = pss ? rhs.pss : rhs.mRss; 11964 if (lss < rss) { 11965 return 1; 11966 } else if (lss > rss) { 11967 return -1; 11968 } 11969 return 0; 11970 } 11971 }); 11972 } 11973 dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, boolean dumpSwapPss, boolean dumpPrivateDirty)11974 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 11975 ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, 11976 boolean dumpSwapPss, boolean dumpPrivateDirty) { 11977 if (sort && !isCompact) { 11978 sortMemItems(items, dumpPss); 11979 } 11980 11981 for (int i=0; i<items.size(); i++) { 11982 MemItem mi = items.get(i); 11983 if (!isCompact) { 11984 String printFormat = "%s%s: %s%s\n"; 11985 if ((dumpPss && dumpSwapPss) || dumpPrivateDirty) { 11986 StringBuilder format = new StringBuilder(); 11987 format.append("%s%s: %-60s%s"); 11988 if (dumpSwapPss) { 11989 format.append(String.format("(%s in swap%s", stringifyKBSize(mi.swapPss), 11990 dumpPrivateDirty ? ", " : ")")); 11991 } 11992 if (dumpPrivateDirty) { 11993 format.append(String.format("%s%s private dirty)", dumpSwapPss ? "" : "(", 11994 stringifyKBSize(mi.mPrivateDirty))); 11995 } 11996 printFormat = format.append("\n").toString(); 11997 } 11998 pw.printf(printFormat, prefix, stringifyKBSize(dumpPss ? mi.pss : mi.mRss), 11999 mi.label, 12000 mi.userId != UserHandle.USER_SYSTEM ? " (user " + mi.userId + ")" : ""); 12001 } else if (mi.isProc) { 12002 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 12003 pw.print(","); pw.print(mi.id); pw.print(","); 12004 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(","); 12005 pw.print(dumpSwapPss ? mi.swapPss : "N/A"); 12006 pw.println(mi.hasActivities ? ",a" : ",e"); 12007 } else { 12008 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 12009 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(","); 12010 pw.println(dumpSwapPss ? mi.swapPss : "N/A"); 12011 } 12012 if (mi.subitems != null) { 12013 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 12014 true, isCompact, dumpPss, dumpSwapPss, dumpPrivateDirty); 12015 } 12016 } 12017 } 12018 dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss)12019 static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, 12020 ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss) { 12021 if (sort) { 12022 sortMemItems(items, dumpPss); 12023 } 12024 12025 for (int i=0; i<items.size(); i++) { 12026 MemItem mi = items.get(i); 12027 final long token = proto.start(fieldId); 12028 12029 proto.write(MemInfoDumpProto.MemItem.TAG, tag); 12030 proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel); 12031 proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc); 12032 proto.write(MemInfoDumpProto.MemItem.ID, mi.id); 12033 proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities); 12034 proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss); 12035 proto.write(MemInfoDumpProto.MemItem.RSS_KB, mi.mRss); 12036 if (dumpSwapPss) { 12037 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss); 12038 } 12039 if (mi.subitems != null) { 12040 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems, 12041 true, dumpPss, dumpSwapPss); 12042 } 12043 proto.end(token); 12044 } 12045 } 12046 12047 // These are in KB. 12048 static final long[] DUMP_MEM_BUCKETS = new long[] { 12049 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 12050 120*1024, 160*1024, 200*1024, 12051 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 12052 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 12053 }; 12054 appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)12055 static final void appendMemBucket(StringBuilder out, long memKB, String label, 12056 boolean stackLike) { 12057 int start = label.lastIndexOf('.'); 12058 if (start >= 0) start++; 12059 else start = 0; 12060 int end = label.length(); 12061 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 12062 if (DUMP_MEM_BUCKETS[i] >= memKB) { 12063 long bucket = DUMP_MEM_BUCKETS[i]/1024; 12064 out.append(bucket); 12065 out.append(stackLike ? "MB." : "MB "); 12066 out.append(label, start, end); 12067 return; 12068 } 12069 } 12070 out.append(memKB/1024); 12071 out.append(stackLike ? "MB." : "MB "); 12072 out.append(label, start, end); 12073 } 12074 12075 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 12076 ProcessList.NATIVE_ADJ, 12077 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, 12078 ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ, 12079 ProcessList.VISIBLE_APP_ADJ, 12080 ProcessList.PERCEPTIBLE_APP_ADJ, 12081 ProcessList.PERCEPTIBLE_MEDIUM_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ, 12082 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 12083 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 12084 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ 12085 }; 12086 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 12087 "Native", 12088 "System", "Persistent", "Persistent Service", "Foreground", 12089 "Visible", "Perceptible", "Perceptible Medium", "Perceptible Low", 12090 "Backup", "Heavy Weight", 12091 "A Services", "Home", 12092 "Previous", "B Services", "Cached" 12093 }; 12094 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 12095 "native", 12096 "sys", "pers", "persvc", "fore", 12097 "vis", "percept", "perceptm", "perceptl", 12098 "backup", "heavy", 12099 "servicea", "home", 12100 "prev", "serviceb", "cached" 12101 }; 12102 dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)12103 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 12104 long realtime, boolean isCheckinRequest, boolean isCompact) { 12105 if (isCompact) { 12106 pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION); 12107 } 12108 if (isCheckinRequest || isCompact) { 12109 // short checkin version 12110 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 12111 } else { 12112 pw.println("Applications Memory Usage (in Kilobytes):"); 12113 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 12114 } 12115 } 12116 12117 static final int KSM_SHARED = 0; 12118 static final int KSM_SHARING = 1; 12119 static final int KSM_UNSHARED = 2; 12120 static final int KSM_VOLATILE = 3; 12121 getKsmInfo()12122 static final long[] getKsmInfo() { 12123 long[] longOut = new long[4]; 12124 final int[] SINGLE_LONG_FORMAT = new int[] { 12125 PROC_SPACE_TERM| PROC_OUT_LONG 12126 }; 12127 long[] longTmp = new long[1]; 12128 readProcFile("/sys/kernel/mm/ksm/pages_shared", 12129 SINGLE_LONG_FORMAT, null, longTmp, null); 12130 longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12131 longTmp[0] = 0; 12132 readProcFile("/sys/kernel/mm/ksm/pages_sharing", 12133 SINGLE_LONG_FORMAT, null, longTmp, null); 12134 longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12135 longTmp[0] = 0; 12136 readProcFile("/sys/kernel/mm/ksm/pages_unshared", 12137 SINGLE_LONG_FORMAT, null, longTmp, null); 12138 longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12139 longTmp[0] = 0; 12140 readProcFile("/sys/kernel/mm/ksm/pages_volatile", 12141 SINGLE_LONG_FORMAT, null, longTmp, null); 12142 longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 12143 return longOut; 12144 } 12145 stringifySize(long size, int order)12146 static String stringifySize(long size, int order) { 12147 Locale locale = Locale.US; 12148 switch (order) { 12149 case 1: 12150 return String.format(locale, "%,13d", size); 12151 case 1024: 12152 return String.format(locale, "%,9dK", size / 1024); 12153 case 1024 * 1024: 12154 return String.format(locale, "%,5dM", size / 1024 / 1024); 12155 case 1024 * 1024 * 1024: 12156 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024); 12157 default: 12158 throw new IllegalArgumentException("Invalid size order"); 12159 } 12160 } 12161 stringifyKBSize(long size)12162 static String stringifyKBSize(long size) { 12163 return stringifySize(size * 1024, 1024); 12164 } 12165 12166 // Update this version number if you change the 'compact' format. 12167 private static final int MEMINFO_COMPACT_VERSION = 1; 12168 12169 private static class MemoryUsageDumpOptions { 12170 boolean dumpDetails; 12171 boolean dumpFullDetails; 12172 boolean dumpDalvik; 12173 boolean dumpSummaryOnly; 12174 boolean dumpUnreachable; 12175 boolean oomOnly; 12176 boolean isCompact; 12177 boolean localOnly; 12178 boolean packages; 12179 boolean isCheckinRequest; 12180 boolean dumpSwapPss; 12181 boolean dumpProto; 12182 boolean mDumpPrivateDirty; 12183 boolean mDumpAllocatorStats; 12184 } 12185 12186 @NeverCompile // Avoid size overhead of debugging code. dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)12187 final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 12188 String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) { 12189 MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions(); 12190 opts.dumpDetails = false; 12191 opts.dumpFullDetails = false; 12192 opts.dumpDalvik = false; 12193 opts.dumpSummaryOnly = false; 12194 opts.dumpUnreachable = false; 12195 opts.oomOnly = false; 12196 opts.isCompact = false; 12197 opts.localOnly = false; 12198 opts.packages = false; 12199 opts.isCheckinRequest = false; 12200 opts.dumpSwapPss = false; 12201 opts.dumpProto = asProto; 12202 opts.mDumpPrivateDirty = false; 12203 opts.mDumpAllocatorStats = false; 12204 12205 int opti = 0; 12206 while (opti < args.length) { 12207 String opt = args[opti]; 12208 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12209 break; 12210 } 12211 opti++; 12212 if ("-a".equals(opt)) { 12213 opts.dumpDetails = true; 12214 opts.dumpFullDetails = true; 12215 opts.dumpDalvik = true; 12216 opts.dumpSwapPss = true; 12217 } else if ("-d".equals(opt)) { 12218 opts.dumpDalvik = true; 12219 } else if ("-c".equals(opt)) { 12220 opts.isCompact = true; 12221 } else if ("-s".equals(opt)) { 12222 opts.dumpDetails = true; 12223 opts.dumpSummaryOnly = true; 12224 } else if ("-S".equals(opt)) { 12225 opts.dumpSwapPss = true; 12226 } else if ("-p".equals(opt)) { 12227 opts.mDumpPrivateDirty = true; 12228 } else if ("--unreachable".equals(opt)) { 12229 opts.dumpUnreachable = true; 12230 } else if ("--oom".equals(opt)) { 12231 opts.oomOnly = true; 12232 } else if ("--local".equals(opt)) { 12233 opts.localOnly = true; 12234 } else if ("--package".equals(opt)) { 12235 opts.packages = true; 12236 } else if ("--checkin".equals(opt)) { 12237 opts.isCheckinRequest = true; 12238 } else if ("--proto".equals(opt)) { 12239 opts.dumpProto = true; 12240 } else if ("--logstats".equals(opt)) { 12241 opts.mDumpAllocatorStats = true; 12242 } else if ("-h".equals(opt) || "--help".equals(opt)) { 12243 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]"); 12244 pw.println(" -a: include all available information for each process."); 12245 pw.println(" -d: include dalvik details."); 12246 pw.println(" -c: dump in a compact machine-parseable representation."); 12247 pw.println(" -s: dump only summary of application memory usage."); 12248 pw.println(" -S: dump also SwapPss."); 12249 pw.println(" -p: dump also private dirty memory usage."); 12250 pw.println(" --oom: only show processes organized by oom adj."); 12251 pw.println(" --local: only collect details locally, don't call process."); 12252 pw.println(" --logstats: dump native allocator stats to log"); 12253 pw.println(" --package: interpret process arg as package, dumping all"); 12254 pw.println(" processes that have loaded that package."); 12255 pw.println(" --checkin: dump data for a checkin"); 12256 pw.println(" --proto: dump data to proto"); 12257 pw.println(" --logstats: log native allocator statistics."); 12258 pw.println(" --unreachable: dump unreachable native memory with libmemunreachable."); 12259 pw.println("If [process] is specified it can be the name or "); 12260 pw.println("pid of a specific process to dump."); 12261 return; 12262 } else { 12263 pw.println("Unknown argument: " + opt + "; use -h for help"); 12264 } 12265 } 12266 12267 String[] innerArgs = new String[args.length-opti]; 12268 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 12269 12270 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args); 12271 if (opts.dumpProto) { 12272 dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs); 12273 } else { 12274 dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw); 12275 } 12276 } 12277 12278 @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)12279 private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 12280 MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, 12281 ArrayList<ProcessRecord> procs, PrintWriter categoryPw) { 12282 long uptime = SystemClock.uptimeMillis(); 12283 long realtime = SystemClock.elapsedRealtime(); 12284 final long[] tmpLong = new long[3]; 12285 12286 if (procs == null) { 12287 // No Java processes. Maybe they want to print a native process. 12288 String proc = "N/A"; 12289 if (innerArgs.length > 0) { 12290 proc = innerArgs[0]; 12291 if (proc.charAt(0) != '-') { 12292 ArrayList<ProcessCpuTracker.Stats> nativeProcs 12293 = new ArrayList<ProcessCpuTracker.Stats>(); 12294 updateCpuStatsNow(); 12295 int findPid = -1; 12296 try { 12297 findPid = Integer.parseInt(innerArgs[0]); 12298 } catch (NumberFormatException e) { 12299 } 12300 final int fFindPid = findPid; 12301 mAppProfiler.forAllCpuStats((st) -> { 12302 if (st.pid == fFindPid || (st.baseName != null 12303 && st.baseName.equals(innerArgs[0]))) { 12304 nativeProcs.add(st); 12305 } 12306 }); 12307 if (nativeProcs.size() > 0) { 12308 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, 12309 opts.isCheckinRequest, opts.isCompact); 12310 Debug.MemoryInfo mi = null; 12311 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 12312 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 12313 final int pid = r.pid; 12314 if (mi == null) { 12315 mi = new Debug.MemoryInfo(); 12316 } 12317 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 12318 if (!Debug.getMemoryInfo(pid, mi)) { 12319 continue; 12320 } 12321 } else { 12322 long pss = Debug.getPss(pid, tmpLong, null); 12323 if (pss == 0) { 12324 continue; 12325 } 12326 mi.nativePss = (int) pss; 12327 mi.nativePrivateDirty = (int) tmpLong[0]; 12328 mi.nativeRss = (int) tmpLong[2]; 12329 } 12330 if (!opts.isCheckinRequest && opts.dumpDetails) { 12331 pw.println("\n** MEMINFO in pid " + pid + " [" 12332 + r.baseName + "] **"); 12333 } 12334 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, 12335 opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 12336 pid, r.baseName, 0, 0, 0, 0, 0, 0); 12337 if (opts.isCheckinRequest) { 12338 pw.println(); 12339 } 12340 } 12341 return; 12342 } 12343 } 12344 } 12345 pw.println("No process found for: " + proc); 12346 return; 12347 } 12348 12349 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 12350 opts.dumpDetails = true; 12351 } 12352 final int numProcs = procs.size(); 12353 final boolean collectNative = !opts.isCheckinRequest && numProcs > 1 && !opts.packages; 12354 if (collectNative) { 12355 // If we are showing aggregations, also look for native processes to 12356 // include so that our aggregations are more accurate. 12357 updateCpuStatsNow(); 12358 } 12359 12360 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact); 12361 12362 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 12363 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 12364 final long[] ss = new long[INDEX_LAST]; 12365 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12366 EmptyArray.LONG; 12367 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12368 EmptyArray.LONG; 12369 long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 12370 EmptyArray.LONG; 12371 long[] dalvikSubitemPrivateDirty = opts.dumpDalvik 12372 ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : EmptyArray.LONG; 12373 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12374 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12375 long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12376 long[] miscPrivateDirty = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 12377 long[] memtrackTmp = new long[4]; 12378 12379 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 12380 long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 12381 long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length]; 12382 long[] oomPrivateDirty = new long[DUMP_MEM_OOM_LABEL.length]; 12383 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 12384 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 12385 12386 long totalSwapPss = 0; 12387 long totalRss = 0; 12388 long cachedPss = 0; 12389 long cachedSwapPss = 0; 12390 boolean hasSwapPss = false; 12391 12392 Debug.MemoryInfo mi = null; 12393 for (int i = numProcs - 1; i >= 0; i--) { 12394 final ProcessRecord r = procs.get(i); 12395 final IApplicationThread thread; 12396 final int pid; 12397 final int oomAdj; 12398 final boolean hasActivities; 12399 synchronized (mProcLock) { 12400 thread = r.getThread(); 12401 pid = r.getPid(); 12402 oomAdj = r.mState.getSetAdjWithServices(); 12403 hasActivities = r.hasActivities(); 12404 } 12405 if (thread != null) { 12406 if (mi == null) { 12407 mi = new Debug.MemoryInfo(); 12408 } 12409 final int reportType; 12410 final long startTime; 12411 final long endTime; 12412 long memtrackGraphics = 0; 12413 long memtrackGl = 0; 12414 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 12415 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 12416 startTime = SystemClock.currentThreadTimeMillis(); 12417 if (!Debug.getMemoryInfo(pid, mi)) { 12418 continue; 12419 } 12420 endTime = SystemClock.currentThreadTimeMillis(); 12421 hasSwapPss = hasSwapPss || mi.hasSwappedOutPss; 12422 memtrackGraphics = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS); 12423 memtrackGl = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GL); 12424 } else { 12425 reportType = ProcessStats.ADD_PSS_EXTERNAL; 12426 startTime = SystemClock.currentThreadTimeMillis(); 12427 long pss = Debug.getPss(pid, tmpLong, memtrackTmp); 12428 if (pss == 0) { 12429 continue; 12430 } 12431 mi.dalvikPss = (int) pss; 12432 endTime = SystemClock.currentThreadTimeMillis(); 12433 mi.dalvikPrivateDirty = (int) tmpLong[0]; 12434 mi.dalvikRss = (int) tmpLong[2]; 12435 memtrackGraphics = memtrackTmp[1]; 12436 memtrackGl = memtrackTmp[2]; 12437 } 12438 if (!opts.isCheckinRequest && opts.dumpDetails) { 12439 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 12440 } 12441 if (opts.dumpDetails) { 12442 if (opts.localOnly) { 12443 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails, 12444 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0); 12445 if (opts.isCheckinRequest) { 12446 pw.println(); 12447 } 12448 } else { 12449 pw.flush(); 12450 try { 12451 TransferPipe tp = new TransferPipe(); 12452 try { 12453 thread.dumpMemInfo(tp.getWriteFd(), 12454 mi, opts.isCheckinRequest, opts.dumpFullDetails, 12455 opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, 12456 opts.mDumpAllocatorStats, innerArgs); 12457 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000); 12458 } finally { 12459 tp.kill(); 12460 } 12461 } catch (IOException e) { 12462 if (!opts.isCheckinRequest) { 12463 pw.println("Got IoException! " + e); 12464 pw.flush(); 12465 } 12466 } catch (RemoteException e) { 12467 if (!opts.isCheckinRequest) { 12468 pw.println("Got RemoteException! " + e); 12469 pw.flush(); 12470 } 12471 } 12472 } 12473 } 12474 12475 final long myTotalPss = mi.getTotalPss(); 12476 final long myTotalUss = mi.getTotalUss(); 12477 final long myTotalRss = mi.getTotalRss(); 12478 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 12479 final long myTotalPrivateDirty = mi.getTotalPrivateDirty(); 12480 12481 synchronized (mProcLock) { 12482 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) { 12483 // Record this for posterity if the process has been stable. 12484 r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true, 12485 reportType, endTime - startTime); 12486 } 12487 } 12488 12489 if (!opts.isCheckinRequest && mi != null) { 12490 ss[INDEX_TOTAL_PSS] += myTotalPss; 12491 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 12492 ss[INDEX_TOTAL_RSS] += myTotalRss; 12493 ss[INDEX_TOTAL_PRIVATE_DIRTY] += myTotalPrivateDirty; 12494 ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics; 12495 ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl; 12496 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 12497 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 12498 myTotalSwapPss, myTotalRss, myTotalPrivateDirty, 12499 pid, r.userId, hasActivities); 12500 procMems.add(pssItem); 12501 procMemsMap.put(pid, pssItem); 12502 12503 ss[INDEX_NATIVE_PSS] += mi.nativePss; 12504 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss; 12505 ss[INDEX_NATIVE_RSS] += mi.nativeRss; 12506 ss[INDEX_NATIVE_PRIVATE_DIRTY] += mi.nativePrivateDirty; 12507 ss[INDEX_DALVIK_PSS] += mi.dalvikPss; 12508 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss; 12509 ss[INDEX_DALVIK_RSS] += mi.dalvikRss; 12510 ss[INDEX_DALVIK_PRIVATE_DIRTY] += mi.dalvikPrivateDirty; 12511 for (int j=0; j<dalvikSubitemPss.length; j++) { 12512 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12513 dalvikSubitemSwapPss[j] += 12514 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12515 dalvikSubitemPrivateDirty[j] += 12516 mi.getOtherPrivateDirty(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12517 dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12518 } 12519 ss[INDEX_OTHER_PSS] += mi.otherPss; 12520 ss[INDEX_OTHER_RSS] += mi.otherRss; 12521 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss; 12522 ss[INDEX_OTHER_PRIVATE_DIRTY] += mi.otherPrivateDirty; 12523 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12524 long mem = mi.getOtherPss(j); 12525 miscPss[j] += mem; 12526 ss[INDEX_OTHER_PSS] -= mem; 12527 mem = mi.getOtherSwappedOutPss(j); 12528 miscSwapPss[j] += mem; 12529 ss[INDEX_OTHER_SWAP_PSS] -= mem; 12530 mem = mi.getOtherPrivateDirty(j); 12531 miscPrivateDirty[j] += mem; 12532 ss[INDEX_OTHER_PRIVATE_DIRTY] -= mem; 12533 mem = mi.getOtherRss(j); 12534 miscRss[j] += mem; 12535 ss[INDEX_OTHER_RSS] -= mem; 12536 } 12537 12538 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 12539 cachedPss += myTotalPss; 12540 cachedSwapPss += myTotalSwapPss; 12541 } 12542 12543 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 12544 if (oomIndex == (oomPss.length - 1) 12545 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 12546 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 12547 oomPss[oomIndex] += myTotalPss; 12548 oomSwapPss[oomIndex] += myTotalSwapPss; 12549 oomPrivateDirty[oomIndex] += myTotalPrivateDirty; 12550 if (oomProcs[oomIndex] == null) { 12551 oomProcs[oomIndex] = new ArrayList<MemItem>(); 12552 } 12553 oomProcs[oomIndex].add(pssItem); 12554 oomRss[oomIndex] += myTotalRss; 12555 break; 12556 } 12557 } 12558 } 12559 } 12560 } 12561 12562 long nativeProcTotalPss = 0; 12563 12564 if (collectNative) { 12565 mi = null; 12566 final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1]; 12567 mAppProfiler.forAllCpuStats((st) -> { 12568 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 12569 long memtrackGraphics = 0; 12570 long memtrackGl = 0; 12571 if (memInfos[0] == null) { 12572 memInfos[0] = new Debug.MemoryInfo(); 12573 } 12574 final Debug.MemoryInfo info = memInfos[0]; 12575 if (!brief && !opts.oomOnly) { 12576 if (!Debug.getMemoryInfo(st.pid, info)) { 12577 return; 12578 } 12579 memtrackGraphics = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS); 12580 memtrackGl = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GL); 12581 } else { 12582 long pss = Debug.getPss(st.pid, tmpLong, memtrackTmp); 12583 if (pss == 0) { 12584 return; 12585 } 12586 info.nativePss = (int) pss; 12587 info.nativePrivateDirty = (int) tmpLong[0]; 12588 info.nativeRss = (int) tmpLong[2]; 12589 memtrackGraphics = memtrackTmp[1]; 12590 memtrackGl = memtrackTmp[2]; 12591 } 12592 12593 final long myTotalPss = info.getTotalPss(); 12594 final long myTotalSwapPss = info.getTotalSwappedOutPss(); 12595 final long myTotalRss = info.getTotalRss(); 12596 final long myTotalPrivateDirty = info.getTotalPrivateDirty(); 12597 ss[INDEX_TOTAL_PSS] += myTotalPss; 12598 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 12599 ss[INDEX_TOTAL_RSS] += myTotalRss; 12600 ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss; 12601 ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics; 12602 ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl; 12603 12604 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 12605 st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss, 12606 myTotalPrivateDirty, st.pid, UserHandle.getUserId(st.uid), false); 12607 procMems.add(pssItem); 12608 12609 ss[INDEX_NATIVE_PSS] += info.nativePss; 12610 ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss; 12611 ss[INDEX_NATIVE_RSS] += info.nativeRss; 12612 ss[INDEX_NATIVE_PRIVATE_DIRTY] += info.nativePrivateDirty; 12613 ss[INDEX_DALVIK_PSS] += info.dalvikPss; 12614 ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss; 12615 ss[INDEX_DALVIK_RSS] += info.dalvikRss; 12616 ss[INDEX_DALVIK_PRIVATE_DIRTY] += info.dalvikPrivateDirty; 12617 for (int j = 0; j < dalvikSubitemPss.length; j++) { 12618 dalvikSubitemPss[j] += info.getOtherPss( 12619 Debug.MemoryInfo.NUM_OTHER_STATS + j); 12620 dalvikSubitemSwapPss[j] += 12621 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12622 dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS 12623 + j); 12624 dalvikSubitemPrivateDirty[j] += 12625 info.getOtherPrivateDirty(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12626 } 12627 ss[INDEX_OTHER_PSS] += info.otherPss; 12628 ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss; 12629 ss[INDEX_OTHER_RSS] += info.otherRss; 12630 ss[INDEX_OTHER_PRIVATE_DIRTY] += info.otherPrivateDirty; 12631 for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12632 long mem = info.getOtherPss(j); 12633 miscPss[j] += mem; 12634 ss[INDEX_OTHER_PSS] -= mem; 12635 mem = info.getOtherSwappedOutPss(j); 12636 miscSwapPss[j] += mem; 12637 ss[INDEX_OTHER_SWAP_PSS] -= mem; 12638 mem = info.getOtherRss(j); 12639 miscRss[j] += mem; 12640 ss[INDEX_OTHER_RSS] -= mem; 12641 mem = info.getOtherPrivateDirty(j); 12642 miscPrivateDirty[j] += mem; 12643 ss[INDEX_OTHER_PRIVATE_DIRTY] -= mem; 12644 } 12645 oomPss[0] += myTotalPss; 12646 oomSwapPss[0] += myTotalSwapPss; 12647 if (oomProcs[0] == null) { 12648 oomProcs[0] = new ArrayList<MemItem>(); 12649 } 12650 oomProcs[0].add(pssItem); 12651 oomRss[0] += myTotalRss; 12652 oomPrivateDirty[0] += myTotalPrivateDirty; 12653 } 12654 }); 12655 12656 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 12657 12658 catMems.add(new MemItem("Native", "Native", 12659 ss[INDEX_NATIVE_PSS], ss[INDEX_NATIVE_SWAP_PSS], 12660 ss[INDEX_NATIVE_RSS], ss[INDEX_NATIVE_PRIVATE_DIRTY], -1)); 12661 final int dalvikId = -2; 12662 catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS], 12663 ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], 12664 ss[INDEX_DALVIK_PRIVATE_DIRTY], dalvikId)); 12665 catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS], 12666 ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], 12667 ss[INDEX_OTHER_PRIVATE_DIRTY], -3)); 12668 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12669 String label = Debug.MemoryInfo.getOtherLabel(j); 12670 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], 12671 miscPrivateDirty[j], j)); 12672 } 12673 if (dalvikSubitemPss.length > 0) { 12674 // Add dalvik subitems. 12675 for (MemItem memItem : catMems) { 12676 int memItemStart = 0, memItemEnd = 0; 12677 if (memItem.id == dalvikId) { 12678 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 12679 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 12680 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 12681 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 12682 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 12683 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 12684 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 12685 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 12686 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 12687 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 12688 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 12689 } else { 12690 continue; // No subitems, continue. 12691 } 12692 memItem.subitems = new ArrayList<MemItem>(); 12693 for (int j=memItemStart; j<=memItemEnd; j++) { 12694 final String name = Debug.MemoryInfo.getOtherLabel( 12695 Debug.MemoryInfo.NUM_OTHER_STATS + j); 12696 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 12697 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], 12698 dalvikSubitemPrivateDirty[j], j)); 12699 } 12700 } 12701 } 12702 12703 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 12704 for (int j=0; j<oomPss.length; j++) { 12705 if (oomPss[j] != 0) { 12706 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 12707 : DUMP_MEM_OOM_LABEL[j]; 12708 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j], 12709 oomPrivateDirty[j], DUMP_MEM_OOM_ADJ[j]); 12710 item.subitems = oomProcs[j]; 12711 oomMems.add(item); 12712 } 12713 } 12714 if (!opts.isCompact) { 12715 pw.println(); 12716 } 12717 if (!brief && !opts.oomOnly && !opts.isCompact) { 12718 pw.println(); 12719 pw.println("Total RSS by process:"); 12720 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, false, false, false); 12721 pw.println(); 12722 } 12723 if (!opts.isCompact) { 12724 pw.println("Total RSS by OOM adjustment:"); 12725 } 12726 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, false, false, false); 12727 if (!brief && !opts.oomOnly) { 12728 PrintWriter out = categoryPw != null ? categoryPw : pw; 12729 if (!opts.isCompact) { 12730 out.println(); 12731 out.println("Total RSS by category:"); 12732 } 12733 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, false, false, false); 12734 } 12735 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0; 12736 if (!brief && !opts.oomOnly && !opts.isCompact) { 12737 pw.println(); 12738 pw.println("Total PSS by process:"); 12739 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, true, 12740 opts.dumpSwapPss, opts.mDumpPrivateDirty); 12741 pw.println(); 12742 } 12743 if (!opts.isCompact) { 12744 pw.println("Total PSS by OOM adjustment:"); 12745 } 12746 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, true, opts.dumpSwapPss, 12747 opts.mDumpPrivateDirty); 12748 if (!brief && !opts.oomOnly) { 12749 PrintWriter out = categoryPw != null ? categoryPw : pw; 12750 if (!opts.isCompact) { 12751 out.println(); 12752 out.println("Total PSS by category:"); 12753 } 12754 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, true, 12755 opts.dumpSwapPss, opts.mDumpPrivateDirty); 12756 } 12757 if (!opts.isCompact) { 12758 pw.println(); 12759 } 12760 MemInfoReader memInfo = new MemInfoReader(); 12761 memInfo.readMemInfo(); 12762 if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) { 12763 synchronized (mProcessStats.mLock) { 12764 final long cachedKb = memInfo.getCachedSizeKb(); 12765 final long freeKb = memInfo.getFreeSizeKb(); 12766 final long zramKb = memInfo.getZramTotalSizeKb(); 12767 final long kernelKb = memInfo.getKernelUsedSizeKb(); 12768 EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, 12769 kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024); 12770 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 12771 ss[INDEX_TOTAL_NATIVE_PSS]); 12772 } 12773 } 12774 if (!brief) { 12775 if (!opts.isCompact) { 12776 pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb())); 12777 pw.print(" (status "); 12778 mAppProfiler.dumpLastMemoryLevelLocked(pw); 12779 pw.print(" Free RAM: "); 12780 pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb() 12781 + memInfo.getFreeSizeKb())); 12782 pw.print(" ("); 12783 pw.print(stringifyKBSize(cachedPss)); 12784 pw.print(" cached pss + "); 12785 pw.print(stringifyKBSize(memInfo.getCachedSizeKb())); 12786 pw.print(" cached kernel + "); 12787 pw.print(stringifyKBSize(memInfo.getFreeSizeKb())); 12788 pw.println(" free)"); 12789 } else { 12790 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 12791 pw.print(cachedPss + memInfo.getCachedSizeKb() 12792 + memInfo.getFreeSizeKb()); pw.print(","); 12793 pw.println(ss[INDEX_TOTAL_PSS] - cachedPss); 12794 } 12795 } 12796 long kernelUsed = memInfo.getKernelUsedSizeKb(); 12797 final long ionHeap = Debug.getIonHeapsSizeKb(); 12798 final long ionPool = Debug.getIonPoolsSizeKb(); 12799 final long dmabufMapped = Debug.getDmabufMappedSizeKb(); 12800 if (ionHeap >= 0 && ionPool >= 0) { 12801 final long ionUnmapped = ionHeap - dmabufMapped; 12802 pw.print(" ION: "); 12803 pw.print(stringifyKBSize(ionHeap + ionPool)); 12804 pw.print(" ("); 12805 pw.print(stringifyKBSize(dmabufMapped)); 12806 pw.print(" mapped + "); 12807 pw.print(stringifyKBSize(ionUnmapped)); 12808 pw.print(" unmapped + "); 12809 pw.print(stringifyKBSize(ionPool)); 12810 pw.println(" pools)"); 12811 kernelUsed += ionUnmapped; 12812 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being 12813 // set on ION VMAs, however it might be included by the memtrack HAL. 12814 // Replace memtrack HAL reported Graphics category with mapped dmabufs 12815 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS]; 12816 ss[INDEX_TOTAL_PSS] += dmabufMapped; 12817 } else { 12818 final long totalExportedDmabuf = Debug.getDmabufTotalExportedKb(); 12819 if (totalExportedDmabuf >= 0) { 12820 final long dmabufUnmapped = totalExportedDmabuf - dmabufMapped; 12821 pw.print("DMA-BUF: "); 12822 pw.print(stringifyKBSize(totalExportedDmabuf)); 12823 pw.print(" ("); 12824 pw.print(stringifyKBSize(dmabufMapped)); 12825 pw.print(" mapped + "); 12826 pw.print(stringifyKBSize(dmabufUnmapped)); 12827 pw.println(" unmapped)"); 12828 // Account unmapped dmabufs as part of kernel memory allocations 12829 kernelUsed += dmabufUnmapped; 12830 // Replace memtrack HAL reported Graphics category with mapped dmabufs 12831 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS]; 12832 ss[INDEX_TOTAL_PSS] += dmabufMapped; 12833 } 12834 12835 // totalDmabufHeapExported is included in totalExportedDmabuf above and hence do not 12836 // need to be added to kernelUsed. 12837 final long totalDmabufHeapExported = Debug.getDmabufHeapTotalExportedKb(); 12838 if (totalDmabufHeapExported >= 0) { 12839 pw.print("DMA-BUF Heaps: "); 12840 pw.println(stringifyKBSize(totalDmabufHeapExported)); 12841 } 12842 12843 final long totalDmabufHeapPool = Debug.getDmabufHeapPoolsSizeKb(); 12844 if (totalDmabufHeapPool >= 0) { 12845 pw.print("DMA-BUF Heaps pool: "); 12846 pw.println(stringifyKBSize(totalDmabufHeapPool)); 12847 } 12848 } 12849 final long gpuUsage = Debug.getGpuTotalUsageKb(); 12850 if (gpuUsage >= 0) { 12851 final long gpuPrivateUsage = Debug.getGpuPrivateMemoryKb(); 12852 if (gpuPrivateUsage >= 0) { 12853 final long gpuDmaBufUsage = gpuUsage - gpuPrivateUsage; 12854 pw.print(" GPU: "); 12855 pw.print(stringifyKBSize(gpuUsage)); 12856 pw.print(" ("); 12857 pw.print(stringifyKBSize(gpuDmaBufUsage)); 12858 pw.print(" dmabuf + "); 12859 pw.print(stringifyKBSize(gpuPrivateUsage)); 12860 pw.println(" private)"); 12861 // Replace memtrack HAL reported GL category with private GPU allocations and 12862 // account it as part of kernel memory allocations 12863 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GL]; 12864 kernelUsed += gpuPrivateUsage; 12865 } else { 12866 pw.print(" GPU: "); pw.println(stringifyKBSize(gpuUsage)); 12867 } 12868 } 12869 12870 final long kernelCmaUsage = Debug.getKernelCmaUsageKb(); 12871 if (kernelCmaUsage >= 0) { 12872 pw.print(" Kernel CMA: "); 12873 pw.println(stringifyKBSize(kernelCmaUsage)); 12874 // CMA memory can be in one of the following four states: 12875 // 12876 // 1. Free, in which case it is accounted for as part of MemFree, which 12877 // is already considered in the lostRAM calculation below. 12878 // 12879 // 2. Allocated as part of a userspace allocated, in which case it is 12880 // already accounted for in the total PSS value that was computed. 12881 // 12882 // 3. Allocated for storing compressed memory (ZRAM) on Android kernels. 12883 // This is accounted for by calculating the amount of memory ZRAM 12884 // consumes and including it in the lostRAM calculuation. 12885 // 12886 // 4. Allocated by a kernel driver, in which case, it is currently not 12887 // attributed to any term that has been derived thus far. Since the 12888 // allocations come from a kernel driver, add it to kernelUsed. 12889 kernelUsed += kernelCmaUsage; 12890 } 12891 12892 // Note: ION/DMA-BUF heap pools are reclaimable and hence, they are included as part of 12893 // memInfo.getCachedSizeKb(). 12894 final long lostRAM = memInfo.getTotalSizeKb() 12895 - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS]) 12896 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 12897 // NR_SHMEM is subtracted twice (getCachedSizeKb() and getKernelUsedSizeKb()) 12898 + memInfo.getShmemSizeKb() 12899 - kernelUsed - memInfo.getZramTotalSizeKb(); 12900 if (!opts.isCompact) { 12901 pw.print(" Used RAM: "); pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss 12902 + kernelUsed)); pw.print(" ("); 12903 pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss)); 12904 pw.print(" used pss + "); 12905 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n"); 12906 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM)); 12907 } else { 12908 pw.print("lostram,"); pw.println(lostRAM); 12909 } 12910 if (!brief) { 12911 if (memInfo.getZramTotalSizeKb() != 0) { 12912 if (!opts.isCompact) { 12913 pw.print(" ZRAM: "); 12914 pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb())); 12915 pw.print(" physical used for "); 12916 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb() 12917 - memInfo.getSwapFreeSizeKb())); 12918 pw.print(" in swap ("); 12919 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb())); 12920 pw.println(" total swap)"); 12921 } else { 12922 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 12923 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 12924 pw.println(memInfo.getSwapFreeSizeKb()); 12925 } 12926 } 12927 final long[] ksm = getKsmInfo(); 12928 if (!opts.isCompact) { 12929 if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 12930 || ksm[KSM_VOLATILE] != 0) { 12931 pw.print(" KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING])); 12932 pw.print(" saved from shared "); 12933 pw.print(stringifyKBSize(ksm[KSM_SHARED])); 12934 pw.print(" "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED])); 12935 pw.print(" unshared; "); 12936 pw.print(stringifyKBSize( 12937 ksm[KSM_VOLATILE])); pw.println(" volatile"); 12938 } 12939 pw.print(" Tuning: "); 12940 pw.print(ActivityManager.staticGetMemoryClass()); 12941 pw.print(" (large "); 12942 pw.print(ActivityManager.staticGetLargeMemoryClass()); 12943 pw.print("), oom "); 12944 pw.print(stringifySize( 12945 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024)); 12946 pw.print(", restore limit "); 12947 pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb())); 12948 if (ActivityManager.isLowRamDeviceStatic()) { 12949 pw.print(" (low-ram)"); 12950 } 12951 if (ActivityManager.isHighEndGfx()) { 12952 pw.print(" (high-end-gfx)"); 12953 } 12954 pw.println(); 12955 } else { 12956 pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(","); 12957 pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]); 12958 pw.print(","); pw.println(ksm[KSM_VOLATILE]); 12959 pw.print("tuning,"); 12960 pw.print(ActivityManager.staticGetMemoryClass()); 12961 pw.print(','); 12962 pw.print(ActivityManager.staticGetLargeMemoryClass()); 12963 pw.print(','); 12964 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 12965 if (ActivityManager.isLowRamDeviceStatic()) { 12966 pw.print(",low-ram"); 12967 } 12968 if (ActivityManager.isHighEndGfx()) { 12969 pw.print(",high-end-gfx"); 12970 } 12971 pw.println(); 12972 } 12973 } 12974 } 12975 } 12976 12977 @NeverCompile // Avoid size overhead of debugging code. dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)12978 private final void dumpApplicationMemoryUsage(FileDescriptor fd, 12979 MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, 12980 ArrayList<ProcessRecord> procs) { 12981 final long uptimeMs = SystemClock.uptimeMillis(); 12982 final long realtimeMs = SystemClock.elapsedRealtime(); 12983 final long[] tmpLong = new long[3]; 12984 12985 if (procs == null) { 12986 // No Java processes. Maybe they want to print a native process. 12987 String proc = "N/A"; 12988 if (innerArgs.length > 0) { 12989 proc = innerArgs[0]; 12990 if (proc.charAt(0) != '-') { 12991 final ArrayList<ProcessCpuTracker.Stats> nativeProcs 12992 = new ArrayList<ProcessCpuTracker.Stats>(); 12993 updateCpuStatsNow(); 12994 int findPid = -1; 12995 try { 12996 findPid = Integer.parseInt(innerArgs[0]); 12997 } catch (NumberFormatException e) { 12998 } 12999 final int fFindPid = findPid; 13000 mAppProfiler.forAllCpuStats((st) -> { 13001 if (st.pid == fFindPid || (st.baseName != null 13002 && st.baseName.equals(innerArgs[0]))) { 13003 nativeProcs.add(st); 13004 } 13005 }); 13006 if (nativeProcs.size() > 0) { 13007 ProtoOutputStream proto = new ProtoOutputStream(fd); 13008 13009 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 13010 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 13011 Debug.MemoryInfo mi = null; 13012 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 13013 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 13014 final int pid = r.pid; 13015 13016 if (mi == null) { 13017 mi = new Debug.MemoryInfo(); 13018 } 13019 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 13020 if (!Debug.getMemoryInfo(pid, mi)) { 13021 continue; 13022 } 13023 } else { 13024 long pss = Debug.getPss(pid, tmpLong, null); 13025 if (pss == 0) { 13026 continue; 13027 } 13028 mi.nativePss = (int) pss; 13029 mi.nativePrivateDirty = (int) tmpLong[0]; 13030 mi.nativeRss = (int) tmpLong[2]; 13031 } 13032 13033 final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES); 13034 13035 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 13036 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName); 13037 13038 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 13039 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 13040 13041 proto.end(nToken); 13042 } 13043 13044 proto.flush(); 13045 return; 13046 } 13047 } 13048 } 13049 Log.d(TAG, "No process found for: " + innerArgs[0]); 13050 return; 13051 } 13052 13053 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 13054 opts.dumpDetails = true; 13055 } 13056 final int numProcs = procs.size(); 13057 final boolean collectNative = numProcs > 1 && !opts.packages; 13058 if (collectNative) { 13059 // If we are showing aggregations, also look for native processes to 13060 // include so that our aggregations are more accurate. 13061 updateCpuStatsNow(); 13062 } 13063 13064 ProtoOutputStream proto = new ProtoOutputStream(fd); 13065 13066 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 13067 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 13068 13069 final ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 13070 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 13071 final long[] ss = new long[INDEX_LAST]; 13072 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 13073 EmptyArray.LONG; 13074 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 13075 EmptyArray.LONG; 13076 long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 13077 EmptyArray.LONG; 13078 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13079 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13080 long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13081 13082 final long[] oomPss = new long[DUMP_MEM_OOM_LABEL.length]; 13083 final long[] oomSwapPss = new long[DUMP_MEM_OOM_LABEL.length]; 13084 final long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length]; 13085 final ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 13086 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 13087 13088 long cachedPss = 0; 13089 long cachedSwapPss = 0; 13090 boolean hasSwapPss = false; 13091 13092 Debug.MemoryInfo mi = null; 13093 for (int i = numProcs - 1; i >= 0; i--) { 13094 final ProcessRecord r = procs.get(i); 13095 final IApplicationThread thread; 13096 final int pid; 13097 final int oomAdj; 13098 final boolean hasActivities; 13099 synchronized (mProcLock) { 13100 thread = r.getThread(); 13101 pid = r.getPid(); 13102 oomAdj = r.mState.getSetAdjWithServices(); 13103 hasActivities = r.hasActivities(); 13104 } 13105 if (thread == null) { 13106 continue; 13107 } 13108 if (mi == null) { 13109 mi = new Debug.MemoryInfo(); 13110 } 13111 final int reportType; 13112 final long startTime; 13113 final long endTime; 13114 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 13115 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 13116 startTime = SystemClock.currentThreadTimeMillis(); 13117 if (!Debug.getMemoryInfo(pid, mi)) { 13118 continue; 13119 } 13120 endTime = SystemClock.currentThreadTimeMillis(); 13121 hasSwapPss = hasSwapPss || mi.hasSwappedOutPss; 13122 } else { 13123 reportType = ProcessStats.ADD_PSS_EXTERNAL; 13124 startTime = SystemClock.currentThreadTimeMillis(); 13125 long pss = Debug.getPss(pid, tmpLong, null); 13126 if (pss == 0) { 13127 continue; 13128 } 13129 mi.dalvikPss = (int) pss; 13130 endTime = SystemClock.currentThreadTimeMillis(); 13131 mi.dalvikPrivateDirty = (int) tmpLong[0]; 13132 mi.dalvikRss = (int) tmpLong[2]; 13133 } 13134 if (opts.dumpDetails) { 13135 if (opts.localOnly) { 13136 final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES); 13137 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY); 13138 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 13139 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName); 13140 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 13141 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 13142 proto.end(mToken); 13143 proto.end(aToken); 13144 } else { 13145 try { 13146 ByteTransferPipe tp = new ByteTransferPipe(); 13147 try { 13148 thread.dumpMemInfoProto(tp.getWriteFd(), 13149 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 13150 opts.dumpUnreachable, innerArgs); 13151 proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get()); 13152 } finally { 13153 tp.kill(); 13154 } 13155 } catch (IOException e) { 13156 Log.e(TAG, "Got IOException!", e); 13157 } catch (RemoteException e) { 13158 Log.e(TAG, "Got RemoteException!", e); 13159 } 13160 } 13161 } 13162 13163 final long myTotalPss = mi.getTotalPss(); 13164 final long myTotalUss = mi.getTotalUss(); 13165 final long myTotalRss = mi.getTotalRss(); 13166 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 13167 13168 synchronized (mProcLock) { 13169 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) { 13170 // Record this for posterity if the process has been stable. 13171 r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true, 13172 reportType, endTime - startTime); 13173 } 13174 } 13175 13176 if (!opts.isCheckinRequest && mi != null) { 13177 ss[INDEX_TOTAL_PSS] += myTotalPss; 13178 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 13179 ss[INDEX_TOTAL_RSS] += myTotalRss; 13180 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 13181 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 13182 myTotalSwapPss, myTotalRss, 0, pid, r.userId, hasActivities); 13183 procMems.add(pssItem); 13184 procMemsMap.put(pid, pssItem); 13185 13186 ss[INDEX_NATIVE_PSS] += mi.nativePss; 13187 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss; 13188 ss[INDEX_NATIVE_RSS] += mi.nativeRss; 13189 ss[INDEX_DALVIK_PSS] += mi.dalvikPss; 13190 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss; 13191 ss[INDEX_DALVIK_RSS] += mi.dalvikRss; 13192 for (int j=0; j<dalvikSubitemPss.length; j++) { 13193 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13194 dalvikSubitemSwapPss[j] += 13195 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13196 dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13197 } 13198 ss[INDEX_OTHER_PSS] += mi.otherPss; 13199 ss[INDEX_OTHER_RSS] += mi.otherRss; 13200 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss; 13201 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13202 long mem = mi.getOtherPss(j); 13203 miscPss[j] += mem; 13204 ss[INDEX_OTHER_PSS] -= mem; 13205 mem = mi.getOtherSwappedOutPss(j); 13206 miscSwapPss[j] += mem; 13207 ss[INDEX_OTHER_SWAP_PSS] -= mem; 13208 mem = mi.getOtherRss(j); 13209 miscRss[j] += mem; 13210 ss[INDEX_OTHER_RSS] -= mem; 13211 } 13212 13213 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 13214 cachedPss += myTotalPss; 13215 cachedSwapPss += myTotalSwapPss; 13216 } 13217 13218 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 13219 if (oomIndex == (oomPss.length - 1) 13220 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 13221 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 13222 oomPss[oomIndex] += myTotalPss; 13223 oomSwapPss[oomIndex] += myTotalSwapPss; 13224 if (oomProcs[oomIndex] == null) { 13225 oomProcs[oomIndex] = new ArrayList<MemItem>(); 13226 } 13227 oomProcs[oomIndex].add(pssItem); 13228 oomRss[oomIndex] += myTotalRss; 13229 break; 13230 } 13231 } 13232 } 13233 } 13234 13235 long nativeProcTotalPss = 0; 13236 13237 if (collectNative) { 13238 mi = null; 13239 final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1]; 13240 mAppProfiler.forAllCpuStats((st) -> { 13241 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 13242 if (memInfos[0] == null) { 13243 memInfos[0] = new Debug.MemoryInfo(); 13244 } 13245 final Debug.MemoryInfo info = memInfos[0]; 13246 if (!brief && !opts.oomOnly) { 13247 if (!Debug.getMemoryInfo(st.pid, info)) { 13248 return; 13249 } 13250 } else { 13251 long pss = Debug.getPss(st.pid, tmpLong, null); 13252 if (pss == 0) { 13253 return; 13254 } 13255 info.nativePss = (int) pss; 13256 info.nativePrivateDirty = (int) tmpLong[0]; 13257 info.nativeRss = (int) tmpLong[2]; 13258 } 13259 13260 final long myTotalPss = info.getTotalPss(); 13261 final long myTotalSwapPss = info.getTotalSwappedOutPss(); 13262 final long myTotalRss = info.getTotalRss(); 13263 ss[INDEX_TOTAL_PSS] += myTotalPss; 13264 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 13265 ss[INDEX_TOTAL_RSS] += myTotalRss; 13266 ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss; 13267 13268 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 13269 st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss, 0, 13270 st.pid, UserHandle.getUserId(st.uid), false); 13271 procMems.add(pssItem); 13272 13273 ss[INDEX_NATIVE_PSS] += info.nativePss; 13274 ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss; 13275 ss[INDEX_NATIVE_RSS] += info.nativeRss; 13276 ss[INDEX_DALVIK_PSS] += info.dalvikPss; 13277 ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss; 13278 ss[INDEX_DALVIK_RSS] += info.dalvikRss; 13279 for (int j = 0; j < dalvikSubitemPss.length; j++) { 13280 dalvikSubitemPss[j] += info.getOtherPss( 13281 Debug.MemoryInfo.NUM_OTHER_STATS + j); 13282 dalvikSubitemSwapPss[j] += 13283 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 13284 dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS 13285 + j); 13286 } 13287 ss[INDEX_OTHER_PSS] += info.otherPss; 13288 ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss; 13289 ss[INDEX_OTHER_RSS] += info.otherRss; 13290 for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13291 long mem = info.getOtherPss(j); 13292 miscPss[j] += mem; 13293 ss[INDEX_OTHER_PSS] -= mem; 13294 mem = info.getOtherSwappedOutPss(j); 13295 miscSwapPss[j] += mem; 13296 ss[INDEX_OTHER_SWAP_PSS] -= mem; 13297 mem = info.getOtherRss(j); 13298 miscRss[j] += mem; 13299 ss[INDEX_OTHER_RSS] -= mem; 13300 } 13301 oomPss[0] += myTotalPss; 13302 oomSwapPss[0] += myTotalSwapPss; 13303 if (oomProcs[0] == null) { 13304 oomProcs[0] = new ArrayList<MemItem>(); 13305 } 13306 oomProcs[0].add(pssItem); 13307 oomRss[0] += myTotalRss; 13308 } 13309 }); 13310 13311 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 13312 13313 catMems.add(new MemItem("Native", "Native", ss[INDEX_NATIVE_PSS], 13314 ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], 0, -1)); 13315 final int dalvikId = -2; 13316 catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS], 13317 ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], 0, dalvikId)); 13318 catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS], 13319 ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], 0, -3)); 13320 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13321 String label = Debug.MemoryInfo.getOtherLabel(j); 13322 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], 13323 miscRss[j], 0, j)); 13324 } 13325 if (dalvikSubitemPss.length > 0) { 13326 // Add dalvik subitems. 13327 for (MemItem memItem : catMems) { 13328 int memItemStart = 0, memItemEnd = 0; 13329 if (memItem.id == dalvikId) { 13330 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 13331 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 13332 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 13333 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 13334 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 13335 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 13336 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 13337 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 13338 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 13339 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 13340 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 13341 } else { 13342 continue; // No subitems, continue. 13343 } 13344 memItem.subitems = new ArrayList<MemItem>(); 13345 for (int j=memItemStart; j<=memItemEnd; j++) { 13346 final String name = Debug.MemoryInfo.getOtherLabel( 13347 Debug.MemoryInfo.NUM_OTHER_STATS + j); 13348 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 13349 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], 0, j)); 13350 } 13351 } 13352 } 13353 13354 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 13355 for (int j=0; j<oomPss.length; j++) { 13356 if (oomPss[j] != 0) { 13357 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 13358 : DUMP_MEM_OOM_LABEL[j]; 13359 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j], 0, 13360 DUMP_MEM_OOM_ADJ[j]); 13361 item.subitems = oomProcs[j]; 13362 oomMems.add(item); 13363 } 13364 } 13365 13366 if (!opts.oomOnly) { 13367 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_PROCESS, "proc", 13368 procMems, true, false, false); 13369 } 13370 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_OOM_ADJUSTMENT, "oom", 13371 oomMems, false, false, false); 13372 if (!brief && !opts.oomOnly) { 13373 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_CATEGORY, "cat", 13374 catMems, true, false, false); 13375 } 13376 13377 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0; 13378 if (!opts.oomOnly) { 13379 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc", 13380 procMems, true, true, opts.dumpSwapPss); 13381 } 13382 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom", 13383 oomMems, false, true, opts.dumpSwapPss); 13384 if (!brief && !opts.oomOnly) { 13385 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat", 13386 catMems, true, true, opts.dumpSwapPss); 13387 } 13388 MemInfoReader memInfo = new MemInfoReader(); 13389 memInfo.readMemInfo(); 13390 if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) { 13391 synchronized (mProcessStats.mLock) { 13392 final long cachedKb = memInfo.getCachedSizeKb(); 13393 final long freeKb = memInfo.getFreeSizeKb(); 13394 final long zramKb = memInfo.getZramTotalSizeKb(); 13395 final long kernelKb = memInfo.getKernelUsedSizeKb(); 13396 EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, 13397 kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024); 13398 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 13399 ss[INDEX_TOTAL_NATIVE_PSS]); 13400 } 13401 } 13402 if (!brief) { 13403 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb()); 13404 proto.write(MemInfoDumpProto.STATUS, mAppProfiler.getLastMemoryLevelLocked()); 13405 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss); 13406 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb()); 13407 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb()); 13408 } 13409 // CMA memory can be in one of the following four states: 13410 // 13411 // 1. Free, in which case it is accounted for as part of MemFree, which 13412 // is already considered in the lostRAM calculation below. 13413 // 13414 // 2. Allocated as part of a userspace allocated, in which case it is 13415 // already accounted for in the total PSS value that was computed. 13416 // 13417 // 3. Allocated for storing compressed memory (ZRAM) on Android Kernels. 13418 // This is accounted for by calculating hte amount of memory ZRAM 13419 // consumes and including it in the lostRAM calculation. 13420 // 13421 // 4. Allocated by a kernel driver, in which case, it is currently not 13422 // attributed to any term that has been derived thus far, so subtract 13423 // it from lostRAM. 13424 long kernelCmaUsage = Debug.getKernelCmaUsageKb(); 13425 if (kernelCmaUsage < 0) { 13426 kernelCmaUsage = 0; 13427 } 13428 long lostRAM = memInfo.getTotalSizeKb() 13429 - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS]) 13430 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 13431 // NR_SHMEM is subtracted twice (getCachedSizeKb() and getKernelUsedSizeKb()) 13432 + memInfo.getShmemSizeKb() 13433 - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb() 13434 - kernelCmaUsage; 13435 proto.write(MemInfoDumpProto.USED_PSS_KB, ss[INDEX_TOTAL_PSS] - cachedPss); 13436 proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb()); 13437 proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM); 13438 if (!brief) { 13439 if (memInfo.getZramTotalSizeKb() != 0) { 13440 proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb()); 13441 proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB, 13442 memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb()); 13443 proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb()); 13444 } 13445 final long[] ksm = getKsmInfo(); 13446 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]); 13447 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]); 13448 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]); 13449 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]); 13450 13451 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass()); 13452 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass()); 13453 proto.write(MemInfoDumpProto.OOM_KB, 13454 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024); 13455 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB, 13456 mProcessList.getCachedRestoreThresholdKb()); 13457 13458 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic()); 13459 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx()); 13460 } 13461 } 13462 13463 proto.flush(); 13464 } 13465 appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)13466 static void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, 13467 long memtrack, String name) { 13468 sb.append(" "); 13469 sb.append(ProcessList.makeOomAdjString(oomAdj, false)); 13470 sb.append(' '); 13471 sb.append(ProcessList.makeProcStateString(procState)); 13472 sb.append(' '); 13473 ProcessList.appendRamKb(sb, pss); 13474 sb.append(": "); 13475 sb.append(name); 13476 if (memtrack > 0) { 13477 sb.append(" ("); 13478 sb.append(stringifyKBSize(memtrack)); 13479 sb.append(" memtrack)"); 13480 } 13481 } 13482 appendMemInfo(StringBuilder sb, ProcessMemInfo mi)13483 static void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) { 13484 appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name); 13485 sb.append(" (pid "); 13486 sb.append(mi.pid); 13487 sb.append(") "); 13488 sb.append(mi.adjType); 13489 sb.append('\n'); 13490 if (mi.adjReason != null) { 13491 sb.append(" "); 13492 sb.append(mi.adjReason); 13493 sb.append('\n'); 13494 } 13495 } 13496 13497 /** 13498 * Searches array of arguments for the specified string 13499 * @param args array of argument strings 13500 * @param value value to search for 13501 * @return true if the value is contained in the array 13502 */ scanArgs(String[] args, String value)13503 private static boolean scanArgs(String[] args, String value) { 13504 if (args != null) { 13505 for (String arg : args) { 13506 if (value.equals(arg)) { 13507 return true; 13508 } 13509 } 13510 } 13511 return false; 13512 } 13513 13514 /** 13515 * Main code for cleaning up a process when it has gone away. This is 13516 * called both as a result of the process dying, or directly when stopping 13517 * a process when running in single process mode. 13518 * 13519 * @return Returns true if the given process has been restarted, so the 13520 * app that was passed in must remain on the process lists. 13521 */ 13522 @GuardedBy("this") cleanUpApplicationRecordLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, int index, boolean replacingPid, boolean fromBinderDied)13523 final boolean cleanUpApplicationRecordLocked(ProcessRecord app, int pid, 13524 boolean restarting, boolean allowRestart, int index, boolean replacingPid, 13525 boolean fromBinderDied) { 13526 boolean restart; 13527 synchronized (mProcLock) { 13528 if (index >= 0) { 13529 removeLruProcessLocked(app); 13530 ProcessList.remove(pid); 13531 } 13532 13533 // We don't want to unlinkDeathRecipient immediately, if it's not called from binder 13534 // and it's not isolated, as we'd need the signal to bookkeeping the dying process list. 13535 restart = app.onCleanupApplicationRecordLSP(mProcessStats, allowRestart, 13536 fromBinderDied || app.isolated /* unlinkDeath */); 13537 13538 // Cancel pending frozen task and clean up frozen record if there is any. 13539 mOomAdjuster.mCachedAppOptimizer.onCleanupApplicationRecordLocked(app); 13540 } 13541 mAppProfiler.onCleanupApplicationRecordLocked(app); 13542 mBroadcastQueue.onApplicationCleanupLocked(app); 13543 clearProcessForegroundLocked(app); 13544 mServices.killServicesLocked(app, allowRestart); 13545 mPhantomProcessList.onAppDied(pid); 13546 13547 // If the app is undergoing backup, tell the backup manager about it 13548 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 13549 if (backupTarget != null && pid == backupTarget.app.getPid()) { 13550 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App " 13551 + backupTarget.appInfo + " died during backup"); 13552 mHandler.post(() -> { 13553 LocalServices.getService(BackupManagerInternal.class).agentDisconnectedForUser( 13554 app.info.packageName, app.userId); 13555 }); 13556 } 13557 13558 mProcessList.scheduleDispatchProcessDiedLocked(pid, app.info.uid); 13559 13560 // If this is a preceding instance of another process instance 13561 allowRestart = mProcessList.handlePrecedingAppDiedLocked(app); 13562 13563 // If somehow this process was still waiting for the death of its predecessor, 13564 // (probably it's "killed" before starting for real), reset the bookkeeping. 13565 final ProcessRecord predecessor = app.mPredecessor; 13566 if (predecessor != null) { 13567 predecessor.mSuccessor = null; 13568 predecessor.mSuccessorStartRunnable = null; 13569 app.mPredecessor = null; 13570 } 13571 13572 // If the caller is restarting this app, then leave it in its 13573 // current lists and let the caller take care of it. 13574 if (restarting) { 13575 return false; 13576 } 13577 13578 if (!app.isPersistent() || app.isolated) { 13579 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 13580 "Removing non-persistent process during cleanup: " + app); 13581 if (!replacingPid) { 13582 mProcessList.removeProcessNameLocked(app.processName, app.uid, app); 13583 } 13584 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 13585 } else if (!app.isRemoved()) { 13586 // This app is persistent, so we need to keep its record around. 13587 // If it is not already on the pending app list, add it there 13588 // and start a new process for it. 13589 if (mPersistentStartingProcesses.indexOf(app) < 0) { 13590 mPersistentStartingProcesses.add(app); 13591 restart = true; 13592 } 13593 } 13594 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v( 13595 TAG_CLEANUP, "Clean-up removing on hold: " + app); 13596 mProcessesOnHold.remove(app); 13597 13598 mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController()); 13599 mProcessList.noteProcessDiedLocked(app); 13600 13601 if (restart && allowRestart && !app.isolated) { 13602 // We have components that still need to be running in the 13603 // process, so re-launch it. 13604 if (index < 0) { 13605 ProcessList.remove(pid); 13606 } 13607 13608 // Remove provider publish timeout because we will start a new timeout when the 13609 // restarted process is attaching (if the process contains launching providers). 13610 mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, app); 13611 13612 mProcessList.addProcessNameLocked(app); 13613 app.setPendingStart(false); 13614 mProcessList.startProcessLocked(app, new HostingRecord( 13615 HostingRecord.HOSTING_TYPE_RESTART, app.processName), 13616 ZYGOTE_POLICY_FLAG_EMPTY); 13617 return true; 13618 } else if (pid > 0 && pid != MY_PID) { 13619 // Goodbye! 13620 removePidLocked(pid, app); 13621 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 13622 mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_SOFT_MSG, app); 13623 mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_HARD_MSG, app); 13624 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 13625 if (app.isolated) { 13626 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 13627 } 13628 app.setPid(0); 13629 } 13630 return false; 13631 } 13632 13633 // ========================================================= 13634 // SERVICES 13635 // ========================================================= 13636 13637 @Override getServices(int maxNum, int flags)13638 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) { 13639 enforceNotIsolatedCaller("getServices"); 13640 13641 final int callingUid = Binder.getCallingUid(); 13642 final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission( 13643 INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED); 13644 final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices", 13645 Binder.getCallingPid(), callingUid); 13646 synchronized (this) { 13647 return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid, 13648 allowed, canInteractAcrossUsers); 13649 } 13650 } 13651 13652 @Override getRunningServiceControlPanel(ComponentName name)13653 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 13654 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 13655 final int callingUid = Binder.getCallingUid(); 13656 final int callingUserId = UserHandle.getUserId(callingUid); 13657 if (name == null || getPackageManagerInternal() 13658 .filterAppAccess(name.getPackageName(), callingUid, callingUserId)) { 13659 return null; 13660 } 13661 synchronized (this) { 13662 return mServices.getRunningServiceControlPanelLocked(name); 13663 } 13664 } 13665 13666 @Override logFgsApiBegin(@oregroundServiceApiType int apiType, int uid, int pid)13667 public void logFgsApiBegin(@ForegroundServiceApiType int apiType, 13668 int uid, int pid) { 13669 enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE, 13670 "logFgsApiBegin"); 13671 synchronized (this) { 13672 mServices.logFgsApiBeginLocked(apiType, uid, pid); 13673 } 13674 } 13675 13676 @Override logFgsApiEnd(@oregroundServiceApiType int apiType, int uid, int pid)13677 public void logFgsApiEnd(@ForegroundServiceApiType int apiType, 13678 int uid, int pid) { 13679 enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE, 13680 "logFgsApiEnd"); 13681 synchronized (this) { 13682 mServices.logFgsApiEndLocked(apiType, uid, pid); 13683 } 13684 } 13685 13686 @Override logFgsApiStateChanged(@oregroundServiceApiType int apiType, int state, int uid, int pid)13687 public void logFgsApiStateChanged(@ForegroundServiceApiType int apiType, 13688 int state, int uid, int pid) { 13689 enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE, 13690 "logFgsApiEvent"); 13691 synchronized (this) { 13692 mServices.logFgsApiStateChangedLocked(apiType, uid, pid, state); 13693 } 13694 } 13695 13696 @Override startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId)13697 public ComponentName startService(IApplicationThread caller, Intent service, 13698 String resolvedType, boolean requireForeground, String callingPackage, 13699 String callingFeatureId, int userId) 13700 throws TransactionTooLargeException { 13701 return startService(caller, service, resolvedType, requireForeground, callingPackage, 13702 callingFeatureId, userId, false /* isSdkSandboxService */, INVALID_UID, null, null); 13703 } 13704 startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)13705 private ComponentName startService(IApplicationThread caller, Intent service, 13706 String resolvedType, boolean requireForeground, String callingPackage, 13707 String callingFeatureId, int userId, boolean isSdkSandboxService, 13708 int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName) 13709 throws TransactionTooLargeException { 13710 enforceNotIsolatedCaller("startService"); 13711 enforceAllowedToStartOrBindServiceIfSdkSandbox(service); 13712 addCreatorToken(service, callingPackage); 13713 if (service != null) { 13714 // Refuse possible leaked file descriptors 13715 if (service.hasFileDescriptors()) { 13716 throw new IllegalArgumentException("File descriptors passed in Intent"); 13717 } 13718 // Remove existing mismatch flag so it can be properly updated later 13719 service.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH); 13720 } 13721 13722 if (callingPackage == null) { 13723 throw new IllegalArgumentException("callingPackage cannot be null"); 13724 } 13725 13726 if (isSdkSandboxService && instanceName == null) { 13727 throw new IllegalArgumentException("No instance name provided for SDK sandbox process"); 13728 } 13729 validateServiceInstanceName(instanceName); 13730 13731 if (DEBUG_SERVICE) 13732 Slog.v( 13733 TAG_SERVICE, 13734 "*** startService: " 13735 + service 13736 + " type=" 13737 + resolvedType 13738 + " fg=" 13739 + requireForeground); 13740 final int callingPid = Binder.getCallingPid(); 13741 final int callingUid = Binder.getCallingUid(); 13742 final long origId = Binder.clearCallingIdentity(); 13743 ComponentName res; 13744 try { 13745 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 13746 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startService: " 13747 + "intent=" + service + ", caller=" + callingPackage 13748 + ", fgRequired=" + requireForeground); 13749 } 13750 synchronized (this) { 13751 res = mServices.startServiceLocked(caller, service, 13752 resolvedType, callingPid, callingUid, 13753 requireForeground, callingPackage, callingFeatureId, userId, 13754 isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage, 13755 instanceName); 13756 } 13757 } finally { 13758 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 13759 Binder.restoreCallingIdentity(origId); 13760 } 13761 return res; 13762 } 13763 validateServiceInstanceName(String instanceName)13764 private void validateServiceInstanceName(String instanceName) { 13765 // Ensure that instanceName, which is caller provided, does not contain 13766 // unusual characters. 13767 if (instanceName != null) { 13768 if (!instanceName.matches("[a-zA-Z0-9_.]+")) { 13769 throw new IllegalArgumentException("Illegal instanceName"); 13770 } 13771 } 13772 } 13773 13774 @Override stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)13775 public int stopService(IApplicationThread caller, Intent service, 13776 String resolvedType, int userId) { 13777 return stopService(caller, service, resolvedType, userId, false /* isSdkSandboxService */, 13778 INVALID_UID, null, null); 13779 } 13780 stopService(IApplicationThread caller, Intent service, String resolvedType, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)13781 private int stopService(IApplicationThread caller, Intent service, String resolvedType, 13782 int userId, boolean isSdkSandboxService, 13783 int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName) { 13784 enforceNotIsolatedCaller("stopService"); 13785 // Refuse possible leaked file descriptors 13786 if (service != null && service.hasFileDescriptors() == true) { 13787 throw new IllegalArgumentException("File descriptors passed in Intent"); 13788 } 13789 13790 try { 13791 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 13792 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopService: " + service); 13793 } 13794 synchronized (this) { 13795 return mServices.stopServiceLocked(caller, service, resolvedType, userId, 13796 isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage, 13797 instanceName); 13798 } 13799 } finally { 13800 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 13801 } 13802 } 13803 13804 @Override peekService(Intent service, String resolvedType, String callingPackage)13805 public IBinder peekService(Intent service, String resolvedType, String callingPackage) { 13806 enforceNotIsolatedCaller("peekService"); 13807 // Refuse possible leaked file descriptors 13808 if (service != null && service.hasFileDescriptors() == true) { 13809 throw new IllegalArgumentException("File descriptors passed in Intent"); 13810 } 13811 13812 if (callingPackage == null) { 13813 throw new IllegalArgumentException("callingPackage cannot be null"); 13814 } 13815 13816 synchronized(this) { 13817 return mServices.peekServiceLocked(service, resolvedType, callingPackage); 13818 } 13819 } 13820 13821 @Override stopServiceToken(ComponentName className, IBinder token, int startId)13822 public boolean stopServiceToken(ComponentName className, IBinder token, 13823 int startId) { 13824 try { 13825 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 13826 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopServiceToken: " 13827 + (className != null ? className.toShortString() 13828 : ("from " + Binder.getCallingPid()))); 13829 } 13830 synchronized (this) { 13831 return mServices.stopServiceTokenLocked(className, token, startId); 13832 } 13833 } finally { 13834 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 13835 } 13836 } 13837 13838 @Override setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)13839 public void setServiceForeground(ComponentName className, IBinder token, 13840 int id, Notification notification, int flags, int foregroundServiceType) { 13841 synchronized(this) { 13842 mServices.setServiceForegroundLocked(className, token, id, notification, flags, 13843 foregroundServiceType); 13844 } 13845 } 13846 13847 @Override getForegroundServiceType(ComponentName className, IBinder token)13848 public int getForegroundServiceType(ComponentName className, IBinder token) { 13849 synchronized (this) { 13850 return mServices.getForegroundServiceTypeLocked(className, token); 13851 } 13852 } 13853 13854 @Override shouldServiceTimeOut(ComponentName className, IBinder token)13855 public boolean shouldServiceTimeOut(ComponentName className, IBinder token) { 13856 synchronized (this) { 13857 return mServices.shouldServiceTimeOutLocked(className, token); 13858 } 13859 } 13860 13861 @Override hasServiceTimeLimitExceeded(ComponentName className, IBinder token)13862 public boolean hasServiceTimeLimitExceeded(ComponentName className, IBinder token) { 13863 synchronized (this) { 13864 return mServices.hasServiceTimedOutLocked(className, token); 13865 } 13866 } 13867 13868 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)13869 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 13870 boolean requireFull, String name, String callerPackage) { 13871 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 13872 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 13873 } 13874 isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)13875 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 13876 String className, int flags) { 13877 boolean result = false; 13878 // For apps that don't have pre-defined UIDs, check for permission 13879 if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) { 13880 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 13881 if (ActivityManager.checkUidPermission( 13882 INTERACT_ACROSS_USERS, 13883 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 13884 ComponentName comp = new ComponentName(aInfo.packageName, className); 13885 String msg = "Permission Denial: Component " + comp.flattenToShortString() 13886 + " requests FLAG_SINGLE_USER, but app does not hold " 13887 + INTERACT_ACROSS_USERS; 13888 Slog.w(TAG, msg); 13889 throw new SecurityException(msg); 13890 } 13891 // Permission passed 13892 result = true; 13893 } 13894 } else if ("system".equals(componentProcessName)) { 13895 result = true; 13896 } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 13897 // Phone app and persistent apps are allowed to export singleuser providers. 13898 result = UserHandle.isSameApp(aInfo.uid, PHONE_UID) 13899 || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 13900 } 13901 if (DEBUG_MU) Slog.v(TAG_MU, 13902 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x" 13903 + Integer.toHexString(flags) + ") = " + result); 13904 return result; 13905 } 13906 isSystemUserOnly(int flags)13907 boolean isSystemUserOnly(int flags) { 13908 return android.multiuser.Flags.enableSystemUserOnlyForServicesAndProviders() 13909 && (flags & ServiceInfo.FLAG_SYSTEM_USER_ONLY) != 0; 13910 } 13911 13912 /** 13913 * Checks to see if the caller is in the same app as the singleton 13914 * component, or the component is in a special app. It allows special apps 13915 * to export singleton components but prevents exporting singleton 13916 * components for regular apps. 13917 */ isValidSingletonCall(int callingUid, int componentUid)13918 boolean isValidSingletonCall(int callingUid, int componentUid) { 13919 int componentAppId = UserHandle.getAppId(componentUid); 13920 return UserHandle.isSameApp(callingUid, componentUid) 13921 || componentAppId == SYSTEM_UID 13922 || componentAppId == PHONE_UID 13923 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 13924 == PackageManager.PERMISSION_GRANTED; 13925 } 13926 bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String callingPackage, int userId)13927 public int bindService(IApplicationThread caller, IBinder token, Intent service, 13928 String resolvedType, IServiceConnection connection, long flags, 13929 String callingPackage, int userId) throws TransactionTooLargeException { 13930 return bindServiceInstance(caller, token, service, resolvedType, connection, flags, 13931 null, callingPackage, userId); 13932 } 13933 13934 /** 13935 * Binds to a service with a given instanceName, creating it if it does not already exist. 13936 * If the instanceName field is not supplied, binding to the service occurs as usual. 13937 */ bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String instanceName, String callingPackage, int userId)13938 public int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, 13939 String resolvedType, IServiceConnection connection, long flags, String instanceName, 13940 String callingPackage, int userId) throws TransactionTooLargeException { 13941 return bindServiceInstance(caller, token, service, resolvedType, connection, flags, 13942 instanceName, false, INVALID_UID, null, null, callingPackage, userId); 13943 } 13944 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)13945 private int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, 13946 String resolvedType, IServiceConnection connection, long flags, String instanceName, 13947 boolean isSdkSandboxService, int sdkSandboxClientAppUid, 13948 String sdkSandboxClientAppPackage, 13949 IApplicationThread sdkSandboxClientApplicationThread, 13950 String callingPackage, int userId) 13951 throws TransactionTooLargeException { 13952 enforceNotIsolatedCaller("bindService"); 13953 enforceAllowedToStartOrBindServiceIfSdkSandbox(service); 13954 13955 if (service != null) { 13956 // Refuse possible leaked file descriptors 13957 if (service.hasFileDescriptors()) { 13958 throw new IllegalArgumentException("File descriptors passed in Intent"); 13959 } 13960 // Remove existing mismatch flag so it can be properly updated later 13961 service.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH); 13962 } 13963 13964 if (callingPackage == null) { 13965 throw new IllegalArgumentException("callingPackage cannot be null"); 13966 } 13967 13968 if (isSdkSandboxService && instanceName == null) { 13969 throw new IllegalArgumentException("No instance name provided for isolated process"); 13970 } 13971 13972 validateServiceInstanceName(instanceName); 13973 13974 addCreatorToken(service, callingPackage); 13975 try { 13976 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 13977 final ComponentName cn = service.getComponent(); 13978 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindService:" 13979 + (cn != null ? cn.toShortString() : service.getAction())); 13980 } 13981 synchronized (this) { 13982 return mServices.bindServiceLocked(caller, token, service, resolvedType, connection, 13983 flags, instanceName, isSdkSandboxService, sdkSandboxClientAppUid, 13984 sdkSandboxClientAppPackage, sdkSandboxClientApplicationThread, 13985 callingPackage, userId); 13986 } 13987 } finally { 13988 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 13989 } 13990 } 13991 updateServiceGroup(IServiceConnection connection, int group, int importance)13992 public void updateServiceGroup(IServiceConnection connection, int group, int importance) { 13993 synchronized (this) { 13994 mServices.updateServiceGroupLocked(connection, group, importance); 13995 } 13996 } 13997 unbindService(IServiceConnection connection)13998 public boolean unbindService(IServiceConnection connection) { 13999 try { 14000 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 14001 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "unbindService"); 14002 } 14003 synchronized (this) { 14004 return mServices.unbindServiceLocked(connection); 14005 } 14006 } finally { 14007 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 14008 } 14009 } 14010 publishService(IBinder token, Intent intent, IBinder service)14011 public void publishService(IBinder token, Intent intent, IBinder service) { 14012 // Refuse possible leaked file descriptors 14013 if (intent != null && intent.hasFileDescriptors() == true) { 14014 throw new IllegalArgumentException("File descriptors passed in Intent"); 14015 } 14016 14017 synchronized(this) { 14018 if (!(token instanceof ServiceRecord)) { 14019 throw new IllegalArgumentException("Invalid service token"); 14020 } 14021 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 14022 } 14023 } 14024 unbindFinished(IBinder token, Intent intent)14025 public void unbindFinished(IBinder token, Intent intent) { 14026 // Refuse possible leaked file descriptors 14027 if (intent != null && intent.hasFileDescriptors() == true) { 14028 throw new IllegalArgumentException("File descriptors passed in Intent"); 14029 } 14030 14031 synchronized(this) { 14032 mServices.unbindFinishedLocked((ServiceRecord)token, intent); 14033 } 14034 } 14035 14036 @Override serviceDoneExecuting(IBinder token, int type, int startId, int res, Intent intent)14037 public void serviceDoneExecuting(IBinder token, int type, int startId, int res, Intent intent) { 14038 synchronized(this) { 14039 if (!(token instanceof ServiceRecord)) { 14040 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token); 14041 throw new IllegalArgumentException("Invalid service token"); 14042 } 14043 mServices.serviceDoneExecutingLocked((ServiceRecord) token, type, startId, res, false, 14044 intent); 14045 } 14046 } 14047 14048 // ========================================================= 14049 // BACKUP AND RESTORE 14050 // ========================================================= 14051 14052 // Cause the target app to be launched if necessary and its backup agent 14053 // instantiated. The backup agent will invoke backupAgentCreated() on the 14054 // activity manager to announce its creation. bindBackupAgent(String packageName, int backupMode, int targetUserId, @BackupDestination int backupDestination, boolean useRestrictedMode)14055 public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId, 14056 @BackupDestination int backupDestination, boolean useRestrictedMode) { 14057 long startTimeNs = SystemClock.uptimeNanos(); 14058 if (DEBUG_BACKUP) { 14059 Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode 14060 + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid() 14061 + " uid = " + Process.myUid()); 14062 } 14063 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 14064 14065 // The instantiatedUserId is the user of the process the backup agent is started in. This is 14066 // different from the targetUserId which is the user whose data is to be backed up or 14067 // restored. This distinction is important for system-process packages that live in the 14068 // system user's process but backup/restore data for non-system users. 14069 // TODO (b/123688746): Handle all system-process packages with singleton check. 14070 boolean useSystemUser = PLATFORM_PACKAGE_NAME.equals(packageName) 14071 || getPackageManagerInternal().getSystemUiServiceComponent().getPackageName() 14072 .equals(packageName); 14073 final int instantiatedUserId = useSystemUser ? UserHandle.USER_SYSTEM : targetUserId; 14074 14075 IPackageManager pm = AppGlobals.getPackageManager(); 14076 ApplicationInfo app = null; 14077 try { 14078 app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId); 14079 } catch (RemoteException e) { 14080 // can't happen; package manager is process-local 14081 } 14082 if (app == null) { 14083 Slog.w(TAG, "Unable to bind backup agent for " + packageName); 14084 return false; 14085 } 14086 if (app.backupAgentName != null) { 14087 final ComponentName backupAgentName = new ComponentName( 14088 app.packageName, app.backupAgentName); 14089 int enableState = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 14090 try { 14091 enableState = pm.getComponentEnabledSetting(backupAgentName, instantiatedUserId); 14092 } catch (RemoteException e) { 14093 // can't happen; package manager is process-local 14094 } 14095 switch (enableState) { 14096 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED: 14097 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER: 14098 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED: 14099 Slog.w(TAG, "Unable to bind backup agent for " + backupAgentName 14100 + ", the backup agent component is disabled."); 14101 return false; 14102 14103 case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT: 14104 case PackageManager.COMPONENT_ENABLED_STATE_ENABLED: 14105 default: 14106 // Since there's no way to declare a backup agent disabled in the manifest, 14107 // assume the case COMPONENT_ENABLED_STATE_DEFAULT to be enabled. 14108 break; 14109 } 14110 } 14111 14112 int oldBackupUid; 14113 int newBackupUid; 14114 14115 synchronized(this) { 14116 if (android.app.Flags.appRestrictionsApi()) { 14117 try { 14118 final boolean wasStopped = mPackageManagerInt.isPackageStopped(app.packageName, 14119 UserHandle.getUserId(app.uid)); 14120 if (wasStopped) { 14121 noteAppRestrictionEnabled(app.packageName, app.uid, 14122 RESTRICTION_LEVEL_FORCE_STOPPED, false, 14123 RESTRICTION_REASON_DEFAULT, "restore", 14124 RESTRICTION_SOURCE_SYSTEM, 0L); 14125 } 14126 } catch (NameNotFoundException e) { 14127 Slog.w(TAG, "No such package", e); 14128 } 14129 } 14130 14131 // !!! TODO: currently no check here that we're already bound 14132 // Backup agent is now in use, its package can't be stopped. 14133 try { 14134 mPackageManagerInt.setPackageStoppedState( 14135 app.packageName, false, UserHandle.getUserId(app.uid)); 14136 } catch (IllegalArgumentException e) { 14137 Slog.w(TAG, "Failed trying to unstop package " 14138 + app.packageName + ": " + e); 14139 } 14140 14141 BackupRecord r = new BackupRecord(app, backupMode, targetUserId, backupDestination, 14142 useRestrictedMode); 14143 ComponentName hostingName = 14144 (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL 14145 || backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE) 14146 ? new ComponentName(app.packageName, app.backupAgentName) 14147 : new ComponentName("android", "FullBackupAgent"); 14148 14149 ProcessRecord proc = getProcessRecordLocked(app.processName, app.uid); 14150 boolean isProcessStarted = proc != null; 14151 if (!isProcessStarted) { 14152 proc = startProcessLocked(app.processName, app, 14153 false, 0, 14154 new HostingRecord(HostingRecord.HOSTING_TYPE_BACKUP, hostingName), 14155 ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false); 14156 } 14157 if (proc == null) { 14158 Slog.e(TAG, "Unable to start backup agent process " + r); 14159 return false; 14160 } 14161 mProcessList.getAppStartInfoTracker().handleProcessBackupStart(startTimeNs, proc, r, 14162 !isProcessStarted); 14163 14164 // If the app is a regular app (uid >= 10000) and not the system server or phone 14165 // process, etc, then mark it as being in full backup so that certain calls to the 14166 // process can be blocked. This is not reset to false anywhere because we kill the 14167 // process after the full backup is done and the ProcessRecord will vaporize anyway. 14168 if (UserHandle.isApp(app.uid) 14169 && backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL 14170 && r.useRestrictedMode) { 14171 proc.setInFullBackup(true); 14172 } 14173 r.app = proc; 14174 // TODO(b/369300367): This code suggests there could be a previous backup being 14175 // replaced here, but an OomAdjsuter update is not triggered on the previous app 14176 // (whose state will change from being removed from mBackupTargets). 14177 final BackupRecord backupTarget = mBackupTargets.get(targetUserId); 14178 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 14179 newBackupUid = proc.isInFullBackup() ? r.appInfo.uid : -1; 14180 mBackupTargets.put(targetUserId, r); 14181 mProcessStateController.setBackupTarget(proc, targetUserId); 14182 14183 proc.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP); 14184 14185 // Try not to kill the process during backup 14186 updateOomAdjLocked(proc, OOM_ADJ_REASON_BACKUP); 14187 14188 // If the process is already attached, schedule the creation of the backup agent now. 14189 // If it is not yet live, this will be done when it attaches to the framework. 14190 final IApplicationThread thread = proc.getThread(); 14191 if (thread != null) { 14192 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc); 14193 try { 14194 thread.scheduleCreateBackupAgent(app, backupMode, targetUserId, 14195 backupDestination); 14196 } catch (RemoteException e) { 14197 // Will time out on the backup manager side 14198 } 14199 } else { 14200 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach"); 14201 } 14202 // Invariants: at this point, the target app process exists and the application 14203 // is either already running or in the process of coming up. mBackupTarget and 14204 // mBackupAppName describe the app, so that when it binds back to the AM we 14205 // know that it's scheduled for a backup-agent operation. 14206 } 14207 14208 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14209 if (oldBackupUid != -1) { 14210 js.removeBackingUpUid(oldBackupUid); 14211 } 14212 if (newBackupUid != -1) { 14213 js.addBackingUpUid(newBackupUid); 14214 } 14215 14216 return true; 14217 } 14218 clearPendingBackup(int userId)14219 private void clearPendingBackup(int userId) { 14220 if (DEBUG_BACKUP) { 14221 Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = " 14222 + Binder.getCallingUid() + " uid = " + Process.myUid()); 14223 } 14224 14225 synchronized (this) { 14226 final int indexOfKey = mBackupTargets.indexOfKey(userId); 14227 if (indexOfKey >= 0) { 14228 final BackupRecord backupTarget = mBackupTargets.valueAt(indexOfKey); 14229 if (backupTarget != null && backupTarget.app != null) { 14230 backupTarget.app.mProfile.clearHostingComponentType( 14231 HOSTING_COMPONENT_TYPE_BACKUP); 14232 } 14233 mBackupTargets.removeAt(indexOfKey); 14234 } 14235 mProcessStateController.stopBackupTarget(userId); 14236 } 14237 14238 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14239 js.clearAllBackingUpUids(); 14240 } 14241 14242 // A backup agent has just come up 14243 @Override backupAgentCreated(String agentPackageName, IBinder agent, int userId)14244 public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) { 14245 final int callingUid = Binder.getCallingUid(); 14246 enforceCallingPackage(agentPackageName, callingUid); 14247 14248 // Resolve the target user id and enforce permissions. 14249 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, 14250 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null); 14251 if (DEBUG_BACKUP) { 14252 Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent 14253 + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId 14254 + " callingUid = " + callingUid + " uid = " + Process.myUid()); 14255 } 14256 14257 synchronized(this) { 14258 final BackupRecord backupTarget = mBackupTargets.get(userId); 14259 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 14260 if (!agentPackageName.equals(backupAppName)) { 14261 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 14262 return; 14263 } 14264 } 14265 14266 final long oldIdent = Binder.clearCallingIdentity(); 14267 try { 14268 LocalServices.getService(BackupManagerInternal.class).agentConnectedForUser( 14269 agentPackageName, userId, agent); 14270 } catch (Exception e) { 14271 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 14272 e.printStackTrace(); 14273 } finally { 14274 Binder.restoreCallingIdentity(oldIdent); 14275 } 14276 } 14277 14278 // done with this agent unbindBackupAgent(ApplicationInfo appInfo)14279 public void unbindBackupAgent(ApplicationInfo appInfo) { 14280 if (DEBUG_BACKUP) { 14281 Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = " 14282 + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = " 14283 + Process.myUid()); 14284 } 14285 14286 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent"); 14287 if (appInfo == null) { 14288 Slog.w(TAG, "unbind backup agent for null app"); 14289 return; 14290 } 14291 14292 int oldBackupUid; 14293 14294 final int userId = UserHandle.getUserId(appInfo.uid); 14295 synchronized(this) { 14296 final BackupRecord backupTarget = mBackupTargets.get(userId); 14297 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 14298 try { 14299 if (backupAppName == null) { 14300 Slog.w(TAG, "Unbinding backup agent with no active backup"); 14301 return; 14302 } 14303 14304 if (!backupAppName.equals(appInfo.packageName)) { 14305 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 14306 return; 14307 } 14308 14309 // Not backing this app up any more; reset its OOM adjustment 14310 final ProcessRecord proc = backupTarget.app; 14311 // TODO(b/369300367): Triggering the update before the state is actually set 14312 // seems wrong. 14313 updateOomAdjLocked(proc, OOM_ADJ_REASON_BACKUP); 14314 proc.setInFullBackup(false); 14315 proc.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP); 14316 14317 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 14318 14319 // If the app crashed during backup, 'thread' will be null here 14320 final IApplicationThread thread = proc.getThread(); 14321 if (thread != null) { 14322 try { 14323 thread.scheduleDestroyBackupAgent(appInfo, userId); 14324 } catch (Exception e) { 14325 Slog.e(TAG, "Exception when unbinding backup agent:"); 14326 e.printStackTrace(); 14327 } 14328 } 14329 } finally { 14330 mBackupTargets.delete(userId); 14331 mProcessStateController.stopBackupTarget(userId); 14332 } 14333 } 14334 14335 if (oldBackupUid != -1) { 14336 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 14337 js.removeBackingUpUid(oldBackupUid); 14338 } 14339 } 14340 14341 // ========================================================= 14342 // BROADCASTS 14343 // ========================================================= 14344 14345 /** 14346 * @deprecated Use {@link #registerReceiverWithFeature} 14347 */ 14348 @Deprecated registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)14349 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 14350 IIntentReceiver receiver, IntentFilter filter, String permission, int userId, 14351 int flags) { 14352 return registerReceiverWithFeature(caller, callerPackage, null, null, 14353 receiver, filter, permission, userId, flags); 14354 } 14355 registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)14356 public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage, 14357 String callerFeatureId, String receiverId, IIntentReceiver receiver, 14358 IntentFilter filter, String permission, int userId, int flags) { 14359 return mBroadcastController.registerReceiverWithFeature(caller, callerPackage, 14360 callerFeatureId, receiverId, receiver, filter, permission, userId, flags); 14361 } 14362 unregisterReceiver(IIntentReceiver receiver)14363 public void unregisterReceiver(IIntentReceiver receiver) { 14364 mBroadcastController.unregisterReceiver(receiver); 14365 } 14366 getRegisteredIntentFilters(IIntentReceiver receiver)14367 public List<IntentFilter> getRegisteredIntentFilters(IIntentReceiver receiver) { 14368 return mBroadcastController.getRegisteredIntentFilters(receiver); 14369 } 14370 14371 @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)14372 final int broadcastIntentLocked(ProcessRecord callerApp, 14373 String callerPackage, String callerFeatureId, Intent intent, String resolvedType, 14374 IIntentReceiver resultTo, int resultCode, String resultData, 14375 Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, 14376 String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered, 14377 boolean sticky, int callingPid, 14378 int callingUid, int realCallingUid, int realCallingPid, int userId) { 14379 return mBroadcastController.broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, 14380 intent, resolvedType, null, resultTo, resultCode, resultData, resultExtras, 14381 requiredPermissions, excludedPermissions, excludedPackages, appOp, bOptions, 14382 ordered, sticky, callingPid, callingUid, realCallingUid, realCallingPid, userId, 14383 BackgroundStartPrivileges.NONE, 14384 null /* broadcastAllowList */, null /* filterExtrasForReceiver */); 14385 } 14386 14387 /** 14388 * @deprecated Use {@link #broadcastIntentWithFeature} 14389 */ 14390 @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)14391 public final int broadcastIntent(IApplicationThread caller, 14392 Intent intent, String resolvedType, IIntentReceiver resultTo, 14393 int resultCode, String resultData, Bundle resultExtras, 14394 String[] requiredPermissions, int appOp, Bundle bOptions, 14395 boolean serialized, boolean sticky, int userId) { 14396 return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode, 14397 resultData, resultExtras, requiredPermissions, null, null, appOp, bOptions, 14398 serialized, sticky, userId); 14399 } 14400 14401 @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)14402 public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, 14403 Intent intent, String resolvedType, IIntentReceiver resultTo, 14404 int resultCode, String resultData, Bundle resultExtras, 14405 String[] requiredPermissions, String[] excludedPermissions, 14406 String[] excludedPackages, int appOp, Bundle bOptions, 14407 boolean serialized, boolean sticky, int userId) { 14408 return mBroadcastController.broadcastIntentWithFeature(caller, callingFeatureId, intent, 14409 resolvedType, resultTo, resultCode, resultData, resultExtras, requiredPermissions, 14410 excludedPermissions, excludedPackages, appOp, bOptions, serialized, sticky, userId); 14411 } 14412 14413 @Override unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)14414 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 14415 mBroadcastController.unbroadcastIntent(caller, intent, userId); 14416 } 14417 finishReceiver(IBinder caller, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)14418 public void finishReceiver(IBinder caller, int resultCode, String resultData, 14419 Bundle resultExtras, boolean resultAbort, int flags) { 14420 mBroadcastController.finishReceiver(caller, resultCode, resultData, resultExtras, 14421 resultAbort, flags); 14422 } 14423 14424 @VisibleForTesting getStickyBroadcastsForTest(String action, int userId)14425 ArrayList<BroadcastController.StickyBroadcast> getStickyBroadcastsForTest(String action, 14426 int userId) { 14427 return mBroadcastController.getStickyBroadcastsForTest(action, userId); 14428 } 14429 notifyBroadcastFinishedLocked(@onNull BroadcastRecord original)14430 final void notifyBroadcastFinishedLocked(@NonNull BroadcastRecord original) { 14431 mBroadcastController.notifyBroadcastFinishedLocked(original); 14432 } 14433 addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)14434 final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount, 14435 int skipCount, long dispatchTime) { 14436 mBroadcastController.addBroadcastStatLocked(action, srcPackage, receiveCount, skipCount, 14437 dispatchTime); 14438 } 14439 addBackgroundCheckViolationLocked(String action, String targetPackage)14440 final void addBackgroundCheckViolationLocked(String action, String targetPackage) { 14441 mBroadcastController.addBackgroundCheckViolationLocked(action, targetPackage); 14442 } 14443 removeReceiverLocked(ReceiverList rl)14444 void removeReceiverLocked(ReceiverList rl) { 14445 mBroadcastController.removeReceiverLocked(rl); 14446 } 14447 14448 // ========================================================= 14449 // INSTRUMENTATION 14450 // ========================================================= 14451 startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)14452 public boolean startInstrumentation(ComponentName className, 14453 String profileFile, int flags, Bundle arguments, 14454 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 14455 int userId, String abiOverride) { 14456 enforceNotIsolatedCaller("startInstrumentation"); 14457 final int callingUid = Binder.getCallingUid(); 14458 final int callingPid = Binder.getCallingPid(); 14459 userId = mUserController.handleIncomingUser(callingPid, callingUid, 14460 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 14461 // Refuse possible leaked file descriptors 14462 if (arguments != null && arguments.hasFileDescriptors()) { 14463 throw new IllegalArgumentException("File descriptors passed in Bundle"); 14464 } 14465 final IPackageManager pm = AppGlobals.getPackageManager(); 14466 14467 synchronized(this) { 14468 InstrumentationInfo ii = null; 14469 ApplicationInfo ai = null; 14470 14471 boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0; 14472 14473 try { 14474 ii = pm.getInstrumentationInfoAsUser(className, STOCK_PM_FLAGS, userId); 14475 if (ii == null) { 14476 reportStartInstrumentationFailureLocked(watcher, className, 14477 "Unable to find instrumentation info for: " + className); 14478 return false; 14479 } 14480 ai = pm.getApplicationInfo(ii.targetPackage, STOCK_PM_FLAGS, userId); 14481 if (ai == null) { 14482 reportStartInstrumentationFailureLocked(watcher, className, 14483 "Unable to find instrumentation target package: " + ii.targetPackage); 14484 return false; 14485 } 14486 } catch (RemoteException e) { 14487 } 14488 14489 if (ii.targetPackage.equals("android")) { 14490 if (!noRestart) { 14491 reportStartInstrumentationFailureLocked(watcher, className, 14492 "Cannot instrument system server without 'no-restart'"); 14493 return false; 14494 } 14495 } else if (!ai.hasCode()) { 14496 reportStartInstrumentationFailureLocked(watcher, className, 14497 "Instrumentation target has no code: " + ii.targetPackage); 14498 return false; 14499 } 14500 14501 int match = SIGNATURE_NO_MATCH; 14502 try { 14503 match = pm.checkSignatures(ii.targetPackage, ii.packageName, userId); 14504 } catch (RemoteException e) { 14505 } 14506 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 14507 if (Build.IS_DEBUGGABLE && (callingUid == Process.ROOT_UID) 14508 && (flags & INSTR_FLAG_ALWAYS_CHECK_SIGNATURE) == 0) { 14509 Slog.w(TAG, "Instrumentation test " + ii.packageName 14510 + " doesn't have a signature matching the target " + ii.targetPackage 14511 + ", which would not be allowed on the production Android builds"); 14512 } else { 14513 String msg = "Permission Denial: starting instrumentation " 14514 + className + " from pid=" 14515 + Binder.getCallingPid() 14516 + ", uid=" + Binder.getCallingUid() 14517 + " not allowed because package " + ii.packageName 14518 + " does not have a signature matching the target " 14519 + ii.targetPackage; 14520 reportStartInstrumentationFailureLocked(watcher, className, msg); 14521 throw new SecurityException(msg); 14522 } 14523 } 14524 14525 if (!Build.IS_DEBUGGABLE && callingUid != ROOT_UID && callingUid != SHELL_UID 14526 && callingUid != SYSTEM_UID && !hasActiveInstrumentationLocked(callingPid)) { 14527 // If it's not debug build and not called from root/shell/system uid, reject it. 14528 final String msg = "Permission Denial: instrumentation test " 14529 + className + " from pid=" + callingPid + ", uid=" + callingUid 14530 + ", pkgName=" + mInternal.getPackageNameByPid(callingPid) 14531 + " not allowed because it's not started from SHELL"; 14532 Slog.wtfQuiet(TAG, msg); 14533 reportStartInstrumentationFailureLocked(watcher, className, msg); 14534 throw new SecurityException(msg); 14535 } 14536 14537 boolean disableHiddenApiChecks = ai.usesNonSdkApi() 14538 || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0; 14539 boolean disableTestApiChecks = disableHiddenApiChecks 14540 || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0; 14541 14542 if (disableHiddenApiChecks || disableTestApiChecks) { 14543 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS, 14544 "disable hidden API checks"); 14545 } 14546 14547 if ((flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_SANDBOX) != 0) { 14548 return startInstrumentationOfSdkSandbox( 14549 className, 14550 profileFile, 14551 arguments, 14552 watcher, 14553 uiAutomationConnection, 14554 userId, 14555 abiOverride, 14556 ii, 14557 ai, 14558 noRestart, 14559 disableHiddenApiChecks, 14560 disableTestApiChecks, 14561 (flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_IN_SANDBOX) != 0); 14562 } 14563 14564 ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); 14565 activeInstr.mClass = className; 14566 String defProcess = ai.processName;; 14567 if (ii.targetProcesses == null) { 14568 activeInstr.mTargetProcesses = new String[]{ai.processName}; 14569 } else if (ii.targetProcesses.equals("*")) { 14570 activeInstr.mTargetProcesses = new String[0]; 14571 } else { 14572 activeInstr.mTargetProcesses = ii.targetProcesses.split(","); 14573 defProcess = activeInstr.mTargetProcesses[0]; 14574 } 14575 activeInstr.mTargetInfo = ai; 14576 activeInstr.mProfileFile = profileFile; 14577 activeInstr.mArguments = arguments; 14578 activeInstr.mWatcher = watcher; 14579 activeInstr.mUiAutomationConnection = uiAutomationConnection; 14580 activeInstr.mResultClass = className; 14581 activeInstr.mHasBackgroundActivityStartsPermission = checkPermission( 14582 START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid) 14583 == PackageManager.PERMISSION_GRANTED; 14584 activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission( 14585 START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid) 14586 == PackageManager.PERMISSION_GRANTED; 14587 activeInstr.mNoRestart = noRestart; 14588 14589 final long origId = Binder.clearCallingIdentity(); 14590 14591 ProcessRecord app; 14592 synchronized (mProcLock) { 14593 if (noRestart) { 14594 app = getProcessRecordLocked(ai.processName, ai.uid); 14595 } else { 14596 // Instrumentation can kill and relaunch even persistent processes 14597 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, 14598 false, userId, "start instr"); 14599 // Inform usage stats to make the target package active 14600 if (mUsageStatsService != null) { 14601 mUsageStatsService.reportEvent(ii.targetPackage, userId, 14602 UsageEvents.Event.SYSTEM_INTERACTION); 14603 } 14604 app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks, 14605 disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY); 14606 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 14607 } 14608 14609 mProcessStateController.setActiveInstrumentation(app, activeInstr); 14610 activeInstr.mFinished = false; 14611 activeInstr.mSourceUid = callingUid; 14612 activeInstr.mRunningProcesses.add(app); 14613 if (!mActiveInstrumentation.contains(activeInstr)) { 14614 mActiveInstrumentation.add(activeInstr); 14615 } 14616 } 14617 14618 if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) { 14619 // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with 14620 // --no-isolated-storage flag. 14621 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid, 14622 ii.packageName, AppOpsManager.MODE_ALLOWED); 14623 } 14624 Binder.restoreCallingIdentity(origId); 14625 14626 if (noRestart) { 14627 instrumentWithoutRestart(activeInstr, ai); 14628 } 14629 } 14630 14631 return true; 14632 } 14633 14634 @GuardedBy("this") hasActiveInstrumentationLocked(int pid)14635 private boolean hasActiveInstrumentationLocked(int pid) { 14636 if (pid == 0) { 14637 return false; 14638 } 14639 synchronized (mPidsSelfLocked) { 14640 ProcessRecord process = mPidsSelfLocked.get(pid); 14641 return process != null && process.getActiveInstrumentation() != null; 14642 } 14643 } 14644 14645 @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)14646 private boolean startInstrumentationOfSdkSandbox( 14647 ComponentName className, 14648 String profileFile, 14649 Bundle arguments, 14650 IInstrumentationWatcher watcher, 14651 IUiAutomationConnection uiAutomationConnection, 14652 int userId, 14653 String abiOverride, 14654 InstrumentationInfo instrumentationInfo, 14655 ApplicationInfo sdkSandboxClientAppInfo, 14656 boolean noRestart, 14657 boolean disableHiddenApiChecks, 14658 boolean disableTestApiChecks, 14659 boolean isSdkInSandbox) { 14660 14661 if (noRestart) { 14662 reportStartInstrumentationFailureLocked( 14663 watcher, 14664 className, 14665 "Instrumenting sdk sandbox with --no-restart flag is not supported"); 14666 return false; 14667 } 14668 14669 final SdkSandboxManagerLocal sandboxManagerLocal = 14670 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 14671 if (sandboxManagerLocal == null) { 14672 reportStartInstrumentationFailureLocked( 14673 watcher, className, "Can't locate SdkSandboxManagerLocal"); 14674 return false; 14675 } 14676 14677 final ApplicationInfo sdkSandboxInfo; 14678 final String processName; 14679 try { 14680 if (sdkSandboxInstrumentationInfo()) { 14681 sdkSandboxInfo = 14682 sandboxManagerLocal.getSdkSandboxApplicationInfoForInstrumentation( 14683 sdkSandboxClientAppInfo, isSdkInSandbox); 14684 processName = sdkSandboxInfo.processName; 14685 } else { 14686 final PackageManager pm = mContext.getPackageManager(); 14687 sdkSandboxInfo = 14688 pm.getApplicationInfoAsUser(pm.getSdkSandboxPackageName(), 0, userId); 14689 processName = 14690 sandboxManagerLocal.getSdkSandboxProcessNameForInstrumentation( 14691 sdkSandboxClientAppInfo); 14692 sdkSandboxInfo.uid = Process.toSdkSandboxUid(sdkSandboxClientAppInfo.uid); 14693 } 14694 } catch (NameNotFoundException e) { 14695 reportStartInstrumentationFailureLocked( 14696 watcher, className, "Can't find SdkSandbox package"); 14697 return false; 14698 } 14699 14700 ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); 14701 activeInstr.mClass = className; 14702 activeInstr.mTargetProcesses = new String[]{processName}; 14703 activeInstr.mTargetInfo = sdkSandboxInfo; 14704 activeInstr.mIsSdkInSandbox = isSdkInSandbox; 14705 activeInstr.mProfileFile = profileFile; 14706 activeInstr.mArguments = arguments; 14707 activeInstr.mWatcher = watcher; 14708 activeInstr.mUiAutomationConnection = uiAutomationConnection; 14709 activeInstr.mResultClass = className; 14710 activeInstr.mHasBackgroundActivityStartsPermission = 14711 isSdkInSandbox 14712 // TODO(b/261864298): consider using START_ACTIVITIES_FROM_BACKGROUND. 14713 && checkPermission( 14714 android.Manifest.permission 14715 .START_ACTIVITIES_FROM_SDK_SANDBOX, 14716 Binder.getCallingPid(), 14717 Binder.getCallingUid()) 14718 == PackageManager.PERMISSION_GRANTED; 14719 activeInstr.mHasBackgroundForegroundServiceStartsPermission = false; 14720 // Instrumenting sdk sandbox without a restart is not supported 14721 activeInstr.mNoRestart = false; 14722 14723 final int callingUid = Binder.getCallingUid(); 14724 final long token = Binder.clearCallingIdentity(); 14725 try { 14726 sandboxManagerLocal.notifyInstrumentationStarted( 14727 sdkSandboxClientAppInfo.packageName, sdkSandboxClientAppInfo.uid); 14728 synchronized (mProcLock) { 14729 // Kill the package sdk sandbox process belong to. At this point sdk sandbox is 14730 // already killed. 14731 forceStopPackageLocked( 14732 instrumentationInfo.targetPackage, 14733 /* appId= */ -1, 14734 /* callerWillRestart= */ true, 14735 /* purgeCache= */ false, 14736 /* doIt= */ true, 14737 /* evenPersistent= */ true, 14738 /* uninstalling= */ false, 14739 /* packageStateStopped= */ false, 14740 userId, 14741 "start instr"); 14742 14743 ProcessRecord app = addAppLocked( 14744 sdkSandboxInfo, 14745 processName, 14746 /* isolated= */ false, 14747 /* isSdkSandbox= */ true, 14748 sdkSandboxInfo.uid, 14749 sdkSandboxClientAppInfo.packageName, 14750 disableHiddenApiChecks, 14751 disableTestApiChecks, 14752 abiOverride, 14753 ZYGOTE_POLICY_FLAG_EMPTY); 14754 14755 mProcessStateController.setActiveInstrumentation(app, activeInstr); 14756 activeInstr.mFinished = false; 14757 activeInstr.mSourceUid = callingUid; 14758 activeInstr.mRunningProcesses.add(app); 14759 if (!mActiveInstrumentation.contains(activeInstr)) { 14760 mActiveInstrumentation.add(activeInstr); 14761 } 14762 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 14763 } 14764 } finally { 14765 Binder.restoreCallingIdentity(token); 14766 } 14767 14768 return true; 14769 } 14770 instrumentWithoutRestart(ActiveInstrumentation activeInstr, ApplicationInfo targetInfo)14771 private void instrumentWithoutRestart(ActiveInstrumentation activeInstr, 14772 ApplicationInfo targetInfo) { 14773 ProcessRecord pr; 14774 synchronized (this) { 14775 pr = getProcessRecordLocked(targetInfo.processName, targetInfo.uid); 14776 } 14777 14778 try { 14779 pr.getThread().instrumentWithoutRestart( 14780 activeInstr.mClass, 14781 activeInstr.mArguments, 14782 activeInstr.mWatcher, 14783 activeInstr.mUiAutomationConnection, 14784 targetInfo); 14785 } catch (RemoteException e) { 14786 Slog.i(TAG, "RemoteException from instrumentWithoutRestart", e); 14787 } 14788 } 14789 isCallerShell()14790 private boolean isCallerShell() { 14791 final int callingUid = Binder.getCallingUid(); 14792 return callingUid == SHELL_UID || callingUid == ROOT_UID; 14793 } 14794 14795 /** 14796 * Report errors that occur while attempting to start Instrumentation. Always writes the 14797 * error to the logs, but if somebody is watching, send the report there too. This enables 14798 * the "am" command to report errors with more information. 14799 * 14800 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 14801 * @param cn The component name of the instrumentation. 14802 * @param report The error report. 14803 */ reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)14804 private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, 14805 ComponentName cn, String report) { 14806 Slog.w(TAG, report); 14807 if (watcher != null) { 14808 Bundle results = new Bundle(); 14809 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 14810 results.putString("Error", report); 14811 mInstrumentationReporter.reportStatus(watcher, cn, -1, results); 14812 } 14813 } 14814 addInstrumentationResultsLocked(ProcessRecord app, Bundle results)14815 void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) { 14816 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 14817 if (instr == null) { 14818 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 14819 return; 14820 } 14821 14822 if (!instr.mFinished && results != null) { 14823 if (instr.mCurResults == null) { 14824 instr.mCurResults = new Bundle(results); 14825 } else { 14826 instr.mCurResults.putAll(results); 14827 } 14828 } 14829 } 14830 addInstrumentationResults(IApplicationThread target, Bundle results)14831 public void addInstrumentationResults(IApplicationThread target, Bundle results) { 14832 int userId = UserHandle.getCallingUserId(); 14833 // Refuse possible leaked file descriptors 14834 if (results != null && results.hasFileDescriptors()) { 14835 throw new IllegalArgumentException("File descriptors passed in Intent"); 14836 } 14837 14838 synchronized(this) { 14839 ProcessRecord app = getRecordForAppLOSP(target); 14840 if (app == null) { 14841 Slog.w(TAG, "addInstrumentationResults: no app for " + target); 14842 return; 14843 } 14844 final long origId = Binder.clearCallingIdentity(); 14845 try { 14846 addInstrumentationResultsLocked(app, results); 14847 } finally { 14848 Binder.restoreCallingIdentity(origId); 14849 } 14850 } 14851 } 14852 14853 @GuardedBy("this") finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)14854 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 14855 try { 14856 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "finishInstrumentationLocked()"); 14857 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 14858 if (instr == null) { 14859 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 14860 return; 14861 } 14862 14863 synchronized (mProcLock) { 14864 if (!instr.mFinished) { 14865 if (instr.mWatcher != null) { 14866 Bundle finalResults = instr.mCurResults; 14867 if (finalResults != null) { 14868 if (instr.mCurResults != null && results != null) { 14869 finalResults.putAll(results); 14870 } 14871 } else { 14872 finalResults = results; 14873 } 14874 mInstrumentationReporter.reportFinished(instr.mWatcher, 14875 instr.mClass, resultCode, finalResults); 14876 } 14877 14878 // Can't call out of the system process with a lock held, so post a message. 14879 if (instr.mUiAutomationConnection != null) { 14880 // Go back to the default mode of denying OP_NO_ISOLATED_STORAGE app op. 14881 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, app.uid, 14882 app.info.packageName, AppOpsManager.MODE_ERRORED); 14883 getAccessCheckDelegateHelper() 14884 .onInstrumentationFinished(app.uid, app.info.packageName); 14885 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG, 14886 instr.mUiAutomationConnection).sendToTarget(); 14887 } 14888 instr.mFinished = true; 14889 } 14890 14891 instr.removeProcess(app); 14892 mProcessStateController.setActiveInstrumentation(app, null); 14893 } 14894 app.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 14895 14896 if (app.isSdkSandbox) { 14897 // For sharedUid apps this will kill all sdk sandbox processes, which is not ideal. 14898 // TODO(b/209061624): should we call ProcessList.removeProcessLocked instead? 14899 killUid(UserHandle.getAppId(app.uid), UserHandle.getUserId(app.uid), 14900 "finished instr"); 14901 final SdkSandboxManagerLocal sandboxManagerLocal = 14902 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 14903 if (sandboxManagerLocal != null) { 14904 sandboxManagerLocal.notifyInstrumentationFinished( 14905 app.sdkSandboxClientAppPackage, 14906 Process.getAppUidForSdkSandboxUid(app.uid)); 14907 } 14908 } else if (!instr.mNoRestart) { 14909 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, 14910 false, app.userId, "finished inst"); 14911 } 14912 } finally { 14913 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 14914 } 14915 } 14916 finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)14917 public void finishInstrumentation(IApplicationThread target, 14918 int resultCode, Bundle results) { 14919 int userId = UserHandle.getCallingUserId(); 14920 // Refuse possible leaked file descriptors 14921 if (results != null && results.hasFileDescriptors()) { 14922 throw new IllegalArgumentException("File descriptors passed in Intent"); 14923 } 14924 14925 synchronized(this) { 14926 ProcessRecord app = getRecordForAppLOSP(target); 14927 if (app == null) { 14928 Slog.w(TAG, "finishInstrumentation: no app for " + target); 14929 return; 14930 } 14931 final long origId = Binder.clearCallingIdentity(); 14932 finishInstrumentationLocked(app, resultCode, results); 14933 Binder.restoreCallingIdentity(origId); 14934 } 14935 } 14936 14937 @Override getFocusedRootTaskInfo()14938 public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException { 14939 return mActivityTaskManager.getFocusedRootTaskInfo(); 14940 } 14941 14942 @Override getConfiguration()14943 public Configuration getConfiguration() { 14944 return mActivityTaskManager.getConfiguration(); 14945 } 14946 14947 @Override suppressResizeConfigChanges(boolean suppress)14948 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException { 14949 mActivityTaskManager.suppressResizeConfigChanges(suppress); 14950 } 14951 14952 @Override updatePersistentConfiguration(Configuration values)14953 public void updatePersistentConfiguration(Configuration values) { 14954 updatePersistentConfigurationWithAttribution(values, 14955 Settings.getPackageNameForUid(mContext, Binder.getCallingUid()), null); 14956 } 14957 14958 @Override updatePersistentConfigurationWithAttribution(Configuration values, String callingPackage, String callingAttributionTag)14959 public void updatePersistentConfigurationWithAttribution(Configuration values, 14960 String callingPackage, String callingAttributionTag) { 14961 enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()"); 14962 enforceWriteSettingsPermission("updatePersistentConfiguration()", callingPackage, 14963 callingAttributionTag); 14964 if (values == null) { 14965 throw new NullPointerException("Configuration must not be null"); 14966 } 14967 14968 int userId = UserHandle.getCallingUserId(); 14969 14970 if (UserManager.isVisibleBackgroundUsersEnabled()) { 14971 final long origId = Binder.clearCallingIdentity(); 14972 try { 14973 if (userId != getCurrentUserId()) { 14974 // The check is added mainly for auto devices. On auto devices, it is 14975 // possible that multiple users are visible simultaneously using visible 14976 // background users. In such cases, it is desired that only the current user 14977 // (not the visible background user) can change the locale and other persistent 14978 // settings of the device. 14979 Slog.w(TAG, "Only current user is allowed to update persistent configuration " 14980 + "if visible background users are enabled. Current User" 14981 + getCurrentUserId() + ". Calling User: " + userId); 14982 throw new SecurityException("Only current user is allowed to update persistent " 14983 + "configuration."); 14984 } 14985 } finally { 14986 Binder.restoreCallingIdentity(origId); 14987 } 14988 } 14989 14990 mActivityTaskManager.updatePersistentConfiguration(values, userId); 14991 } 14992 enforceWriteSettingsPermission(String func, String callingPackage, String callingAttributionTag)14993 private void enforceWriteSettingsPermission(String func, String callingPackage, 14994 String callingAttributionTag) { 14995 int uid = Binder.getCallingUid(); 14996 if (uid == ROOT_UID) { 14997 return; 14998 } 14999 15000 if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid, 15001 callingPackage, callingAttributionTag, false)) { 15002 return; 15003 } 15004 15005 String msg = "Permission Denial: " + func + " from pid=" 15006 + Binder.getCallingPid() 15007 + ", uid=" + uid 15008 + " requires " + android.Manifest.permission.WRITE_SETTINGS; 15009 Slog.w(TAG, msg); 15010 throw new SecurityException(msg); 15011 } 15012 15013 @Override updateConfiguration(Configuration values)15014 public boolean updateConfiguration(Configuration values) { 15015 return mActivityTaskManager.updateConfiguration(values); 15016 } 15017 15018 @Override updateMccMncConfiguration(String mcc, String mnc)15019 public boolean updateMccMncConfiguration(String mcc, String mnc) { 15020 int mccInt, mncInt; 15021 try { 15022 mccInt = Integer.parseInt(mcc); 15023 mncInt = Integer.parseInt(mnc); 15024 } catch (NumberFormatException | StringIndexOutOfBoundsException ex) { 15025 Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex); 15026 return false; 15027 } 15028 Configuration config = new Configuration(); 15029 config.mcc = mccInt; 15030 config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt; 15031 return mActivityTaskManager.updateConfiguration(config); 15032 } 15033 15034 @Override getLaunchedFromUid(IBinder activityToken)15035 public int getLaunchedFromUid(IBinder activityToken) { 15036 return ActivityClient.getInstance().getLaunchedFromUid(activityToken); 15037 } 15038 getLaunchedFromPackage(IBinder activityToken)15039 public String getLaunchedFromPackage(IBinder activityToken) { 15040 return ActivityClient.getInstance().getLaunchedFromPackage(activityToken); 15041 } 15042 15043 // ========================================================= 15044 // LIFETIME MANAGEMENT 15045 // ========================================================= 15046 isReceivingBroadcastLocked(ProcessRecord app, int[] outSchedGroup)15047 boolean isReceivingBroadcastLocked(ProcessRecord app, int[] outSchedGroup) { 15048 final int res = mBroadcastQueue.getPreferredSchedulingGroupLocked(app); 15049 outSchedGroup[0] = res; 15050 return res != ProcessList.SCHED_GROUP_UNDEFINED; 15051 } 15052 startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)15053 Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, 15054 int targetUid, long targetVersionCode, ComponentName targetComponent, 15055 String targetProcess) { 15056 if (!mTrackingAssociations) { 15057 return null; 15058 } 15059 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 15060 = mAssociations.get(targetUid); 15061 if (components == null) { 15062 components = new ArrayMap<>(); 15063 mAssociations.put(targetUid, components); 15064 } 15065 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 15066 if (sourceUids == null) { 15067 sourceUids = new SparseArray<>(); 15068 components.put(targetComponent, sourceUids); 15069 } 15070 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 15071 if (sourceProcesses == null) { 15072 sourceProcesses = new ArrayMap<>(); 15073 sourceUids.put(sourceUid, sourceProcesses); 15074 } 15075 Association ass = sourceProcesses.get(sourceProcess); 15076 if (ass == null) { 15077 ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent, 15078 targetProcess); 15079 sourceProcesses.put(sourceProcess, ass); 15080 } 15081 ass.mCount++; 15082 ass.mNesting++; 15083 if (ass.mNesting == 1) { 15084 ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis(); 15085 ass.mLastState = sourceState; 15086 } 15087 return ass; 15088 } 15089 stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)15090 void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, 15091 long targetVersionCode, ComponentName targetComponent, String targetProcess) { 15092 if (!mTrackingAssociations) { 15093 return; 15094 } 15095 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 15096 = mAssociations.get(targetUid); 15097 if (components == null) { 15098 return; 15099 } 15100 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 15101 if (sourceUids == null) { 15102 return; 15103 } 15104 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 15105 if (sourceProcesses == null) { 15106 return; 15107 } 15108 Association ass = sourceProcesses.get(sourceProcess); 15109 if (ass == null || ass.mNesting <= 0) { 15110 return; 15111 } 15112 ass.mNesting--; 15113 if (ass.mNesting == 0) { 15114 long uptime = SystemClock.uptimeMillis(); 15115 ass.mTime += uptime - ass.mStartTime; 15116 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 15117 += uptime - ass.mLastStateUptime; 15118 ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2; 15119 } 15120 } 15121 15122 /** 15123 * Called by {@link OomAdjuster} whenever either the ProcessState or Capability of a uid has 15124 * changed. 15125 * NOTE: Use {@link #noteUidProcessState(int, int)} instead of this method for listeners 15126 * interested in only ProcessState changes. 15127 */ noteUidProcessStateAndCapability(final int uid, final int state, final @ProcessCapability int capability)15128 void noteUidProcessStateAndCapability(final int uid, final int state, 15129 final @ProcessCapability int capability) { 15130 mAppOpsService.updateUidProcState(uid, state, capability); 15131 } 15132 15133 /** 15134 * Called by {@link OomAdjuster} whenever either the ProcessState of a uid has changed. 15135 * NOTE: Use {@link #noteUidProcessStateAndCapability(int, int, int)} instead of this method 15136 * for listeners interested in both ProcessState and Capability changes. 15137 */ noteUidProcessState(final int uid, final int state)15138 void noteUidProcessState(final int uid, final int state) { 15139 mBatteryStatsService.noteUidProcessState(uid, state); 15140 if (StatsPullAtomService.ENABLE_MOBILE_DATA_STATS_AGGREGATED_PULLER) { 15141 try { 15142 if (mStatsPullAtomServiceInternal == null) { 15143 mStatsPullAtomServiceInternal = LocalServices.getService( 15144 StatsPullAtomServiceInternal.class); 15145 } 15146 if (mStatsPullAtomServiceInternal != null) { 15147 mStatsPullAtomServiceInternal.noteUidProcessState(uid, state); 15148 } else { 15149 Slog.d(TAG, "StatsPullAtomService not ready yet"); 15150 } 15151 } catch (Exception e) { 15152 Slog.e(TAG, "Exception during logging uid proc state change event", e); 15153 } 15154 } 15155 if (mTrackingAssociations) { 15156 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 15157 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 15158 = mAssociations.valueAt(i1); 15159 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 15160 SparseArray<ArrayMap<String, Association>> sourceUids 15161 = targetComponents.valueAt(i2); 15162 ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid); 15163 if (sourceProcesses != null) { 15164 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 15165 Association ass = sourceProcesses.valueAt(i4); 15166 if (ass.mNesting >= 1) { 15167 // currently associated 15168 long uptime = SystemClock.uptimeMillis(); 15169 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 15170 += uptime - ass.mLastStateUptime; 15171 ass.mLastState = state; 15172 ass.mLastStateUptime = uptime; 15173 } 15174 } 15175 } 15176 } 15177 } 15178 } 15179 } 15180 15181 /** 15182 * Returns true if things are idle enough to perform GCs. 15183 */ 15184 @GuardedBy("this") canGcNowLocked()15185 final boolean canGcNowLocked() { 15186 if (!mBroadcastQueue.isIdleLocked()) { 15187 return false; 15188 } 15189 return mAtmInternal.canGcNow(); 15190 } 15191 checkExcessivePowerUsage()15192 private void checkExcessivePowerUsage() { 15193 updateCpuStatsNow(); 15194 15195 final boolean monitorPhantomProcs = mSystemReady && FeatureFlagUtils.isEnabled(mContext, 15196 SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS); 15197 synchronized (mProcLock) { 15198 final boolean doCpuKills = mLastPowerCheckUptime != 0; 15199 final long curUptime = SystemClock.uptimeMillis(); 15200 final long uptimeSince = curUptime - mLastPowerCheckUptime; 15201 mLastPowerCheckUptime = curUptime; 15202 mProcessList.forEachLruProcessesLOSP(false, app -> { 15203 if (app.getThread() == null) { 15204 return; 15205 } 15206 if (app.mState.getSetProcState() >= ActivityManager.PROCESS_STATE_HOME) { 15207 int cpuLimit; 15208 long checkDur = curUptime - app.mState.getWhenUnimportant(); 15209 if (checkDur <= mConstants.POWER_CHECK_INTERVAL) { 15210 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1; 15211 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 2) 15212 || app.mState.getSetProcState() <= ActivityManager.PROCESS_STATE_HOME) { 15213 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2; 15214 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 3)) { 15215 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3; 15216 } else { 15217 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4; 15218 } 15219 15220 updateAppProcessCpuTimeLPr(uptimeSince, doCpuKills, checkDur, cpuLimit, app); 15221 15222 if (monitorPhantomProcs) { 15223 // Also check the phantom processes if there is any 15224 updatePhantomProcessCpuTimeLPr( 15225 uptimeSince, doCpuKills, checkDur, cpuLimit, app); 15226 } 15227 } 15228 }); 15229 } 15230 } 15231 15232 @GuardedBy("mProcLock") updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)15233 private void updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, 15234 final long checkDur, final int cpuLimit, final ProcessRecord app) { 15235 synchronized (mAppProfiler.mProfilerLock) { 15236 final ProcessProfileRecord profile = app.mProfile; 15237 final long curCpuTime = profile.mCurCpuTime.get(); 15238 final long lastCpuTime = profile.mLastCpuTime.get(); 15239 if (lastCpuTime > 0) { 15240 final long cpuTimeUsed = curCpuTime - lastCpuTime; 15241 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed, 15242 app.processName, app.toShortString(), cpuLimit, app)) { 15243 mHandler.post(() -> { 15244 synchronized (ActivityManagerService.this) { 15245 if (app.getThread() == null 15246 || app.mState.getSetProcState() < ActivityManager.PROCESS_STATE_HOME) { 15247 return; 15248 } 15249 app.killLocked("excessive cpu " + cpuTimeUsed + " during " 15250 + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit, 15251 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 15252 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU, 15253 true); 15254 } 15255 }); 15256 profile.reportExcessiveCpu(); 15257 } 15258 } 15259 15260 profile.mLastCpuTime.set(curCpuTime); 15261 } 15262 } 15263 15264 @GuardedBy("mProcLock") updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)15265 private void updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, 15266 final long checkDur, final int cpuLimit, final ProcessRecord app) { 15267 mPhantomProcessList.forEachPhantomProcessOfApp(app, r -> { 15268 if (r.mLastCputime > 0) { 15269 final long cpuTimeUsed = r.mCurrentCputime - r.mLastCputime; 15270 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed, 15271 app.processName, r.toString(), cpuLimit, app)) { 15272 mHandler.post(() -> { 15273 synchronized (ActivityManagerService.this) { 15274 if (app.getThread() == null 15275 || app.mState.getSetProcState() < ActivityManager.PROCESS_STATE_HOME) { 15276 return; 15277 } 15278 mPhantomProcessList.killPhantomProcessGroupLocked(app, r, 15279 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 15280 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU, 15281 "excessive cpu " + cpuTimeUsed + " during " 15282 + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit); 15283 } 15284 }); 15285 return false; 15286 } 15287 } 15288 r.mLastCputime = r.mCurrentCputime; 15289 return true; 15290 }); 15291 } 15292 15293 @GuardedBy("mProcLock") checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, final long cputimeUsed, final String processName, final String description, final int cpuLimit, final ProcessRecord app)15294 private boolean checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, 15295 final long cputimeUsed, final String processName, final String description, 15296 final int cpuLimit, final ProcessRecord app) { 15297 if (DEBUG_POWER && (uptimeSince > 0)) { 15298 StringBuilder sb = new StringBuilder(128); 15299 sb.append("CPU for "); 15300 sb.append(description); 15301 sb.append(": over "); 15302 TimeUtils.formatDuration(uptimeSince, sb); 15303 sb.append(" used "); 15304 TimeUtils.formatDuration(cputimeUsed, sb); 15305 sb.append(" ("); 15306 sb.append((cputimeUsed * 100.0) / uptimeSince); 15307 sb.append("%)"); 15308 Slog.i(TAG_POWER, sb.toString()); 15309 } 15310 // If the process has used too much CPU over the last duration, the 15311 // user probably doesn't want this, so kill! 15312 if (doCpuKills && uptimeSince > 0) { 15313 if (((cputimeUsed * 100) / uptimeSince) >= cpuLimit) { 15314 mBatteryStatsService.reportExcessiveCpu(app.info.uid, app.processName, 15315 uptimeSince, cputimeUsed); 15316 app.getPkgList().forEachPackageProcessStats(holder -> { 15317 final ProcessState state = holder.state; 15318 FrameworkStatsLog.write( 15319 FrameworkStatsLog.EXCESSIVE_CPU_USAGE_REPORTED, 15320 app.info.uid, 15321 processName, 15322 state != null ? state.getPackage() : app.info.packageName, 15323 holder.appVersion); 15324 }); 15325 return true; 15326 } 15327 } 15328 return false; 15329 } 15330 isEphemeralLocked(int uid)15331 private boolean isEphemeralLocked(int uid) { 15332 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid); 15333 if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid 15334 return false; 15335 } 15336 return getPackageManagerInternal().isPackageEphemeral( 15337 UserHandle.getUserId(uid), packages[0]); 15338 } 15339 15340 @GuardedBy("this") enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)15341 void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) { 15342 uid = uidRec != null ? uidRec.getUid() : uid; 15343 if (uid < 0) { 15344 throw new IllegalArgumentException("No UidRecord or uid"); 15345 } 15346 15347 final int procState = uidRec != null 15348 ? uidRec.getSetProcState() : PROCESS_STATE_NONEXISTENT; 15349 final int procAdj = uidRec != null 15350 ? uidRec.getMinProcAdj() : ProcessList.INVALID_ADJ; 15351 final long procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0; 15352 final int capability = uidRec != null ? uidRec.getSetCapability() : 0; 15353 final boolean ephemeral = uidRec != null ? uidRec.isEphemeral() : isEphemeralLocked(uid); 15354 15355 if (uidRec != null && uidRec.isIdle() && (change & UidRecord.CHANGE_IDLE) != 0) { 15356 mProcessList.killAppIfBgRestrictedAndCachedIdleLocked(uidRec); 15357 } 15358 15359 if (uidRec != null && !uidRec.isIdle() && (change & UidRecord.CHANGE_GONE) != 0) { 15360 // If this uid is going away, and we haven't yet reported it is gone, 15361 // then do so now. 15362 change |= UidRecord.CHANGE_IDLE; 15363 } 15364 final int enqueuedChange = mUidObserverController.enqueueUidChange( 15365 uidRec == null ? null : uidRec.pendingChange, 15366 uid, change, procState, procAdj, procStateSeq, capability, ephemeral); 15367 if (uidRec != null) { 15368 uidRec.setLastReportedChange(enqueuedChange); 15369 } 15370 15371 // Directly update the power manager, since we sit on top of it and it is critical 15372 // it be kept in sync (so wake locks will be held as soon as appropriate). 15373 if (mLocalPowerManager != null) { 15374 // TODO: dispatch cached/uncached changes here, so we don't need to report 15375 // all proc state changes. 15376 if ((enqueuedChange & UidRecord.CHANGE_ACTIVE) != 0) { 15377 mLocalPowerManager.uidActive(uid); 15378 } 15379 if ((enqueuedChange & UidRecord.CHANGE_IDLE) != 0) { 15380 mLocalPowerManager.uidIdle(uid); 15381 } 15382 if ((enqueuedChange & UidRecord.CHANGE_GONE) != 0) { 15383 mLocalPowerManager.uidGone(uid); 15384 } else if ((enqueuedChange & UidRecord.CHANGE_PROCSTATE) != 0) { 15385 mLocalPowerManager.updateUidProcState(uid, procState); 15386 } 15387 } 15388 } 15389 15390 @GuardedBy(anyOf = {"this", "mProcLock"}) setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor)15391 final void setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor) { 15392 if (proc.getThread() != null) { 15393 proc.mProfile.setProcessTrackerState( 15394 proc.mState.getReportedProcState(), memFactor); 15395 } 15396 } 15397 15398 @GuardedBy("this") clearProcessForegroundLocked(ProcessRecord proc)15399 final void clearProcessForegroundLocked(ProcessRecord proc) { 15400 updateProcessForegroundLocked(proc, /* isForeground =*/ false, 15401 /* fgsTypes =*/0, /* hasTypeNoneFgs =*/false, /* oomAdj= */ false); 15402 } 15403 15404 @GuardedBy("this") updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean hasTypeNoneFgs, boolean oomAdj)15405 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 15406 int fgServiceTypes, boolean hasTypeNoneFgs, boolean oomAdj) { 15407 final ProcessServiceRecord psr = proc.mServices; 15408 final boolean foregroundStateChanged = isForeground != psr.hasForegroundServices(); 15409 if (foregroundStateChanged 15410 || !psr.areForegroundServiceTypesSame(fgServiceTypes, hasTypeNoneFgs)) { 15411 if (foregroundStateChanged) { 15412 // Notify internal listeners. 15413 for (int i = mForegroundServiceStateListeners.size() - 1; i >= 0; i--) { 15414 mForegroundServiceStateListeners.get(i).onForegroundServiceStateChanged( 15415 proc.info.packageName, proc.info.uid, proc.getPid(), isForeground); 15416 } 15417 } 15418 mProcessStateController.setHasForegroundServices(psr, isForeground, fgServiceTypes, 15419 hasTypeNoneFgs); 15420 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 15421 proc.info.uid); 15422 if (isForeground) { 15423 if (curProcs == null) { 15424 curProcs = new ArrayList<ProcessRecord>(); 15425 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 15426 } 15427 if (!curProcs.contains(proc)) { 15428 curProcs.add(proc); 15429 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 15430 proc.info.packageName, proc.info.uid); 15431 } 15432 } else { 15433 if (curProcs != null) { 15434 if (curProcs.remove(proc)) { 15435 mBatteryStatsService.noteEvent( 15436 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 15437 proc.info.packageName, proc.info.uid); 15438 if (curProcs.size() <= 0) { 15439 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 15440 } 15441 } 15442 } 15443 } 15444 15445 psr.setReportedForegroundServiceTypes(fgServiceTypes); 15446 mProcessList.enqueueProcessChangeItemLocked(proc.getPid(), proc.info.uid, 15447 ProcessChangeItem.CHANGE_FOREGROUND_SERVICES, fgServiceTypes); 15448 } 15449 if (oomAdj) { 15450 mProcessStateController.runUpdate(proc, OOM_ADJ_REASON_UI_VISIBILITY); 15451 } 15452 } 15453 15454 // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update 15455 // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities 15456 @Nullable getTopApp()15457 ProcessRecord getTopApp() { 15458 final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null; 15459 final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null; 15460 String pkg; 15461 int uid; 15462 if (r != null) { 15463 pkg = r.processName; 15464 uid = r.info.uid; 15465 } else { 15466 pkg = null; 15467 uid = -1; 15468 } 15469 // Has the UID or resumed package name changed? 15470 synchronized (mCurResumedAppLock) { 15471 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 15472 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 15473 15474 final long identity = Binder.clearCallingIdentity(); 15475 try { 15476 if (mCurResumedPackage != null) { 15477 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 15478 mCurResumedPackage, mCurResumedUid); 15479 } 15480 mCurResumedPackage = pkg; 15481 mCurResumedUid = uid; 15482 if (mCurResumedPackage != null) { 15483 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 15484 mCurResumedPackage, mCurResumedUid); 15485 } 15486 } finally { 15487 Binder.restoreCallingIdentity(identity); 15488 } 15489 } 15490 } 15491 return r; 15492 } 15493 15494 /** 15495 * Enqueue the given process into a todo list, and the caller should 15496 * call {@link #updateOomAdjPendingTargetsLocked} to kick off a pass of the oom adj update. 15497 */ 15498 @GuardedBy("this") enqueueOomAdjTargetLocked(ProcessRecord app)15499 void enqueueOomAdjTargetLocked(ProcessRecord app) { 15500 mProcessStateController.enqueueUpdateTarget(app); 15501 } 15502 15503 /** 15504 * Remove the given process into a todo list. 15505 */ 15506 @GuardedBy("this") removeOomAdjTargetLocked(ProcessRecord app, boolean procDied)15507 void removeOomAdjTargetLocked(ProcessRecord app, boolean procDied) { 15508 mProcessStateController.removeUpdateTarget(app, procDied); 15509 } 15510 15511 /** 15512 * Kick off an oom adj update pass for the pending targets which are enqueued via 15513 * {@link #enqueueOomAdjTargetLocked}. 15514 */ 15515 @GuardedBy("this") updateOomAdjPendingTargetsLocked(@omAdjReason int oomAdjReason)15516 void updateOomAdjPendingTargetsLocked(@OomAdjReason int oomAdjReason) { 15517 mProcessStateController.runPendingUpdate(oomAdjReason); 15518 } 15519 15520 static final class ProcStatsRunnable implements Runnable { 15521 private final ActivityManagerService mService; 15522 private final ProcessStatsService mProcessStats; 15523 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)15524 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) { 15525 this.mService = service; 15526 this.mProcessStats = mProcessStats; 15527 } 15528 run()15529 @Override public void run() { 15530 mProcessStats.writeStateAsync(); 15531 } 15532 } 15533 15534 @GuardedBy("this") updateOomAdjLocked(@omAdjReason int oomAdjReason)15535 final void updateOomAdjLocked(@OomAdjReason int oomAdjReason) { 15536 mProcessStateController.runFullUpdate(oomAdjReason); 15537 } 15538 15539 /** 15540 * Update OomAdj for a specific process and its reachable processes. 15541 * 15542 * @param app The process to update 15543 * @param oomAdjReason 15544 * @return whether updateOomAdjLocked(app) was successful. 15545 */ 15546 @GuardedBy("this") updateOomAdjLocked(ProcessRecord app, @OomAdjReason int oomAdjReason)15547 final boolean updateOomAdjLocked(ProcessRecord app, @OomAdjReason int oomAdjReason) { 15548 return mProcessStateController.runUpdate(app, oomAdjReason); 15549 } 15550 15551 @Override makePackageIdle(String packageName, int userId)15552 public void makePackageIdle(String packageName, int userId) { 15553 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 15554 != PackageManager.PERMISSION_GRANTED) { 15555 String msg = "Permission Denial: makePackageIdle() from pid=" 15556 + Binder.getCallingPid() 15557 + ", uid=" + Binder.getCallingUid() 15558 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 15559 Slog.w(TAG, msg); 15560 throw new SecurityException(msg); 15561 } 15562 final int callingPid = Binder.getCallingPid(); 15563 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 15564 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null); 15565 final long callingId = Binder.clearCallingIdentity(); 15566 try { 15567 IPackageManager pm = AppGlobals.getPackageManager(); 15568 int pkgUid = -1; 15569 try { 15570 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES 15571 | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM); 15572 } catch (RemoteException e) { 15573 } 15574 if (pkgUid == -1) { 15575 throw new IllegalArgumentException("Unknown package name " + packageName); 15576 } 15577 15578 synchronized (this) { 15579 try { 15580 if (mLocalPowerManager != null) { 15581 mLocalPowerManager.startUidChanges(); 15582 } 15583 final int appId = UserHandle.getAppId(pkgUid); 15584 for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; i--) { 15585 final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i); 15586 final long bgTime = uidRec.getLastBackgroundTime(); 15587 if (bgTime > 0 && !uidRec.isIdle()) { 15588 final int uid = uidRec.getUid(); 15589 if (UserHandle.getAppId(uid) == appId) { 15590 if (userId == UserHandle.USER_ALL 15591 || userId == UserHandle.getUserId(uid)) { 15592 EventLogTags.writeAmUidIdle(uid); 15593 synchronized (mProcLock) { 15594 uidRec.setIdle(true); 15595 uidRec.setSetIdle(true); 15596 } 15597 Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uid) 15598 + " from package " + packageName + " user " + userId); 15599 doStopUidLocked(uid, uidRec); 15600 } 15601 } 15602 } 15603 } 15604 } finally { 15605 if (mLocalPowerManager != null) { 15606 mLocalPowerManager.finishUidChanges(); 15607 } 15608 } 15609 } 15610 } finally { 15611 Binder.restoreCallingIdentity(callingId); 15612 } 15613 } 15614 15615 @Override setDeterministicUidIdle(boolean deterministic)15616 public void setDeterministicUidIdle(boolean deterministic) { 15617 synchronized (this) { 15618 mDeterministicUidIdle = deterministic; 15619 } 15620 } 15621 15622 /** Make the currently active UIDs idle after a certain grace period. */ idleUids()15623 final void idleUids() { 15624 synchronized (this) { 15625 mOomAdjuster.idleUidsLocked(); 15626 } 15627 } 15628 runInBackgroundDisabled(int uid)15629 final void runInBackgroundDisabled(int uid) { 15630 synchronized (this) { 15631 UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 15632 if (uidRec != null) { 15633 // This uid is actually running... should it be considered background now? 15634 if (uidRec.isIdle()) { 15635 doStopUidLocked(uidRec.getUid(), uidRec); 15636 } 15637 } else { 15638 // This uid isn't actually running... still send a report about it being "stopped". 15639 doStopUidLocked(uid, null); 15640 } 15641 } 15642 } 15643 cameraActiveChanged(@serIdInt int uid, boolean active)15644 final void cameraActiveChanged(@UserIdInt int uid, boolean active) { 15645 synchronized (mActiveCameraUids) { 15646 final int curIndex = mActiveCameraUids.indexOf(uid); 15647 if (active) { 15648 if (curIndex < 0) { 15649 mActiveCameraUids.add(uid); 15650 } 15651 } else { 15652 if (curIndex >= 0) { 15653 mActiveCameraUids.remove(curIndex); 15654 } 15655 } 15656 } 15657 15658 if (com.android.window.flags.Flags.fifoPriorityForMajorUiProcesses()) { 15659 synchronized (mProcLock) { 15660 adjustFifoProcessesIfNeeded(uid, !active /* allowFifo */); 15661 } 15662 } 15663 } 15664 isCameraActiveForUid(@serIdInt int uid)15665 final boolean isCameraActiveForUid(@UserIdInt int uid) { 15666 synchronized (mActiveCameraUids) { 15667 return mActiveCameraUids.indexOf(uid) >= 0; 15668 } 15669 } 15670 15671 /** 15672 * This is called when the given uid is using camera. If the uid has top process state, then 15673 * cancel the FIFO priority of the high priority processes. 15674 */ 15675 @VisibleForTesting 15676 @GuardedBy("mProcLock") adjustFifoProcessesIfNeeded(int preemptiveUid, boolean allowSpecifiedFifo)15677 void adjustFifoProcessesIfNeeded(int preemptiveUid, boolean allowSpecifiedFifo) { 15678 if (allowSpecifiedFifo == mAllowSpecifiedFifoScheduling) { 15679 return; 15680 } 15681 if (!allowSpecifiedFifo) { 15682 final UidRecord uidRec = mProcessList.mActiveUids.get(preemptiveUid); 15683 if (uidRec == null || uidRec.getCurProcState() > PROCESS_STATE_TOP) { 15684 // To avoid frequent switching by background camera usages, e.g. face unlock, 15685 // face detection (auto rotation), screen attention (keep screen on). 15686 return; 15687 } 15688 } 15689 mAllowSpecifiedFifoScheduling = allowSpecifiedFifo; 15690 for (int i = mSpecifiedFifoProcesses.size() - 1; i >= 0; i--) { 15691 final ProcessRecord proc = mSpecifiedFifoProcesses.get(i); 15692 if (proc.mState.getSetSchedGroup() != ProcessList.SCHED_GROUP_TOP_APP) { 15693 continue; 15694 } 15695 setFifoPriority(proc, allowSpecifiedFifo /* enable */); 15696 } 15697 } 15698 15699 @GuardedBy("this") doStopUidLocked(int uid, final UidRecord uidRec)15700 final void doStopUidLocked(int uid, final UidRecord uidRec) { 15701 mServices.stopInBackgroundLocked(uid); 15702 enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE | UidRecord.CHANGE_PROCSTATE); 15703 } 15704 15705 /** 15706 * Allowlists {@code targetUid} to temporarily bypass Power Save mode. 15707 */ 15708 @GuardedBy("this") tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)15709 void tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, 15710 long duration, int type, @ReasonCode int reasonCode, String reason) { 15711 if (DEBUG_ALLOWLISTS) { 15712 Slog.d(TAG, "tempAllowlistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", " 15713 + targetUid + ", " + duration + ", " + type + ")"); 15714 } 15715 15716 synchronized (mPidsSelfLocked) { 15717 final ProcessRecord pr = mPidsSelfLocked.get(callerPid); 15718 if (pr == null) { 15719 Slog.w(TAG, "tempAllowlistForPendingIntentLocked() no ProcessRecord for pid " 15720 + callerPid); 15721 return; 15722 } 15723 if (!pr.mServices.mAllowlistManager) { 15724 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid) 15725 != PackageManager.PERMISSION_GRANTED 15726 && checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callerPid, callerUid) 15727 != PackageManager.PERMISSION_GRANTED 15728 && checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callerPid, 15729 callerUid) != PackageManager.PERMISSION_GRANTED) { 15730 if (DEBUG_ALLOWLISTS) { 15731 Slog.d(TAG, "tempAllowlistForPendingIntentLocked() for target " + targetUid 15732 + ": pid " + callerPid + " is not allowed"); 15733 } 15734 return; 15735 } 15736 } 15737 } 15738 15739 tempAllowlistUidLocked(targetUid, duration, reasonCode, reason, type, callerUid); 15740 } 15741 15742 /** 15743 * Allowlists {@code targetUid} to temporarily bypass Power Save mode. 15744 */ 15745 @GuardedBy("this") tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, String reason, @TempAllowListType int type, int callingUid)15746 void tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, 15747 String reason, @TempAllowListType int type, int callingUid) { 15748 synchronized (mProcLock) { 15749 // The temp allowlist type could change according to the reasonCode. 15750 if (mLocalDeviceIdleController != null) { 15751 type = mLocalDeviceIdleController.getTempAllowListType(reasonCode, type); 15752 } 15753 if (type == TEMPORARY_ALLOW_LIST_TYPE_NONE) { 15754 return; 15755 } 15756 mPendingTempAllowlist.put(targetUid, 15757 new PendingTempAllowlist(targetUid, duration, reasonCode, reason, type, 15758 callingUid)); 15759 setUidTempAllowlistStateLSP(targetUid, true); 15760 mUiHandler.obtainMessage(PUSH_TEMP_ALLOWLIST_UI_MSG).sendToTarget(); 15761 15762 if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) { 15763 mFgsStartTempAllowList.add(targetUid, duration, 15764 new FgsTempAllowListItem(duration, reasonCode, reason, callingUid)); 15765 } 15766 } 15767 } 15768 pushTempAllowlist()15769 void pushTempAllowlist() { 15770 final int N; 15771 final PendingTempAllowlist[] list; 15772 15773 // First copy out the pending changes... we need to leave them in the map for now, 15774 // in case someone needs to check what is coming up while we don't have the lock held. 15775 synchronized (this) { 15776 synchronized (mProcLock) { 15777 N = mPendingTempAllowlist.size(); 15778 list = new PendingTempAllowlist[N]; 15779 for (int i = 0; i < N; i++) { 15780 list[i] = mPendingTempAllowlist.valueAt(i); 15781 } 15782 } 15783 } 15784 15785 // Now safely dispatch changes to device idle controller. Skip this if we're early 15786 // in boot and the controller hasn't yet been brought online: we do not apply 15787 // device idle policy anyway at this phase. 15788 if (mLocalDeviceIdleController != null) { 15789 for (int i = 0; i < N; i++) { 15790 PendingTempAllowlist ptw = list[i]; 15791 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid, 15792 ptw.duration, ptw.type, false, ptw.reasonCode, ptw.tag, 15793 ptw.callingUid); 15794 } 15795 } 15796 15797 // And now we can safely remove them from the map. 15798 synchronized (this) { 15799 synchronized (mProcLock) { 15800 for (int i = 0; i < N; i++) { 15801 PendingTempAllowlist ptw = list[i]; 15802 int index = mPendingTempAllowlist.indexOfKey(ptw.targetUid); 15803 if (index >= 0 && mPendingTempAllowlist.valueAt(index) == ptw) { 15804 mPendingTempAllowlist.removeAt(index); 15805 } 15806 } 15807 } 15808 } 15809 } 15810 15811 @GuardedBy({"this", "mProcLock"}) setUidTempAllowlistStateLSP(int uid, boolean onAllowlist)15812 final void setUidTempAllowlistStateLSP(int uid, boolean onAllowlist) { 15813 mProcessStateController.setUidTempAllowlistStateLSP(uid, onAllowlist); 15814 } 15815 trimApplications(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason)15816 private void trimApplications(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason) { 15817 synchronized (this) { 15818 trimApplicationsLocked(forceFullOomAdj, oomAdjReason); 15819 } 15820 } 15821 15822 @GuardedBy("this") trimApplicationsLocked(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason)15823 void trimApplicationsLocked(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason) { 15824 // First remove any unused application processes whose package 15825 // has been removed. 15826 boolean didSomething = false; 15827 for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) { 15828 final ProcessRecord app = mProcessList.mRemovedProcesses.get(i); 15829 if (!app.hasActivitiesOrRecentTasks() 15830 && app.mReceivers.numberOfCurReceivers() == 0 15831 && app.mServices.numberOfRunningServices() == 0) { 15832 final IApplicationThread thread = app.getThread(); 15833 Slog.i(TAG, "Exiting empty application process " 15834 + app.toShortString() + " (" 15835 + (thread != null ? thread.asBinder() : null) 15836 + ")\n"); 15837 final int pid = app.getPid(); 15838 if (pid > 0 && pid != MY_PID) { 15839 app.killLocked("empty", 15840 ApplicationExitInfo.REASON_OTHER, 15841 ApplicationExitInfo.SUBREASON_TRIM_EMPTY, 15842 false); 15843 } else if (thread != null) { 15844 try { 15845 thread.scheduleExit(); 15846 } catch (Exception e) { 15847 // Ignore exceptions. 15848 } 15849 } 15850 didSomething = true; 15851 cleanUpApplicationRecordLocked(app, pid, false, true, -1, false /*replacingPid*/, 15852 false /* fromBinderDied */); 15853 mProcessList.mRemovedProcesses.remove(i); 15854 15855 if (app.isPersistent()) { 15856 addAppLocked(app.info, null, false, null /* ABI override */, 15857 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 15858 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_PERSISTENT); 15859 } 15860 } 15861 } 15862 15863 // Now update the oom adj for all processes. Don't skip this, since other callers 15864 // might be depending on it. 15865 if (didSomething || forceFullOomAdj) { 15866 updateOomAdjLocked(oomAdjReason); 15867 } else { 15868 // Process any pending oomAdj targets, it'll be a no-op if nothing is pending. 15869 updateOomAdjPendingTargetsLocked(oomAdjReason); 15870 } 15871 } 15872 15873 /** This method sends the specified signal to each of the persistent apps */ signalPersistentProcesses(final int sig)15874 public void signalPersistentProcesses(final int sig) throws RemoteException { 15875 if (sig != SIGNAL_USR1) { 15876 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 15877 } 15878 15879 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 15880 != PackageManager.PERMISSION_GRANTED) { 15881 throw new SecurityException("Requires permission " 15882 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 15883 } 15884 15885 synchronized (mProcLock) { 15886 mProcessList.forEachLruProcessesLOSP(false, app -> { 15887 if (app.getThread() != null && app.isPersistent()) { 15888 sendSignal(app.getPid(), sig); 15889 } 15890 }); 15891 } 15892 } 15893 profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)15894 public boolean profileControl(String process, int userId, boolean start, 15895 ProfilerInfo profilerInfo, int profileType) throws RemoteException { 15896 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 15897 // its own permission. 15898 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 15899 != PackageManager.PERMISSION_GRANTED) { 15900 throw new SecurityException("Requires permission " 15901 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 15902 } 15903 15904 if (start && profileType == ProfilerInfo.PROFILE_TYPE_REGULAR 15905 && (profilerInfo == null || profilerInfo.profileFd == null)) { 15906 throw new IllegalArgumentException("null profile info or fd"); 15907 } 15908 15909 ProcessRecord proc = null; 15910 synchronized (mProcLock) { 15911 if (process != null) { 15912 proc = findProcessLOSP(process, userId, "profileControl"); 15913 } 15914 15915 if (start && (proc == null || proc.getThread() == null)) { 15916 throw new IllegalArgumentException("Unknown process: " + process); 15917 } 15918 } 15919 15920 synchronized (mAppProfiler.mProfilerLock) { 15921 return mAppProfiler.profileControlLPf(proc, start, profilerInfo, profileType); 15922 } 15923 } 15924 15925 @GuardedBy(anyOf = {"this", "mProcLock"}) findProcessLOSP(String process, int userId, String callName)15926 private ProcessRecord findProcessLOSP(String process, int userId, String callName) { 15927 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 15928 userId, true, ALLOW_FULL_ONLY, callName, null); 15929 ProcessRecord proc = null; 15930 try { 15931 int pid = Integer.parseInt(process); 15932 synchronized (mPidsSelfLocked) { 15933 proc = mPidsSelfLocked.get(pid); 15934 } 15935 } catch (NumberFormatException e) { 15936 } 15937 15938 if (proc == null) { 15939 ArrayMap<String, SparseArray<ProcessRecord>> all = 15940 mProcessList.getProcessNamesLOSP().getMap(); 15941 SparseArray<ProcessRecord> procs = all.get(process); 15942 if (procs != null && procs.size() > 0) { 15943 proc = procs.valueAt(0); 15944 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 15945 for (int i=1; i<procs.size(); i++) { 15946 ProcessRecord thisProc = procs.valueAt(i); 15947 if (thisProc.userId == userId) { 15948 proc = thisProc; 15949 break; 15950 } 15951 } 15952 } 15953 } 15954 } 15955 15956 return proc; 15957 } 15958 15959 @Override dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String dumpBitmaps, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)15960 public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, 15961 boolean runGc, String dumpBitmaps, 15962 String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) { 15963 try { 15964 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 15965 // its own permission (same as profileControl). 15966 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 15967 != PackageManager.PERMISSION_GRANTED) { 15968 throw new SecurityException("Requires permission " 15969 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 15970 } 15971 15972 if (fd == null) { 15973 throw new IllegalArgumentException("null fd"); 15974 } 15975 15976 synchronized (this) { 15977 ProcessRecord proc = findProcessLOSP(process, userId, "dumpHeap"); 15978 IApplicationThread thread; 15979 if (proc == null || (thread = proc.getThread()) == null) { 15980 throw new IllegalArgumentException("Unknown process: " + process); 15981 } 15982 15983 enforceDebuggable(proc); 15984 15985 mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 15986 15987 final RemoteCallback intermediateCallback = new RemoteCallback( 15988 new RemoteCallback.OnResultListener() { 15989 @Override 15990 public void onResult(Bundle result) { 15991 finishCallback.sendResult(result); 15992 mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 15993 } 15994 }, null); 15995 15996 thread.dumpHeap(managed, mallocInfo, runGc, dumpBitmaps, 15997 path, fd, intermediateCallback); 15998 fd = null; 15999 return true; 16000 } 16001 } catch (RemoteException e) { 16002 throw new IllegalStateException("Process disappeared"); 16003 } finally { 16004 if (fd != null) { 16005 try { 16006 fd.close(); 16007 } catch (IOException e) { 16008 } 16009 } 16010 } 16011 } 16012 16013 /** 16014 * Dump the resources structure for the given process 16015 * 16016 * @param process The process to dump resource info for 16017 * @param fd The FileDescriptor to dump it into 16018 * @throws RemoteException 16019 */ dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback)16020 public boolean dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback) 16021 throws RemoteException { 16022 synchronized (this) { 16023 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_CURRENT, "dumpResources"); 16024 IApplicationThread thread; 16025 if (proc == null || (thread = proc.getThread()) == null) { 16026 throw new IllegalArgumentException("Unknown process: " + process); 16027 } 16028 thread.dumpResources(fd, callback); 16029 return true; 16030 } 16031 } 16032 16033 /** 16034 * Dump the resources structure for all processes 16035 * 16036 * @param fd The FileDescriptor to dump it into 16037 * @throws RemoteException 16038 */ dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw)16039 public void dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw) throws RemoteException { 16040 final ArrayList<ProcessRecord> processes = new ArrayList<>(); 16041 synchronized (this) { 16042 processes.addAll(mProcessList.getLruProcessesLOSP()); 16043 } 16044 for (int i = 0, size = processes.size(); i < size; i++) { 16045 ProcessRecord app = processes.get(i); 16046 pw.println(String.format("Resources History for %s (%s)", 16047 app.processName, 16048 app.info.packageName)); 16049 if (app.mOptRecord.isFrozen()) { 16050 pw.println(" Skipping frozen process"); 16051 pw.flush(); 16052 continue; 16053 } 16054 pw.flush(); 16055 try { 16056 TransferPipe tp = new TransferPipe(" "); 16057 try { 16058 IApplicationThread thread = app.getThread(); 16059 if (thread != null) { 16060 app.getThread().dumpResources(tp.getWriteFd(), null); 16061 tp.go(fd.getFileDescriptor(), 2000); 16062 } else { 16063 pw.println(String.format( 16064 " Resources history for %s (%s) failed, no thread", 16065 app.processName, 16066 app.info.packageName)); 16067 } 16068 } finally { 16069 tp.kill(); 16070 } 16071 } catch (IOException e) { 16072 pw.println(" " + e.getMessage()); 16073 pw.flush(); 16074 } 16075 16076 } 16077 } 16078 16079 @Override setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)16080 public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, 16081 String reportPackage) { 16082 if (processName != null) { 16083 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 16084 "setDumpHeapDebugLimit()"); 16085 } else { 16086 synchronized (mPidsSelfLocked) { 16087 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid()); 16088 if (proc == null) { 16089 throw new SecurityException("No process found for calling pid " 16090 + Binder.getCallingPid()); 16091 } 16092 enforceDebuggable(proc); 16093 processName = proc.processName; 16094 uid = proc.uid; 16095 if (reportPackage != null && !proc.getPkgList().containsKey(reportPackage)) { 16096 throw new SecurityException("Package " + reportPackage + " is not running in " 16097 + proc); 16098 } 16099 } 16100 } 16101 mAppProfiler.setDumpHeapDebugLimit(processName, uid, maxMemSize, reportPackage); 16102 } 16103 16104 @Override dumpHeapFinished(String path)16105 public void dumpHeapFinished(String path) { 16106 mAppProfiler.dumpHeapFinished(path, Binder.getCallingPid()); 16107 } 16108 16109 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ monitor()16110 public void monitor() { 16111 synchronized (this) { } 16112 } 16113 onCoreSettingsChange(Bundle settings)16114 void onCoreSettingsChange(Bundle settings) { 16115 synchronized (mProcLock) { 16116 mProcessList.updateCoreSettingsLOSP(settings); 16117 } 16118 } 16119 16120 // Multi-user methods 16121 16122 /** 16123 * Start user, if its not already running, but don't bring it to foreground. 16124 */ 16125 @Override startUserInBackground(final int userId)16126 public boolean startUserInBackground(final int userId) { 16127 return startUserInBackgroundWithListener(userId, null); 16128 } 16129 16130 @Override startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)16131 public boolean startUserInBackgroundWithListener(final int userId, 16132 @Nullable IProgressListener unlockListener) { 16133 return mUserController.startUser(userId, USER_START_MODE_BACKGROUND, unlockListener); 16134 } 16135 16136 @Override startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)16137 public boolean startUserInForegroundWithListener(final int userId, 16138 @Nullable IProgressListener unlockListener) { 16139 // Permission check done inside UserController. 16140 return mUserController.startUser(userId, USER_START_MODE_FOREGROUND, unlockListener); 16141 } 16142 16143 @Override startUserInBackgroundVisibleOnDisplay(int userId, int displayId, @Nullable IProgressListener unlockListener)16144 public boolean startUserInBackgroundVisibleOnDisplay(int userId, int displayId, 16145 @Nullable IProgressListener unlockListener) { 16146 int[] displayIds = getDisplayIdsForStartingVisibleBackgroundUsers(); 16147 boolean validDisplay = false; 16148 if (displayIds != null) { 16149 for (int i = 0; i < displayIds.length; i++) { 16150 if (displayId == displayIds[i]) { 16151 validDisplay = true; 16152 break; 16153 } 16154 } 16155 } 16156 if (!validDisplay) { 16157 throw new IllegalArgumentException("Invalid display (" + displayId + ") to start user. " 16158 + "Valid options are: " + Arrays.toString(displayIds)); 16159 } 16160 16161 if (DEBUG_MU) { 16162 Slogf.d(TAG_MU, "Calling startUserOnSecondaryDisplay(%d, %d, %s) using injector %s", 16163 userId, displayId, unlockListener, mInjector); 16164 } 16165 // Permission check done inside UserController. 16166 return mInjector.startUserInBackgroundVisibleOnDisplay(userId, displayId, unlockListener); 16167 } 16168 16169 @Override getDisplayIdsForStartingVisibleBackgroundUsers()16170 public int[] getDisplayIdsForStartingVisibleBackgroundUsers() { 16171 enforceCallingHasAtLeastOnePermission("getDisplayIdsForStartingVisibleBackgroundUsers()", 16172 MANAGE_USERS, INTERACT_ACROSS_USERS); 16173 return mInjector.getDisplayIdsForStartingVisibleBackgroundUsers(); 16174 } 16175 16176 /** @deprecated see the AIDL documentation {@inheritDoc} */ 16177 @Override 16178 @Deprecated unlockUser(@serIdInt int userId, @Nullable byte[] token, @Nullable byte[] secret, @Nullable IProgressListener listener)16179 public boolean unlockUser(@UserIdInt int userId, @Nullable byte[] token, 16180 @Nullable byte[] secret, @Nullable IProgressListener listener) { 16181 return mUserController.unlockUser(userId, listener); 16182 } 16183 16184 @Override unlockUser2(@serIdInt int userId, @Nullable IProgressListener listener)16185 public boolean unlockUser2(@UserIdInt int userId, @Nullable IProgressListener listener) { 16186 return mUserController.unlockUser(userId, listener); 16187 } 16188 16189 @Override switchUser(final int targetUserId)16190 public boolean switchUser(final int targetUserId) { 16191 return mUserController.switchUser(targetUserId); 16192 } 16193 16194 @Nullable 16195 @Override getSwitchingFromUserMessage(@serIdInt int userId)16196 public String getSwitchingFromUserMessage(@UserIdInt int userId) { 16197 return mUserController.getSwitchingFromUserMessage(userId); 16198 } 16199 16200 @Nullable 16201 @Override getSwitchingToUserMessage(@serIdInt int userId)16202 public String getSwitchingToUserMessage(@UserIdInt int userId) { 16203 return mUserController.getSwitchingToUserMessage(userId); 16204 } 16205 16206 @Override setStopUserOnSwitch(@topUserOnSwitch int value)16207 public void setStopUserOnSwitch(@StopUserOnSwitch int value) { 16208 mUserController.setStopUserOnSwitch(value); 16209 } 16210 16211 /** @deprecated use {@link #stopUserWithCallback(int, IStopUserCallback)} instead */ 16212 @Deprecated 16213 @Override stopUser(final int userId, boolean stopProfileRegardlessOfParent, final IStopUserCallback callback)16214 public int stopUser(final int userId, 16215 boolean stopProfileRegardlessOfParent, final IStopUserCallback callback) { 16216 return stopUserExceptCertainProfiles(userId, stopProfileRegardlessOfParent, callback); 16217 } 16218 16219 /** Stops the given user. */ 16220 @Override stopUserWithCallback(@serIdInt int userId, @Nullable IStopUserCallback callback)16221 public int stopUserWithCallback(@UserIdInt int userId, @Nullable IStopUserCallback callback) { 16222 return mUserController.stopUser(userId, /* allowDelayedLocking= */ false, 16223 /* callback= */ callback, /* keyEvictedCallback= */ null); 16224 } 16225 16226 /** 16227 * Stops the given user. 16228 * 16229 * Usually, callers can just use @link{#stopUserWithCallback(int, IStopUserCallback)} instead. 16230 * 16231 * @param stopProfileRegardlessOfParent whether to stop the profile regardless of who its 16232 * parent is, e.g. even if the parent is the current user; 16233 * its value is irrelevant for non-profile users. 16234 */ 16235 @Override stopUserExceptCertainProfiles(@serIdInt int userId, boolean stopProfileRegardlessOfParent, @Nullable IStopUserCallback callback)16236 public int stopUserExceptCertainProfiles(@UserIdInt int userId, 16237 boolean stopProfileRegardlessOfParent, @Nullable IStopUserCallback callback) { 16238 return mUserController.stopUser(userId, 16239 stopProfileRegardlessOfParent, /* allowDelayedLocking= */ false, 16240 /* callback= */ callback, /* keyEvictedCallback= */ null); 16241 } 16242 16243 /** 16244 * Stops user but allow delayed locking. Delayed locking keeps user unlocked even after 16245 * stopping only if {@code config_multiuserDelayUserDataLocking} overlay is set true on the 16246 * device or if the user has {@link UserProperties#getAllowStoppingUserWithDelayedLocking()} 16247 * set to true. 16248 * 16249 * <p>When delayed locking is not enabled through the overlay, this call becomes the same 16250 * with {@link #stopUserWithCallback(int, IStopUserCallback)} call. 16251 * 16252 * @param userId User id to stop. 16253 * @param callback Callback called when user has stopped. 16254 * 16255 * @return {@link ActivityManager#USER_OP_SUCCESS} when user is stopped successfully. Returns 16256 * other {@code ActivityManager#USER_OP_*} codes for failure. 16257 * 16258 */ 16259 @Override stopUserWithDelayedLocking(@serIdInt int userId, IStopUserCallback callback)16260 public int stopUserWithDelayedLocking(@UserIdInt int userId, IStopUserCallback callback) { 16261 return mUserController.stopUser(userId, /* allowDelayedLocking= */ true, 16262 /* callback= */ callback, /* keyEvictedCallback= */ null); 16263 } 16264 16265 @Override startProfile(@serIdInt int userId)16266 public boolean startProfile(@UserIdInt int userId) { 16267 return mUserController.startProfile(userId, /* evenWhenDisabled= */ false, 16268 /* unlockListener= */ null); 16269 } 16270 16271 @Override startProfileWithListener(@serIdInt int userId, @Nullable IProgressListener unlockListener)16272 public boolean startProfileWithListener(@UserIdInt int userId, 16273 @Nullable IProgressListener unlockListener) { 16274 return mUserController.startProfile(userId, /* evenWhenDisabled= */ false, unlockListener); 16275 } 16276 16277 @Override stopProfile(@serIdInt int userId)16278 public boolean stopProfile(@UserIdInt int userId) { 16279 return mUserController.stopProfile(userId); 16280 } 16281 16282 @Override getCurrentUser()16283 public UserInfo getCurrentUser() { 16284 return mUserController.getCurrentUser(); 16285 } 16286 16287 @Override getCurrentUserId()16288 public @UserIdInt int getCurrentUserId() { 16289 return mUserController.getCurrentUserIdChecked(); 16290 } 16291 getStartedUserState(int userId)16292 String getStartedUserState(int userId) { 16293 final UserState userState = mUserController.getStartedUserState(userId); 16294 return UserState.stateToString(userState.state); 16295 } 16296 16297 @Override isUserRunning(int userId, int flags)16298 public boolean isUserRunning(int userId, int flags) { 16299 if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId()) 16300 && checkCallingPermission(INTERACT_ACROSS_USERS) 16301 != PackageManager.PERMISSION_GRANTED) { 16302 String msg = "Permission Denial: isUserRunning() from pid=" 16303 + Binder.getCallingPid() 16304 + ", uid=" + Binder.getCallingUid() 16305 + " requires " + INTERACT_ACROSS_USERS; 16306 Slog.w(TAG, msg); 16307 throw new SecurityException(msg); 16308 } 16309 return mUserController.isUserRunning(userId, flags); 16310 } 16311 16312 @Override getRunningUserIds()16313 public int[] getRunningUserIds() { 16314 if (checkCallingPermission(INTERACT_ACROSS_USERS) 16315 != PackageManager.PERMISSION_GRANTED) { 16316 String msg = "Permission Denial: isUserRunning() from pid=" 16317 + Binder.getCallingPid() 16318 + ", uid=" + Binder.getCallingUid() 16319 + " requires " + INTERACT_ACROSS_USERS; 16320 Slog.w(TAG, msg); 16321 throw new SecurityException(msg); 16322 } 16323 return mUserController.getStartedUserArray(); 16324 } 16325 16326 @Override registerUserSwitchObserver(IUserSwitchObserver observer, String name)16327 public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) { 16328 mUserController.registerUserSwitchObserver(observer, name); 16329 } 16330 16331 @Override unregisterUserSwitchObserver(IUserSwitchObserver observer)16332 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 16333 mUserController.unregisterUserSwitchObserver(observer); 16334 } 16335 getAppInfoForUser(ApplicationInfo info, int userId)16336 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 16337 if (info == null) return null; 16338 ApplicationInfo newInfo = new ApplicationInfo(info); 16339 newInfo.initForUser(userId); 16340 return newInfo; 16341 } 16342 isUserStopped(int userId)16343 public boolean isUserStopped(int userId) { 16344 return mUserController.getStartedUserState(userId) == null; 16345 } 16346 getActivityInfoForUser(ActivityInfo aInfo, int userId)16347 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 16348 if (aInfo == null 16349 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 16350 return aInfo; 16351 } 16352 16353 ActivityInfo info = new ActivityInfo(aInfo); 16354 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 16355 return info; 16356 } 16357 16358 @GuardedBy("mProcLock") processSanityChecksLPr(ProcessRecord process, IApplicationThread thread)16359 private boolean processSanityChecksLPr(ProcessRecord process, IApplicationThread thread) { 16360 if (process == null || thread == null) { 16361 return false; 16362 } 16363 16364 return Build.IS_DEBUGGABLE || process.isDebuggable(); 16365 } 16366 startBinderTracking()16367 public boolean startBinderTracking() throws RemoteException { 16368 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 16369 // permission (same as profileControl). 16370 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 16371 != PackageManager.PERMISSION_GRANTED) { 16372 throw new SecurityException("Requires permission " 16373 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 16374 } 16375 16376 synchronized (mProcLock) { 16377 mBinderTransactionTrackingEnabled = true; 16378 mProcessList.forEachLruProcessesLOSP(true, process -> { 16379 final IApplicationThread thread = process.getThread(); 16380 if (!processSanityChecksLPr(process, thread)) { 16381 return; 16382 } 16383 try { 16384 thread.startBinderTracking(); 16385 } catch (RemoteException e) { 16386 Log.v(TAG, "Process disappared"); 16387 } 16388 }); 16389 } 16390 return true; 16391 } 16392 16393 @Override stopBinderTrackingAndDump(final ParcelFileDescriptor fd)16394 public boolean stopBinderTrackingAndDump(final ParcelFileDescriptor fd) throws RemoteException { 16395 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 16396 // permission (same as profileControl). 16397 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 16398 != PackageManager.PERMISSION_GRANTED) { 16399 throw new SecurityException("Requires permission " 16400 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 16401 } 16402 16403 boolean closeFd = true; 16404 try { 16405 Objects.requireNonNull(fd); 16406 16407 record ProcessToDump(String processName, IApplicationThread thread) { } 16408 16409 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor())); 16410 pw.println("Binder transaction traces for all processes.\n"); 16411 final ArrayList<ProcessToDump> processes = new ArrayList<>(); 16412 synchronized (mProcLock) { 16413 // Since dumping binder transactions is a long-running operation, we can't do it 16414 // with mProcLock held. Do the initial verification here, and save the processes 16415 // to dump later outside the lock. 16416 final ArrayList<ProcessRecord> unverifiedProcesses = 16417 new ArrayList<>(mProcessList.getLruProcessesLOSP()); 16418 for (int i = 0, size = unverifiedProcesses.size(); i < size; i++) { 16419 ProcessRecord process = unverifiedProcesses.get(i); 16420 final IApplicationThread thread = process.getThread(); 16421 if (!processSanityChecksLPr(process, thread)) { 16422 continue; 16423 } 16424 processes.add(new ProcessToDump(process.processName, process.getThread())); 16425 } 16426 mBinderTransactionTrackingEnabled = false; 16427 } 16428 for (int i = 0, size = processes.size(); i < size; i++) { 16429 final String processName = processes.get(i).processName(); 16430 final IApplicationThread thread = processes.get(i).thread(); 16431 16432 pw.println("Traces for process: " + processName); 16433 pw.flush(); 16434 try { 16435 TransferPipe tp = new TransferPipe(); 16436 try { 16437 thread.stopBinderTrackingAndDump(tp.getWriteFd()); 16438 tp.go(fd.getFileDescriptor()); 16439 } finally { 16440 tp.kill(); 16441 } 16442 } catch (IOException e) { 16443 pw.println("Failure while dumping IPC traces from " + processName + 16444 ". Exception: " + e); 16445 pw.flush(); 16446 } catch (RemoteException e) { 16447 pw.println("Got a RemoteException while dumping IPC traces from " + 16448 processName + ". Exception: " + e); 16449 pw.flush(); 16450 } 16451 } 16452 closeFd = false; 16453 return true; 16454 } finally { 16455 if (fd != null && closeFd) { 16456 try { 16457 fd.close(); 16458 } catch (IOException e) { 16459 } 16460 } 16461 } 16462 } 16463 onProcessFreezableChangedLocked(ProcessRecord app)16464 void onProcessFreezableChangedLocked(ProcessRecord app) { 16465 mBroadcastQueue.onProcessFreezableChangedLocked(app); 16466 } 16467 16468 @VisibleForTesting 16469 public final class LocalService extends ActivityManagerInternal 16470 implements ActivityManagerLocal { 16471 16472 @Override addFrozenProcessListener(int pid, @NonNull Executor executor, @NonNull FrozenProcessListener listener)16473 public void addFrozenProcessListener(int pid, @NonNull Executor executor, 16474 @NonNull FrozenProcessListener listener) { 16475 Objects.requireNonNull(executor); 16476 Objects.requireNonNull(listener); 16477 synchronized (mProcLock) { 16478 final ProcessRecord app; 16479 synchronized (mPidsSelfLocked) { 16480 app = mPidsSelfLocked.get(pid); 16481 } 16482 if (app != null) { 16483 mOomAdjuster.mCachedAppOptimizer.addFrozenProcessListener(app, executor, 16484 listener); 16485 } 16486 } 16487 } 16488 16489 @Override getPendingIntentStats()16490 public List<PendingIntentStats> getPendingIntentStats() { 16491 return mPendingIntentController.dumpPendingIntentStatsForStatsd(); 16492 } 16493 16494 @Override getAppProfileStatsForDebugging(long time, int lines)16495 public Pair<String, String> getAppProfileStatsForDebugging(long time, int lines) { 16496 return mAppProfiler.getAppProfileStatsForDebugging(time, lines); 16497 } 16498 16499 @Override checkContentProviderAccess(String authority, int userId)16500 public String checkContentProviderAccess(String authority, int userId) { 16501 return mCpHelper.checkContentProviderAccess(authority, userId); 16502 } 16503 16504 @Override checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)16505 public int checkContentProviderUriPermission(Uri uri, int userId, 16506 int callingUid, int modeFlags) { 16507 return mCpHelper.checkContentProviderUriPermission(uri, userId, callingUid, modeFlags); 16508 } 16509 16510 @Override onWakefulnessChanged(int wakefulness)16511 public void onWakefulnessChanged(int wakefulness) { 16512 ActivityManagerService.this.onWakefulnessChanged(wakefulness); 16513 } 16514 16515 @Override startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)16516 public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 16517 String processName, String abiOverride, int uid, Runnable crashHandler) { 16518 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 16519 processName, abiOverride, uid, crashHandler); 16520 } 16521 16522 @Override startSdkSandboxService(Intent service, int clientAppUid, String clientAppPackage, String processName)16523 public ComponentName startSdkSandboxService(Intent service, int clientAppUid, 16524 String clientAppPackage, String processName) throws RemoteException { 16525 validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName); 16526 if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) 16527 != AppOpsManager.MODE_ALLOWED) { 16528 throw new IllegalArgumentException("uid does not belong to provided package"); 16529 } 16530 // TODO(b/269598719): Is passing the application thread of the system_server alright? 16531 // e.g. the sandbox getting privileged access due to this. 16532 ComponentName cn = ActivityManagerService.this.startService( 16533 mContext.getIApplicationThread(), service, 16534 service.resolveTypeIfNeeded(mContext.getContentResolver()), false, 16535 mContext.getOpPackageName(), mContext.getAttributionTag(), 16536 UserHandle.getUserId(clientAppUid), true, clientAppUid, clientAppPackage, 16537 processName); 16538 if (cn != null) { 16539 if (cn.getPackageName().equals("!")) { 16540 throw new SecurityException( 16541 "Not allowed to start service " + service 16542 + " without permission " + cn.getClassName()); 16543 } else if (cn.getPackageName().equals("!!")) { 16544 throw new SecurityException( 16545 "Unable to start service " + service 16546 + ": " + cn.getClassName()); 16547 } else if (cn.getPackageName().equals("?")) { 16548 throw ServiceStartNotAllowedException.newInstance(false, 16549 "Not allowed to start service " + service + ": " 16550 + cn.getClassName()); 16551 } 16552 } 16553 16554 return cn; 16555 } 16556 16557 @Override stopSdkSandboxService(Intent service, int clientAppUid, String clientAppPackage, String processName)16558 public boolean stopSdkSandboxService(Intent service, int clientAppUid, 16559 String clientAppPackage, String processName) { 16560 validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName); 16561 int res = ActivityManagerService.this.stopService( 16562 mContext.getIApplicationThread(), service, 16563 service.resolveTypeIfNeeded(mContext.getContentResolver()), 16564 UserHandle.getUserId(clientAppUid), true, clientAppUid, clientAppPackage, 16565 processName); 16566 if (res < 0) { 16567 throw new SecurityException( 16568 "Not allowed to stop service " + service); 16569 } 16570 return res != 0; 16571 } 16572 16573 @Override bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, int flags)16574 public boolean bindSdkSandboxService(Intent service, ServiceConnection conn, 16575 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, 16576 String processName, int flags) 16577 throws RemoteException { 16578 return bindSdkSandboxServiceInternal(service, conn, clientAppUid, 16579 clientApplicationThread, clientAppPackage, processName, 16580 Integer.toUnsignedLong(flags)); 16581 } 16582 16583 @Override bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, BindServiceFlags flags)16584 public boolean bindSdkSandboxService(Intent service, ServiceConnection conn, 16585 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, 16586 String processName, BindServiceFlags flags) throws RemoteException { 16587 return bindSdkSandboxServiceInternal(service, conn, clientAppUid, 16588 clientApplicationThread, clientAppPackage, processName, flags.getValue()); 16589 } 16590 bindSdkSandboxServiceInternal(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, long flags)16591 private boolean bindSdkSandboxServiceInternal(Intent service, ServiceConnection conn, 16592 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, 16593 String processName, long flags) 16594 throws RemoteException { 16595 validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName); 16596 if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) 16597 != AppOpsManager.MODE_ALLOWED) { 16598 throw new IllegalArgumentException("uid does not belong to provided package"); 16599 } 16600 if (conn == null) { 16601 throw new IllegalArgumentException("connection is null"); 16602 } 16603 16604 Handler handler = mContext.getMainThreadHandler(); 16605 IApplicationThread clientApplicationThreadVerified = null; 16606 if (clientApplicationThread != null) { 16607 // Make sure this is a valid application process 16608 synchronized (this) { 16609 final ProcessRecord rec = getRecordForAppLOSP(clientApplicationThread); 16610 if (rec == null) { 16611 // This could happen if the calling process has disappeared; no need for the 16612 // sandbox to be even started in this case. 16613 Slog.i(TAG, "clientApplicationThread process not found."); 16614 return false; 16615 } 16616 if (rec.info.uid != clientAppUid) { 16617 throw new IllegalArgumentException("clientApplicationThread does not match " 16618 + " client uid"); 16619 } 16620 clientApplicationThreadVerified = rec.getThread(); 16621 } 16622 } 16623 final IServiceConnection sd = mContext.getServiceDispatcher(conn, handler, 16624 flags); 16625 service.prepareToLeaveProcess(mContext); 16626 return ActivityManagerService.this.bindServiceInstance( 16627 mContext.getIApplicationThread(), mContext.getActivityToken(), service, 16628 service.resolveTypeIfNeeded(mContext.getContentResolver()), sd, 16629 flags, 16630 processName, /*isSdkSandboxService*/ true, clientAppUid, clientAppPackage, 16631 clientApplicationThreadVerified, mContext.getOpPackageName(), 16632 UserHandle.getUserId(clientAppUid)) != 0; 16633 } 16634 validateSdkSandboxParams(Intent service, int clientAppUid, String clientAppPackage, String processName)16635 private void validateSdkSandboxParams(Intent service, int clientAppUid, 16636 String clientAppPackage, String processName) { 16637 if (service == null) { 16638 throw new IllegalArgumentException("intent is null"); 16639 } 16640 if (clientAppPackage == null) { 16641 throw new IllegalArgumentException("clientAppPackage is null"); 16642 } 16643 if (processName == null) { 16644 throw new IllegalArgumentException("processName is null"); 16645 } 16646 if (service.getComponent() == null) { 16647 throw new IllegalArgumentException("service must specify explicit component"); 16648 } 16649 if (!UserHandle.isApp(clientAppUid)) { 16650 throw new IllegalArgumentException("uid is not within application range"); 16651 } 16652 } 16653 16654 @Override bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, String clientAppPackage, String processName, int flags)16655 public boolean bindSdkSandboxService(Intent service, ServiceConnection conn, 16656 int clientAppUid, String clientAppPackage, String processName, int flags) 16657 throws RemoteException { 16658 return bindSdkSandboxService(service, conn, clientAppUid, 16659 null /* clientApplicationThread */, clientAppPackage, processName, flags); 16660 } 16661 16662 @Override killSdkSandboxClientAppProcess(IBinder clientApplicationThreadBinder)16663 public void killSdkSandboxClientAppProcess(IBinder clientApplicationThreadBinder) { 16664 synchronized (ActivityManagerService.this) { 16665 ProcessRecord r = getRecordForAppLOSP(clientApplicationThreadBinder); 16666 if (r != null) { 16667 r.killLocked( 16668 "sdk sandbox died", 16669 ApplicationExitInfo.REASON_DEPENDENCY_DIED, 16670 ApplicationExitInfo.SUBREASON_SDK_SANDBOX_DIED, 16671 true); 16672 } 16673 } 16674 } 16675 16676 @Override onUserRemoving(@serIdInt int userId)16677 public void onUserRemoving(@UserIdInt int userId) { 16678 // Clean up any ActivityTaskManager state (by telling it the user is stopped) 16679 mAtmInternal.onUserStopped(userId); 16680 // Clean up various services by removing the user 16681 mBatteryStatsService.onUserRemoved(userId); 16682 16683 if (isHomeLaunchDelayable()) { 16684 synchronized (mThemeOverlayReadyUsers) { 16685 mThemeOverlayReadyUsers.remove(userId); 16686 } 16687 } 16688 } 16689 16690 @Override onUserRemoved(int userId)16691 public void onUserRemoved(int userId) { 16692 // Clean up UserController state 16693 mUserController.onUserRemoved(userId); 16694 } 16695 16696 @Override startUserInBackground(final int userId)16697 public boolean startUserInBackground(final int userId) { 16698 return ActivityManagerService.this.startUserInBackground(userId); 16699 } 16700 16701 @Override killForegroundAppsForUser(@serIdInt int userId)16702 public void killForegroundAppsForUser(@UserIdInt int userId) { 16703 final ArrayList<ProcessRecord> procs = new ArrayList<>(); 16704 synchronized (mProcLock) { 16705 final int numOfProcs = mProcessList.getProcessNamesLOSP().getMap().size(); 16706 for (int ip = 0; ip < numOfProcs; ip++) { 16707 final SparseArray<ProcessRecord> apps = 16708 mProcessList.getProcessNamesLOSP().getMap().valueAt(ip); 16709 final int NA = apps.size(); 16710 for (int ia = 0; ia < NA; ia++) { 16711 final ProcessRecord app = apps.valueAt(ia); 16712 if (app.isPersistent()) { 16713 // We don't kill persistent processes. 16714 continue; 16715 } 16716 if (app.isRemoved() 16717 || (app.userId == userId && app.mState.hasForegroundActivities())) { 16718 procs.add(app); 16719 } 16720 } 16721 } 16722 } 16723 16724 final int numOfProcs = procs.size(); 16725 if (numOfProcs > 0) { 16726 synchronized (ActivityManagerService.this) { 16727 for (int i = 0; i < numOfProcs; i++) { 16728 mProcessList.removeProcessLocked(procs.get(i), false, true, 16729 ApplicationExitInfo.REASON_OTHER, 16730 ApplicationExitInfo.SUBREASON_KILL_ALL_FG, 16731 "kill all fg"); 16732 } 16733 } 16734 } 16735 } 16736 16737 @Override setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, int type, @ReasonCode int reasonCode, @Nullable String reason)16738 public void setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, 16739 long duration, int type, @ReasonCode int reasonCode, @Nullable String reason) { 16740 mPendingIntentController.setPendingIntentAllowlistDuration(target, allowlistToken, 16741 duration, type, reasonCode, reason); 16742 } 16743 16744 @Override getPendingIntentFlags(IIntentSender target)16745 public int getPendingIntentFlags(IIntentSender target) { 16746 return mPendingIntentController.getPendingIntentFlags(target); 16747 } 16748 16749 @Override getStartedUserIds()16750 public int[] getStartedUserIds() { 16751 return mUserController.getStartedUserArray(); 16752 } 16753 16754 @Override setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken, int flags)16755 public void setPendingIntentAllowBgActivityStarts(IIntentSender target, 16756 IBinder allowlistToken, int flags) { 16757 if (!(target instanceof PendingIntentRecord)) { 16758 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():" 16759 + " not a PendingIntentRecord: " + target); 16760 return; 16761 } 16762 synchronized (ActivityManagerService.this) { 16763 ((PendingIntentRecord) target).setAllowBgActivityStarts(allowlistToken, flags); 16764 } 16765 } 16766 16767 @Override clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)16768 public void clearPendingIntentAllowBgActivityStarts(IIntentSender target, 16769 IBinder allowlistToken) { 16770 if (!(target instanceof PendingIntentRecord)) { 16771 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():" 16772 + " not a PendingIntentRecord: " + target); 16773 return; 16774 } 16775 synchronized (ActivityManagerService.this) { 16776 ((PendingIntentRecord) target).clearAllowBgActivityStarts(allowlistToken); 16777 } 16778 } 16779 16780 @Override setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)16781 public void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids) { 16782 synchronized (ActivityManagerService.this) { 16783 synchronized (mProcLock) { 16784 mDeviceIdleAllowlist = allAppids; 16785 mDeviceIdleExceptIdleAllowlist = exceptIdleAppids; 16786 mAppRestrictionController.setDeviceIdleAllowlist(allAppids, exceptIdleAppids); 16787 } 16788 } 16789 } 16790 16791 @Override updateDeviceIdleTempAllowlist(@ullable int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)16792 public void updateDeviceIdleTempAllowlist(@Nullable int[] appids, int changingUid, 16793 boolean adding, long durationMs, @TempAllowListType int type, 16794 @ReasonCode int reasonCode, @Nullable String reason, int callingUid) { 16795 synchronized (ActivityManagerService.this) { 16796 synchronized (mProcLock) { 16797 if (appids != null) { 16798 mDeviceIdleTempAllowlist = appids; 16799 } 16800 if (adding) { 16801 if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) { 16802 // Note, the device idle temp-allowlist are by app-ids, but here 16803 // mFgsStartTempAllowList contains UIDs. 16804 mFgsStartTempAllowList.add(changingUid, durationMs, 16805 new FgsTempAllowListItem(durationMs, reasonCode, reason, 16806 callingUid)); 16807 } 16808 } else { 16809 mFgsStartTempAllowList.removeUid(changingUid); 16810 } 16811 setUidTempAllowlistStateLSP(changingUid, adding); 16812 } 16813 } 16814 } 16815 16816 @Override getUidProcessState(int uid)16817 public int getUidProcessState(int uid) { 16818 return getUidState(uid); 16819 } 16820 16821 @Override getProcessesWithPendingBindMounts(int userId)16822 public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) { 16823 return mProcessList.getProcessesWithPendingBindMounts(userId); 16824 } 16825 16826 @Override isSystemReady()16827 public boolean isSystemReady() { 16828 // no need to synchronize(this) just to read & return the value 16829 return mSystemReady; 16830 } 16831 16832 @Override enforceBroadcastOptionsPermissions(Bundle options, int callingUid)16833 public void enforceBroadcastOptionsPermissions(Bundle options, int callingUid) { 16834 mBroadcastController.enforceBroadcastOptionPermissionsInternal(options, callingUid); 16835 } 16836 16837 /** 16838 * Returns package name by pid. 16839 */ 16840 @Override 16841 @Nullable getPackageNameByPid(int pid)16842 public String getPackageNameByPid(int pid) { 16843 synchronized (mPidsSelfLocked) { 16844 final ProcessRecord app = mPidsSelfLocked.get(pid); 16845 16846 if (app != null && app.info != null) { 16847 return app.info.packageName; 16848 } 16849 16850 return null; 16851 } 16852 } 16853 16854 /** 16855 * Sets if the given pid has an overlay UI or not. 16856 * 16857 * @param pid The pid we are setting overlay UI for. 16858 * @param hasOverlayUi True if the process has overlay UI. 16859 * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY 16860 */ 16861 @Override setHasOverlayUi(int pid, boolean hasOverlayUi)16862 public void setHasOverlayUi(int pid, boolean hasOverlayUi) { 16863 synchronized (ActivityManagerService.this) { 16864 final ProcessRecord pr; 16865 synchronized (mPidsSelfLocked) { 16866 pr = mPidsSelfLocked.get(pid); 16867 if (pr == null) { 16868 Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid); 16869 return; 16870 } 16871 } 16872 if (mProcessStateController.setHasOverlayUi(pr, hasOverlayUi)) { 16873 mProcessStateController.runUpdate(pr, OOM_ADJ_REASON_UI_VISIBILITY); 16874 } 16875 } 16876 } 16877 16878 /** 16879 * Called after the network policy rules are updated by 16880 * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid} 16881 * and {@param procStateSeq}. 16882 */ 16883 @Override notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)16884 public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) { 16885 if (DEBUG_NETWORK) { 16886 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: " 16887 + uid + " seq: " + procStateSeq); 16888 } 16889 UidRecord record; 16890 synchronized (mProcLock) { 16891 record = mProcessList.getUidRecordLOSP(uid); 16892 if (record == null) { 16893 if (DEBUG_NETWORK) { 16894 Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid 16895 + " procStateSeq: " + procStateSeq); 16896 } 16897 return; 16898 } 16899 } 16900 synchronized (record.networkStateLock) { 16901 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 16902 if (DEBUG_NETWORK) { 16903 Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already" 16904 + " been handled for uid: " + uid); 16905 } 16906 return; 16907 } 16908 record.lastNetworkUpdatedProcStateSeq = procStateSeq; 16909 if (record.procStateSeqWaitingForNetwork != 0 16910 && procStateSeq >= record.procStateSeqWaitingForNetwork) { 16911 if (DEBUG_NETWORK) { 16912 Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid 16913 + ", procStateSeq: " + procStateSeq 16914 + ", procStateSeqWaitingForNetwork: " 16915 + record.procStateSeqWaitingForNetwork); 16916 } 16917 record.networkStateLock.notifyAll(); 16918 } 16919 } 16920 } 16921 16922 @Override onUidBlockedReasonsChanged(int uid, int blockedReasons)16923 public void onUidBlockedReasonsChanged(int uid, int blockedReasons) { 16924 synchronized (mUidNetworkBlockedReasons) { 16925 if (blockedReasons == BLOCKED_REASON_NONE) { 16926 mUidNetworkBlockedReasons.delete(uid); 16927 } else { 16928 mUidNetworkBlockedReasons.put(uid, blockedReasons); 16929 } 16930 } 16931 } 16932 16933 @Override isRuntimeRestarted()16934 public boolean isRuntimeRestarted() { 16935 return mSystemServiceManager.isRuntimeRestarted(); 16936 } 16937 16938 @Override canStartMoreUsers()16939 public boolean canStartMoreUsers() { 16940 return mUserController.canStartMoreUsers(); 16941 } 16942 16943 @Override setSwitchingFromUserMessage(@serIdInt int userId, @Nullable String message)16944 public void setSwitchingFromUserMessage(@UserIdInt int userId, @Nullable String message) { 16945 mUserController.setSwitchingFromUserMessage(userId, message); 16946 } 16947 16948 @Override setSwitchingToUserMessage(@serIdInt int userId, @Nullable String message)16949 public void setSwitchingToUserMessage(@UserIdInt int userId, @Nullable String message) { 16950 mUserController.setSwitchingToUserMessage(userId, message); 16951 } 16952 16953 @Override getMaxRunningUsers()16954 public int getMaxRunningUsers() { 16955 return mUserController.getMaxRunningUsers(); 16956 } 16957 16958 @Override isUidActive(int uid)16959 public boolean isUidActive(int uid) { 16960 synchronized (mProcLock) { 16961 return isUidActiveLOSP(uid); 16962 } 16963 } 16964 16965 @Override getMemoryStateForProcesses()16966 public List<ProcessMemoryState> getMemoryStateForProcesses() { 16967 List<ProcessMemoryState> processMemoryStates = new ArrayList<>(); 16968 synchronized (mPidsSelfLocked) { 16969 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 16970 final ProcessRecord r = mPidsSelfLocked.valueAt(i); 16971 processMemoryStates.add(new ProcessMemoryState( 16972 r.uid, r.getPid(), r.processName, r.mState.getCurAdj(), 16973 r.mServices.hasForegroundServices(), 16974 r.mProfile.getCurrentHostingComponentTypes(), 16975 r.mProfile.getHistoricalHostingComponentTypes())); 16976 } 16977 } 16978 return processMemoryStates; 16979 } 16980 16981 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)16982 public int handleIncomingUser(int callingPid, int callingUid, int userId, 16983 boolean allowAll, int allowMode, String name, String callerPackage) { 16984 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 16985 allowMode, name, callerPackage); 16986 } 16987 16988 @Override enforceCallingPermission(String permission, String func)16989 public void enforceCallingPermission(String permission, String func) { 16990 ActivityManagerService.this.enforceCallingPermission(permission, func); 16991 } 16992 16993 @Override getCurrentAndTargetUserIds()16994 public Pair<Integer, Integer> getCurrentAndTargetUserIds() { 16995 return mUserController.getCurrentAndTargetUserIds(); 16996 } 16997 16998 @Override getCurrentUserId()16999 public int getCurrentUserId() { 17000 return mUserController.getCurrentUserId(); 17001 } 17002 17003 @Override isUserRunning(int userId, int flags)17004 public boolean isUserRunning(int userId, int flags) { 17005 // Holding am lock isn't required to call into user controller. 17006 return mUserController.isUserRunning(userId, flags); 17007 } 17008 17009 @Override trimApplications()17010 public void trimApplications() { 17011 ActivityManagerService.this.trimApplications(true, OOM_ADJ_REASON_ACTIVITY); 17012 } 17013 killProcessesForRemovedTask(ArrayList<Object> procsToKill)17014 public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) { 17015 synchronized (ActivityManagerService.this) { 17016 for (int i = 0; i < procsToKill.size(); i++) { 17017 final WindowProcessController wpc = 17018 (WindowProcessController) procsToKill.get(i); 17019 final ProcessRecord pr = (ProcessRecord) wpc.mOwner; 17020 if (ActivityManager.isProcStateBackground(pr.mState.getSetProcState()) 17021 && pr.mReceivers.numberOfCurReceivers() == 0 17022 && !pr.mState.hasStartedServices()) { 17023 pr.killLocked("remove task", ApplicationExitInfo.REASON_USER_REQUESTED, 17024 ApplicationExitInfo.SUBREASON_REMOVE_TASK, true); 17025 } else { 17026 // We delay killing processes that are not in the background or running a 17027 // receiver. 17028 pr.setWaitingToKill("remove task"); 17029 } 17030 } 17031 } 17032 } 17033 17034 @Override killProcess(String processName, int uid, String reason)17035 public void killProcess(String processName, int uid, String reason) { 17036 synchronized (ActivityManagerService.this) { 17037 final ProcessRecord proc = getProcessRecordLocked(processName, uid); 17038 if (proc != null) { 17039 mProcessList.removeProcessLocked(proc, false /* callerWillRestart */, 17040 true /* allowRestart */, ApplicationExitInfo.REASON_OTHER, reason); 17041 } 17042 } 17043 } 17044 17045 @Override hasRunningActivity(int uid, @Nullable String packageName)17046 public boolean hasRunningActivity(int uid, @Nullable String packageName) { 17047 if (packageName == null) return false; 17048 17049 synchronized (mProcLock) { 17050 return mProcessList.searchEachLruProcessesLOSP(true, app -> { 17051 if (app.uid == uid 17052 && app.getWindowProcessController().hasRunningActivity(packageName)) { 17053 return Boolean.TRUE; 17054 } 17055 return null; 17056 }) != null; 17057 } 17058 } 17059 17060 @Override updateOomAdj(@omAdjReason int oomAdjReason)17061 public void updateOomAdj(@OomAdjReason int oomAdjReason) { 17062 synchronized (ActivityManagerService.this) { 17063 ActivityManagerService.this.updateOomAdjLocked(oomAdjReason); 17064 } 17065 } 17066 17067 @Override updateCpuStats()17068 public void updateCpuStats() { 17069 ActivityManagerService.this.updateCpuStats(); 17070 } 17071 17072 @Override updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)17073 public void updateBatteryStats(ComponentName activity, int uid, int userId, 17074 boolean resumed) { 17075 ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed); 17076 } 17077 17078 @Override updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)17079 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 17080 IBinder appToken, ComponentName taskRoot, ActivityId activityId) { 17081 ActivityManagerService.this.updateActivityUsageStats(activity, userId, event, 17082 appToken, taskRoot, activityId); 17083 } 17084 17085 @Override updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)17086 public void updateForegroundTimeIfOnBattery( 17087 String packageName, int uid, long cpuTimeDiff) { 17088 mBatteryStatsService.updateForegroundTimeIfOnBattery(packageName, uid, cpuTimeDiff); 17089 } 17090 17091 @Override sendForegroundProfileChanged(int userId)17092 public void sendForegroundProfileChanged(int userId) { 17093 mUserController.sendForegroundProfileChanged(userId); 17094 } 17095 17096 @Override shouldConfirmCredentials(int userId)17097 public boolean shouldConfirmCredentials(int userId) { 17098 return mUserController.shouldConfirmCredentials(userId); 17099 } 17100 17101 @Override noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)17102 public void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, 17103 String tag) { 17104 ActivityManagerService.this.noteAlarmFinish((ps != null) ? ps.getTarget() : null, 17105 workSource, sourceUid, tag); 17106 } 17107 17108 @Override noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)17109 public void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, 17110 String tag) { 17111 ActivityManagerService.this.noteAlarmStart((ps != null) ? ps.getTarget() : null, 17112 workSource, sourceUid, tag); 17113 } 17114 17115 @Override noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)17116 public void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, 17117 String sourcePkg, String tag) { 17118 ActivityManagerService.this.noteWakeupAlarm((ps != null) ? ps.getTarget() : null, 17119 workSource, sourceUid, sourcePkg, tag); 17120 } 17121 17122 @Override isAppStartModeDisabled(int uid, String packageName)17123 public boolean isAppStartModeDisabled(int uid, String packageName) { 17124 return ActivityManagerService.this.isAppStartModeDisabled(uid, packageName); 17125 } 17126 17127 @Override getCurrentProfileIds()17128 public int[] getCurrentProfileIds() { 17129 return mUserController.getCurrentProfileIds(); 17130 } 17131 17132 @Override getCurrentUser()17133 public UserInfo getCurrentUser() { 17134 return mUserController.getCurrentUser(); 17135 } 17136 17137 @Override ensureNotSpecialUser(int userId)17138 public void ensureNotSpecialUser(int userId) { 17139 mUserController.ensureNotSpecialUser(userId); 17140 } 17141 17142 @Override isCurrentProfile(int userId)17143 public boolean isCurrentProfile(int userId) { 17144 return mUserController.isCurrentProfile(userId); 17145 } 17146 17147 @Override hasStartedUserState(int userId)17148 public boolean hasStartedUserState(int userId) { 17149 return mUserController.hasStartedUserState(userId); 17150 } 17151 17152 @Override finishUserSwitch(Object uss)17153 public void finishUserSwitch(Object uss) { 17154 mUserController.finishUserSwitch((UserState) uss); 17155 } 17156 17157 @Override scheduleAppGcs()17158 public void scheduleAppGcs() { 17159 synchronized (mAppProfiler.mProfilerLock) { 17160 mAppProfiler.scheduleAppGcsLPf(); 17161 } 17162 } 17163 17164 @Override getTaskIdForActivity(IBinder token, boolean onlyRoot)17165 public int getTaskIdForActivity(IBinder token, boolean onlyRoot) { 17166 return ActivityManagerService.this.getTaskForActivity(token, onlyRoot); 17167 } 17168 17169 @Override getActivityPresentationInfo(IBinder token)17170 public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) { 17171 final ActivityClient ac = ActivityClient.getInstance(); 17172 return new ActivityPresentationInfo(ac.getTaskForActivity(token, 17173 /*onlyRoot=*/ false), ac.getDisplayId(token), 17174 mAtmInternal.getActivityName(token)); 17175 } 17176 17177 @Override setBooting(boolean booting)17178 public void setBooting(boolean booting) { 17179 mBooting = booting; 17180 } 17181 17182 @Override isBooting()17183 public boolean isBooting() { 17184 return mBooting; 17185 } 17186 17187 @Override setBooted(boolean booted)17188 public void setBooted(boolean booted) { 17189 mBooted = booted; 17190 } 17191 17192 @Override isBooted()17193 public boolean isBooted() { 17194 return mBooted; 17195 } 17196 17197 @Override finishBooting()17198 public void finishBooting() { 17199 ActivityManagerService.this.finishBooting(); 17200 } 17201 17202 @Override tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)17203 public void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, 17204 long duration, int type, @ReasonCode int reasonCode, String reason) { 17205 synchronized (ActivityManagerService.this) { 17206 ActivityManagerService.this.tempAllowlistForPendingIntentLocked( 17207 callerPid, callerUid, targetUid, duration, type, reasonCode, reason); 17208 } 17209 } 17210 17211 @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)17212 public int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, 17213 int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 17214 IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode, 17215 String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, 17216 boolean serialized, boolean sticky, int userId, 17217 BackgroundStartPrivileges backgroundStartPrivileges, 17218 @Nullable int[] broadcastAllowList) { 17219 synchronized (ActivityManagerService.this) { 17220 final ProcessRecord resultToApp = getRecordForAppLOSP(resultToThread); 17221 return mBroadcastController.broadcastIntentInPackage(packageName, featureId, 17222 uid, realCallingUid, realCallingPid, intent, resolvedType, resultToApp, 17223 resultTo, resultCode, resultData, resultExtras, requiredPermission, 17224 bOptions, serialized, sticky, userId, 17225 backgroundStartPrivileges, 17226 broadcastAllowList); 17227 } 17228 } 17229 17230 @Override broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)17231 public int broadcastIntent(Intent intent, 17232 IIntentReceiver resultTo, 17233 String[] requiredPermissions, 17234 boolean serialized, int userId, int[] appIdAllowList, 17235 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 17236 @Nullable Bundle bOptions) { 17237 synchronized (ActivityManagerService.this) { 17238 intent = mBroadcastController.verifyBroadcastLocked(intent); 17239 17240 final int callingPid = Binder.getCallingPid(); 17241 final int callingUid = Binder.getCallingUid(); 17242 final long origId = Binder.clearCallingIdentity(); 17243 try { 17244 return mBroadcastController.broadcastIntentLocked(null /*callerApp*/, 17245 null /*callerPackage*/, null /*callingFeatureId*/, intent, 17246 null /* resolvedType */, null /* resultToApp */, resultTo, 17247 0 /* resultCode */, null /* resultData */, 17248 null /* resultExtras */, requiredPermissions, 17249 null /*excludedPermissions*/, null /*excludedPackages*/, 17250 AppOpsManager.OP_NONE, bOptions /*options*/, serialized, 17251 false /*sticky*/, callingPid, callingUid, callingUid, callingPid, 17252 userId, BackgroundStartPrivileges.NONE, 17253 appIdAllowList, filterExtrasForReceiver); 17254 } finally { 17255 Binder.restoreCallingIdentity(origId); 17256 } 17257 } 17258 } 17259 17260 @Override broadcastIntentWithCallback(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)17261 public int broadcastIntentWithCallback(Intent intent, 17262 IIntentReceiver resultTo, 17263 String[] requiredPermissions, 17264 int userId, int[] appIdAllowList, 17265 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 17266 @Nullable Bundle bOptions) { 17267 return broadcastIntent(intent, resultTo, requiredPermissions, false /* serialized */, 17268 userId, appIdAllowList, filterExtrasForReceiver, bOptions); 17269 } 17270 17271 @Override startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, int userId, BackgroundStartPrivileges backgroundStartPrivileges)17272 public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType, 17273 boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, 17274 int userId, BackgroundStartPrivileges backgroundStartPrivileges) 17275 throws TransactionTooLargeException { 17276 if (DEBUG_SERVICE) { 17277 Slog.v(TAG_SERVICE, 17278 "startServiceInPackage: " + service + " type=" + resolvedType); 17279 } 17280 addCreatorToken(service, callingPackage); 17281 final long origId = Binder.clearCallingIdentity(); 17282 ComponentName res; 17283 try { 17284 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 17285 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startServiceInPackage: " 17286 + "intent=" + service + ", caller=" + callingPackage 17287 + ", fgRequired=" + fgRequired); 17288 } 17289 synchronized (ActivityManagerService.this) { 17290 res = mServices.startServiceLocked(null, service, 17291 resolvedType, -1, uid, fgRequired, callingPackage, 17292 callingFeatureId, userId, 17293 backgroundStartPrivileges); 17294 } 17295 } finally { 17296 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 17297 Binder.restoreCallingIdentity(origId); 17298 } 17299 return res; 17300 } 17301 17302 // The arguments here are untyped because the base ActivityManagerInternal class 17303 // doesn't have compile-time visibility into ActivityServiceConnectionHolder or 17304 // ConnectionRecord. 17305 @Override disconnectActivityFromServices(Object connectionHolder)17306 public void disconnectActivityFromServices(Object connectionHolder) { 17307 // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder 17308 final ActivityServiceConnectionsHolder holder = 17309 (ActivityServiceConnectionsHolder) connectionHolder; 17310 synchronized (ActivityManagerService.this) { 17311 synchronized (mProcLock) { 17312 holder.forEachConnection(cr -> mServices.removeConnectionLocked( 17313 (ConnectionRecord) cr, null /* skipApp */, holder /* skipAct */, 17314 false /* enqueueOomAdj */)); 17315 } 17316 } 17317 } 17318 cleanUpServices(int userId, ComponentName component, Intent baseIntent)17319 public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) { 17320 synchronized(ActivityManagerService.this) { 17321 mServices.cleanUpServices(userId, component, baseIntent); 17322 } 17323 } 17324 getActivityInfoForUser(ActivityInfo aInfo, int userId)17325 public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 17326 // Locked intentionally not held as it isn't needed for this case. 17327 return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId); 17328 } 17329 ensureBootCompleted()17330 public void ensureBootCompleted() { 17331 // Locked intentionally not held as it isn't needed for this case. 17332 ActivityManagerService.this.ensureBootCompleted(); 17333 } 17334 updateOomLevelsForDisplay(int displayId)17335 public void updateOomLevelsForDisplay(int displayId) { 17336 synchronized(ActivityManagerService.this) { 17337 if (mWindowManager != null) { 17338 mProcessList.applyDisplaySize(mWindowManager); 17339 } 17340 } 17341 } 17342 isActivityStartsLoggingEnabled()17343 public boolean isActivityStartsLoggingEnabled() { 17344 return mConstants.mFlagActivityStartsLoggingEnabled; 17345 } 17346 isBackgroundActivityStartsEnabled()17347 public boolean isBackgroundActivityStartsEnabled() { 17348 return mConstants.mFlagBackgroundActivityStartsEnabled; 17349 } 17350 17351 @Override getBackgroundStartPrivileges(int uid)17352 public BackgroundStartPrivileges getBackgroundStartPrivileges(int uid) { 17353 return ActivityManagerService.this.getBackgroundStartPrivileges(uid); 17354 } 17355 17356 @Override canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)17357 public boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName) { 17358 return ActivityManagerService.this.canScheduleUserInitiatedJobs(uid, pid, pkgName); 17359 } 17360 reportCurKeyguardUsageEvent(boolean keyguardShowing)17361 public void reportCurKeyguardUsageEvent(boolean keyguardShowing) { 17362 ActivityManagerService.this.reportGlobalUsageEvent(keyguardShowing 17363 ? UsageEvents.Event.KEYGUARD_SHOWN 17364 : UsageEvents.Event.KEYGUARD_HIDDEN); 17365 } 17366 17367 @Override monitor()17368 public void monitor() { 17369 ActivityManagerService.this.monitor(); 17370 } 17371 17372 @Override inputDispatchingTimedOut(int pid, boolean aboveSystem, TimeoutRecord timeoutRecord)17373 public long inputDispatchingTimedOut(int pid, boolean aboveSystem, 17374 TimeoutRecord timeoutRecord) { 17375 return ActivityManagerService.this.inputDispatchingTimedOut(pid, aboveSystem, 17376 timeoutRecord); 17377 } 17378 17379 @Override inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, TimeoutRecord timeoutRecord)17380 public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName, 17381 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, 17382 boolean aboveSystem, TimeoutRecord timeoutRecord) { 17383 return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc, 17384 activityShortComponentName, aInfo, parentShortComponentName, 17385 (WindowProcessController) parentProc, aboveSystem, timeoutRecord); 17386 } 17387 17388 @Override inputDispatchingResumed(int pid)17389 public void inputDispatchingResumed(int pid) { 17390 final ProcessRecord proc; 17391 synchronized (mPidsSelfLocked) { 17392 proc = mPidsSelfLocked.get(pid); 17393 } 17394 if (proc != null) { 17395 mAppErrors.handleDismissAnrDialogs(proc); 17396 } 17397 } 17398 17399 @Override rescheduleAnrDialog(Object data)17400 public void rescheduleAnrDialog(Object data) { 17401 Message msg = Message.obtain(); 17402 msg.what = SHOW_NOT_RESPONDING_UI_MSG; 17403 msg.obj = (AppNotRespondingDialog.Data) data; 17404 17405 mUiHandler.sendMessageDelayed(msg, InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS); 17406 } 17407 17408 @Override broadcastGlobalConfigurationChanged(int changes, boolean initLocale)17409 public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) { 17410 synchronized (ActivityManagerService.this) { 17411 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 17412 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17413 | Intent.FLAG_RECEIVER_REPLACE_PENDING 17414 | Intent.FLAG_RECEIVER_FOREGROUND 17415 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 17416 final Bundle configChangedOptions = new BroadcastOptions() 17417 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT) 17418 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE) 17419 .toBundle(); 17420 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 17421 null, null, OP_NONE, configChangedOptions, false, false, MY_PID, SYSTEM_UID, 17422 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 17423 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) { 17424 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 17425 intent.addFlags(Intent.FLAG_RECEIVER_OFFLOAD_FOREGROUND 17426 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND 17427 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 17428 if (initLocale || !mProcessesReady) { 17429 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 17430 } 17431 final BroadcastOptions bOptions = BroadcastOptions.makeBasic(); 17432 bOptions.setTemporaryAppAllowlist(mInternal.getBootTimeTempAllowListDuration(), 17433 TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED, 17434 PowerExemptionManager.REASON_LOCALE_CHANGED, ""); 17435 bOptions.setDeliveryGroupPolicy( 17436 BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT); 17437 bOptions.setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE); 17438 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 17439 null, null, OP_NONE, bOptions.toBundle(), false, false, MY_PID, 17440 SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(), 17441 UserHandle.USER_ALL); 17442 } 17443 17444 // Send a broadcast to PackageInstallers if the configuration change is interesting 17445 // for the purposes of installing additional splits. 17446 if (!initLocale && isSplitConfigurationChange(changes)) { 17447 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED); 17448 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING 17449 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 17450 17451 // Typically only app stores will have this permission. 17452 String[] permissions = 17453 new String[] { android.Manifest.permission.INSTALL_PACKAGES }; 17454 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, 17455 permissions, null, null, OP_NONE, null, false, false, MY_PID, 17456 SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(), 17457 UserHandle.USER_ALL); 17458 } 17459 } 17460 } 17461 17462 /** 17463 * Returns true if this configuration change is interesting enough to send an 17464 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast. 17465 */ isSplitConfigurationChange(int configDiff)17466 private boolean isSplitConfigurationChange(int configDiff) { 17467 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0; 17468 } 17469 17470 @Override broadcastCloseSystemDialogs(String reason)17471 public void broadcastCloseSystemDialogs(String reason) { 17472 synchronized (ActivityManagerService.this) { 17473 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 17474 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17475 | Intent.FLAG_RECEIVER_FOREGROUND); 17476 if (reason != null) { 17477 intent.putExtra("reason", reason); 17478 } 17479 17480 final BroadcastOptions options = new BroadcastOptions() 17481 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT) 17482 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE); 17483 if (reason != null) { 17484 options.setDeliveryGroupMatchingKey(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, reason); 17485 } 17486 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 17487 null, null, OP_NONE, options.toBundle(), false, false, -1, SYSTEM_UID, 17488 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 17489 } 17490 } 17491 17492 @Override appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)17493 public void appNotResponding(@NonNull String processName, int uid, 17494 @NonNull TimeoutRecord timeoutRecord) { 17495 ActivityManagerService.this.appNotResponding(processName, uid, timeoutRecord); 17496 } 17497 17498 @Override killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)17499 public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 17500 synchronized (ActivityManagerService.this) { 17501 ActivityManagerService.this.killAllBackgroundProcessesExcept( 17502 minTargetSdk, maxProcState); 17503 } 17504 } 17505 17506 @Override startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)17507 public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, 17508 boolean isTop, String hostingType, ComponentName hostingName) { 17509 try { 17510 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 17511 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:" 17512 + processName); 17513 } 17514 synchronized (ActivityManagerService.this) { 17515 // If the process is known as top app, set a hint so when the process is 17516 // started, the top priority can be applied immediately to avoid cpu being 17517 // preempted by other processes before attaching the process of top app. 17518 HostingRecord hostingRecord = 17519 new HostingRecord(hostingType, hostingName, isTop); 17520 ProcessRecord rec = getProcessRecordLocked(processName, info.uid); 17521 ProcessRecord app = startProcessLocked(processName, info, knownToBeDead, 17522 0 /* intentFlags */, hostingRecord, 17523 ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */, 17524 false /* isolated */); 17525 } 17526 } finally { 17527 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 17528 } 17529 } 17530 17531 @Override setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)17532 public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, 17533 ProfilerInfo profilerInfo, Object wmLock) { 17534 synchronized (ActivityManagerService.this) { 17535 /** 17536 * This function is called from the window manager context and needs to be executed 17537 * synchronously. To avoid deadlock, we pass a message to AMS to execute the 17538 * function and notify the passed in lock when it has been completed. 17539 */ 17540 synchronized (wmLock) { 17541 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) { 17542 boolean suspend = 17543 (startFlags & ActivityManager.START_FLAG_DEBUG_SUSPEND) != 0; 17544 setDebugApp(aInfo.processName, true, false, suspend); 17545 } 17546 17547 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) { 17548 setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName); 17549 } 17550 17551 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) { 17552 setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName); 17553 } 17554 17555 if (profilerInfo != null) { 17556 // We only support normal method tracing along with app startup for now. 17557 setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo, 17558 null, /*profileType= */ ProfilerInfo.PROFILE_TYPE_REGULAR); 17559 } 17560 wmLock.notify(); 17561 } 17562 } 17563 } 17564 17565 @Override getStorageMountMode(int pid, int uid)17566 public int getStorageMountMode(int pid, int uid) { 17567 if (uid == SHELL_UID || uid == ROOT_UID) { 17568 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17569 } 17570 synchronized (mPidsSelfLocked) { 17571 final ProcessRecord pr = mPidsSelfLocked.get(pid); 17572 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.getMountMode(); 17573 } 17574 } 17575 17576 @Override isAppForeground(int uid)17577 public boolean isAppForeground(int uid) { 17578 return ActivityManagerService.this.isAppForeground(uid); 17579 } 17580 17581 @Override isAppBad(final String processName, final int uid)17582 public boolean isAppBad(final String processName, final int uid) { 17583 return ActivityManagerService.this.isAppBad(processName, uid); 17584 } 17585 17586 @Override clearPendingBackup(int userId)17587 public void clearPendingBackup(int userId) { 17588 ActivityManagerService.this.clearPendingBackup(userId); 17589 } 17590 17591 /** 17592 * When power button is very long pressed, call this interface to do some pre-shutdown work 17593 * like persisting database etc. 17594 */ 17595 @Override prepareForPossibleShutdown()17596 public void prepareForPossibleShutdown() { 17597 ActivityManagerService.this.prepareForPossibleShutdown(); 17598 } 17599 17600 @Override hasRunningForegroundService(int uid, int foregroundServicetype)17601 public boolean hasRunningForegroundService(int uid, int foregroundServicetype) { 17602 synchronized (ActivityManagerService.this) { 17603 final UidRecord uidRec = mProcessList.mActiveUids.get(uid); 17604 if (uidRec == null) { 17605 return false; 17606 } 17607 for (int i = uidRec.getNumOfProcs() - 1; i >= 0; i--) { 17608 final ProcessRecord app = uidRec.getProcessRecordByIndex(i); 17609 if ((app.mServices.containsAnyForegroundServiceTypes(foregroundServicetype))) { 17610 return true; 17611 } 17612 } 17613 return false; 17614 } 17615 } 17616 17617 @Override hasForegroundServiceNotification(String pkg, int userId, String channelId)17618 public boolean hasForegroundServiceNotification(String pkg, int userId, 17619 String channelId) { 17620 synchronized (ActivityManagerService.this) { 17621 return mServices.hasForegroundServiceNotificationLocked(pkg, userId, channelId); 17622 } 17623 } 17624 17625 @Override applyForegroundServiceNotification( Notification notification, String tag, int id, String pkg, int userId)17626 public ServiceNotificationPolicy applyForegroundServiceNotification( 17627 Notification notification, String tag, int id, String pkg, int userId) { 17628 synchronized (ActivityManagerService.this) { 17629 return mServices.applyForegroundServiceNotificationLocked(notification, 17630 tag, id, pkg, userId); 17631 } 17632 } 17633 17634 @Override onForegroundServiceNotificationUpdate(boolean shown, Notification notification, int id, String pkg, @UserIdInt int userId)17635 public void onForegroundServiceNotificationUpdate(boolean shown, 17636 Notification notification, int id, String pkg, @UserIdInt int userId) { 17637 synchronized (ActivityManagerService.this) { 17638 mServices.onForegroundServiceNotificationUpdateLocked(shown, 17639 notification, id, pkg, userId); 17640 } 17641 } 17642 17643 @Override stopAppForUser(String pkg, @UserIdInt int userId)17644 public void stopAppForUser(String pkg, @UserIdInt int userId) { 17645 ActivityManagerService.this.stopAppForUserInternal(pkg, userId); 17646 } 17647 17648 @Override registerProcessObserver(IProcessObserver processObserver)17649 public void registerProcessObserver(IProcessObserver processObserver) { 17650 ActivityManagerService.this.registerProcessObserver(processObserver); 17651 } 17652 17653 @Override unregisterProcessObserver(IProcessObserver processObserver)17654 public void unregisterProcessObserver(IProcessObserver processObserver) { 17655 ActivityManagerService.this.unregisterProcessObserver(processObserver); 17656 } 17657 17658 @Override getInstrumentationSourceUid(int uid)17659 public int getInstrumentationSourceUid(int uid) { 17660 synchronized (mProcLock) { 17661 for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) { 17662 ActiveInstrumentation activeInst = mActiveInstrumentation.get(i); 17663 if (!activeInst.mFinished && activeInst.mTargetInfo != null 17664 && activeInst.mTargetInfo.uid == uid) { 17665 return activeInst.mSourceUid; 17666 } 17667 } 17668 } 17669 return INVALID_UID; 17670 } 17671 17672 @Override setDeviceOwnerUid(int uid)17673 public void setDeviceOwnerUid(int uid) { 17674 mDeviceOwnerUid = uid; 17675 } 17676 17677 @Override isDeviceOwner(int uid)17678 public boolean isDeviceOwner(int uid) { 17679 int cachedUid = mDeviceOwnerUid; 17680 return uid >= 0 && cachedUid == uid; 17681 } 17682 17683 17684 @Override setProfileOwnerUid(ArraySet<Integer> profileOwnerUids)17685 public void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids) { 17686 synchronized (mProfileOwnerUids) { 17687 mProfileOwnerUids.clear(); 17688 mProfileOwnerUids.addAll(profileOwnerUids); 17689 } 17690 } 17691 17692 @Override isProfileOwner(int uid)17693 public boolean isProfileOwner(int uid) { 17694 synchronized (mProfileOwnerUids) { 17695 return mProfileOwnerUids.indexOf(uid) >= 0; 17696 } 17697 } 17698 17699 @Override setCompanionAppUids(int userId, Set<Integer> companionAppUids)17700 public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) { 17701 synchronized (mCompanionAppUidsMap) { 17702 mCompanionAppUidsMap.put(userId, companionAppUids); 17703 } 17704 } 17705 17706 @Override isAssociatedCompanionApp(int userId, int uid)17707 public boolean isAssociatedCompanionApp(int userId, int uid) { 17708 synchronized (mCompanionAppUidsMap) { 17709 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId); 17710 if (allUids == null) { 17711 return false; 17712 } 17713 return allUids.contains(uid); 17714 } 17715 } 17716 17717 @Override addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread)17718 public void addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread) { 17719 final boolean isNewPending = mPendingStartActivityUids.add(uid, pid); 17720 // If the next top activity is in cached and frozen mode, WM should raise its priority 17721 // to unfreeze it. This is done by calling AMS.updateOomAdj that will lower its oom adj. 17722 // However, WM cannot hold the AMS clock here so the updateOomAdj operation is performed 17723 // in a separate thread asynchronously. Therefore WM can't guarantee AMS will unfreeze 17724 // next top activity on time. This race will fail the following binder transactions WM 17725 // sends to the activity. After this race issue between WM/ATMS and AMS is solved, this 17726 // workaround can be removed. (b/213288355) 17727 if (isNewPending) { 17728 mOomAdjuster.mCachedAppOptimizer.unfreezeProcess(pid, OOM_ADJ_REASON_ACTIVITY); 17729 } 17730 // We need to update the network rules for the app coming to the top state so that 17731 // it can access network when the device or the app is in a restricted state 17732 // (e.g. battery/data saver) but since waiting for updateOomAdj to complete and then 17733 // informing NetworkPolicyManager might get delayed, informing the state change as soon 17734 // as we know app is going to come to the top state. 17735 if (isNewPending && mNetworkPolicyUidObserver != null) { 17736 try { 17737 final long procStateSeq = mProcessList.getNextProcStateSeq(); 17738 mNetworkPolicyUidObserver.onUidStateChanged(uid, PROCESS_STATE_TOP, 17739 procStateSeq, PROCESS_CAPABILITY_ALL); 17740 if (thread != null && shouldWaitForNetworkRulesUpdate(uid)) { 17741 thread.setNetworkBlockSeq(procStateSeq); 17742 } 17743 } catch (RemoteException e) { 17744 Slog.d(TAG, "Error calling setNetworkBlockSeq", e); 17745 } 17746 } 17747 } 17748 shouldWaitForNetworkRulesUpdate(int uid)17749 private boolean shouldWaitForNetworkRulesUpdate(int uid) { 17750 synchronized (mUidNetworkBlockedReasons) { 17751 // TODO: We can reuse this data in 17752 // ProcessList#incrementProcStateSeqAndNotifyAppsLOSP instead of calling into 17753 // NetworkManagementService. 17754 final int uidBlockedReasons = mUidNetworkBlockedReasons.get( 17755 uid, BLOCKED_REASON_NONE); 17756 // We should only inform the uid to block if it is currently blocked but will be 17757 // unblocked once it comes to the TOP state. 17758 return uidBlockedReasons != BLOCKED_REASON_NONE 17759 && updateBlockedReasonsWithProcState(uidBlockedReasons, PROCESS_STATE_TOP) 17760 == BLOCKED_REASON_NONE; 17761 } 17762 } 17763 17764 @Override deletePendingTopUid(int uid, long nowElapsed)17765 public void deletePendingTopUid(int uid, long nowElapsed) { 17766 mPendingStartActivityUids.delete(uid, nowElapsed); 17767 } 17768 17769 @Override isPendingTopUid(int uid)17770 public boolean isPendingTopUid(int uid) { 17771 return mPendingStartActivityUids.isPendingTopUid(uid); 17772 } 17773 17774 @Override getIntentForIntentSender(IIntentSender sender)17775 public Intent getIntentForIntentSender(IIntentSender sender) { 17776 return ActivityManagerService.this.getIntentForIntentSender(sender); 17777 } 17778 17779 @Override getPendingIntentActivityAsApp( int requestCode, @NonNull Intent intent, int flags, Bundle options, String ownerPkg, int ownerUid)17780 public PendingIntent getPendingIntentActivityAsApp( 17781 int requestCode, @NonNull Intent intent, int flags, Bundle options, 17782 String ownerPkg, int ownerUid) { 17783 return getPendingIntentActivityAsApp(requestCode, new Intent[] { intent }, flags, 17784 options, ownerPkg, ownerUid); 17785 } 17786 17787 @Override getPendingIntentActivityAsApp( int requestCode, @NonNull Intent[] intents, int flags, Bundle options, String ownerPkg, int ownerUid)17788 public PendingIntent getPendingIntentActivityAsApp( 17789 int requestCode, @NonNull Intent[] intents, int flags, Bundle options, 17790 String ownerPkg, int ownerUid) { 17791 // system callers must explicitly set mutability state 17792 final boolean flagImmutableSet = (flags & PendingIntent.FLAG_IMMUTABLE) != 0; 17793 final boolean flagMutableSet = (flags & PendingIntent.FLAG_MUTABLE) != 0; 17794 if (flagImmutableSet == flagMutableSet) { 17795 throw new IllegalArgumentException( 17796 "Must set exactly one of FLAG_IMMUTABLE or FLAG_MUTABLE"); 17797 } 17798 17799 final Context context = ActivityManagerService.this.mContext; 17800 final ContentResolver resolver = context.getContentResolver(); 17801 final int len = intents.length; 17802 final String[] resolvedTypes = new String[len]; 17803 for (int i = 0; i < len; i++) { 17804 final Intent intent = intents[i]; 17805 resolvedTypes[i] = intent.resolveTypeIfNeeded(resolver); 17806 intent.migrateExtraStreamToClipData(context); 17807 intent.prepareToLeaveProcess(context); 17808 } 17809 IIntentSender target = 17810 ActivityManagerService.this.getIntentSenderWithFeatureAsApp( 17811 INTENT_SENDER_ACTIVITY, ownerPkg, 17812 context.getAttributionTag(), null, null, requestCode, 17813 intents, 17814 resolvedTypes, 17815 flags, options, UserHandle.getUserId(ownerUid), ownerUid); 17816 return target != null ? new PendingIntent(target) : null; 17817 } 17818 17819 @Override getBootTimeTempAllowListDuration()17820 public long getBootTimeTempAllowListDuration() { 17821 // Do not lock ActivityManagerService.this here, this API is called by 17822 // PackageManagerService. 17823 return mConstants.mBootTimeTempAllowlistDuration; 17824 } 17825 17826 @Override registerAnrController(AnrController controller)17827 public void registerAnrController(AnrController controller) { 17828 mActivityTaskManager.registerAnrController(controller); 17829 } 17830 17831 @Override unregisterAnrController(AnrController controller)17832 public void unregisterAnrController(AnrController controller) { 17833 mActivityTaskManager.unregisterAnrController(controller); 17834 } 17835 17836 @Override canStartForegroundService(int pid, int uid, @NonNull String packageName)17837 public boolean canStartForegroundService(int pid, int uid, @NonNull String packageName) { 17838 synchronized (ActivityManagerService.this) { 17839 return mServices.canStartForegroundServiceLocked(pid, uid, packageName); 17840 } 17841 } 17842 17843 @Override tempAllowWhileInUsePermissionInFgs(int uid, long durationMs)17844 public void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs) { 17845 mFgsWhileInUseTempAllowList.add(uid, durationMs, ""); 17846 } 17847 17848 @Override isTempAllowlistedForFgsWhileInUse(int uid)17849 public boolean isTempAllowlistedForFgsWhileInUse(int uid) { 17850 return mFgsWhileInUseTempAllowList.isAllowed(uid); 17851 } 17852 17853 @Override canAllowWhileInUsePermissionInFgs(int pid, int uid, @NonNull String packageName)17854 public boolean canAllowWhileInUsePermissionInFgs(int pid, int uid, 17855 @NonNull String packageName) { 17856 synchronized (ActivityManagerService.this) { 17857 return mServices.canAllowWhileInUsePermissionInFgsLocked(pid, uid, packageName); 17858 } 17859 } 17860 17861 @Override getPushMessagingOverQuotaBehavior()17862 public @TempAllowListType int getPushMessagingOverQuotaBehavior() { 17863 synchronized (ActivityManagerService.this) { 17864 return mConstants.mPushMessagingOverQuotaBehavior; 17865 } 17866 } 17867 17868 @Override getServiceStartForegroundTimeout()17869 public int getServiceStartForegroundTimeout() { 17870 return mConstants.mServiceStartForegroundTimeoutMs; 17871 } 17872 17873 @Override getUidCapability(int uid)17874 public int getUidCapability(int uid) { 17875 synchronized (ActivityManagerService.this) { 17876 UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 17877 if (uidRecord == null) { 17878 throw new IllegalArgumentException("uid record for " + uid + " not found"); 17879 } 17880 return uidRecord.getCurCapability(); 17881 } 17882 } 17883 17884 /** 17885 * @return The PID list of the isolated process with packages matching the given uid. 17886 */ 17887 @Nullable getIsolatedProcesses(int uid)17888 public List<Integer> getIsolatedProcesses(int uid) { 17889 synchronized (ActivityManagerService.this) { 17890 return mProcessList.getIsolatedProcessesLocked(uid); 17891 } 17892 } 17893 17894 /** @see ActivityManagerService#sendIntentSender */ 17895 @Override sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)17896 public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, 17897 Intent intent, String resolvedType, 17898 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 17899 return ActivityManagerService.this.sendIntentSender(null, target, allowlistToken, code, 17900 intent, resolvedType, finishedReceiver, requiredPermission, options); 17901 } 17902 17903 @Override setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)17904 public void setVoiceInteractionManagerProvider( 17905 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) { 17906 ActivityManagerService.this.setVoiceInteractionManagerProvider(provider); 17907 } 17908 17909 @Override isEarlyPackageKillEnabledForUserSwitch(int fromUserId, int toUserId)17910 public boolean isEarlyPackageKillEnabledForUserSwitch(int fromUserId, int toUserId) { 17911 return mUserController.isEarlyPackageKillEnabledForUserSwitch(fromUserId, toUserId); 17912 } 17913 17914 @Override setStopUserOnSwitch(int value)17915 public void setStopUserOnSwitch(int value) { 17916 ActivityManagerService.this.setStopUserOnSwitch(value); 17917 } 17918 17919 @Override getRestrictionLevel(int uid)17920 public @RestrictionLevel int getRestrictionLevel(int uid) { 17921 return mAppRestrictionController.getRestrictionLevel(uid); 17922 } 17923 17924 @Override getRestrictionLevel(String pkg, @UserIdInt int userId)17925 public @RestrictionLevel int getRestrictionLevel(String pkg, @UserIdInt int userId) { 17926 return mAppRestrictionController.getRestrictionLevel(pkg, userId); 17927 } 17928 17929 @Override isBgAutoRestrictedBucketFeatureFlagEnabled()17930 public boolean isBgAutoRestrictedBucketFeatureFlagEnabled() { 17931 return mAppRestrictionController.isBgAutoRestrictedBucketFeatureFlagEnabled(); 17932 } 17933 17934 @Override addAppBackgroundRestrictionListener( @onNull ActivityManagerInternal.AppBackgroundRestrictionListener listener)17935 public void addAppBackgroundRestrictionListener( 17936 @NonNull ActivityManagerInternal.AppBackgroundRestrictionListener listener) { 17937 mAppRestrictionController.addAppBackgroundRestrictionListener(listener); 17938 } 17939 17940 @Override addForegroundServiceStateListener( @onNull ForegroundServiceStateListener listener)17941 public void addForegroundServiceStateListener( 17942 @NonNull ForegroundServiceStateListener listener) { 17943 synchronized (ActivityManagerService.this) { 17944 mForegroundServiceStateListeners.add(listener); 17945 } 17946 } 17947 17948 @Override addBroadcastEventListener(@onNull BroadcastEventListener listener)17949 public void addBroadcastEventListener(@NonNull BroadcastEventListener listener) { 17950 // It's a CopyOnWriteArrayList, so no lock is needed. 17951 mBroadcastEventListeners.add(listener); 17952 } 17953 17954 @Override addBindServiceEventListener(@onNull BindServiceEventListener listener)17955 public void addBindServiceEventListener(@NonNull BindServiceEventListener listener) { 17956 // It's a CopyOnWriteArrayList, so no lock is needed. 17957 mBindServiceEventListeners.add(listener); 17958 } 17959 17960 @Override restart()17961 public void restart() { 17962 ActivityManagerService.this.restart(); 17963 } 17964 17965 @Override registerNetworkPolicyUidObserver(@onNull IUidObserver observer, int which, int cutpoint, @NonNull String callingPackage)17966 public void registerNetworkPolicyUidObserver(@NonNull IUidObserver observer, 17967 int which, int cutpoint, @NonNull String callingPackage) { 17968 mNetworkPolicyUidObserver = observer; 17969 mUidObserverController.register(observer, which, cutpoint, callingPackage, 17970 Binder.getCallingUid(), /*uids*/null); 17971 } 17972 17973 @Override startForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options, @Nullable ServiceConnection connection)17974 public boolean startForegroundServiceDelegate( 17975 @NonNull ForegroundServiceDelegationOptions options, 17976 @Nullable ServiceConnection connection) { 17977 synchronized (ActivityManagerService.this) { 17978 return mServices.startForegroundServiceDelegateLocked(options, connection); 17979 } 17980 } 17981 17982 @Override stopForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options)17983 public void stopForegroundServiceDelegate( 17984 @NonNull ForegroundServiceDelegationOptions options) { 17985 synchronized (ActivityManagerService.this) { 17986 mServices.stopForegroundServiceDelegateLocked(options); 17987 } 17988 } 17989 17990 @Override stopForegroundServiceDelegate(@onNull ServiceConnection connection)17991 public void stopForegroundServiceDelegate(@NonNull ServiceConnection connection) { 17992 synchronized (ActivityManagerService.this) { 17993 mServices.stopForegroundServiceDelegateLocked(connection); 17994 } 17995 } 17996 17997 @Override notifyActiveMediaForegroundService(@onNull String packageName, @UserIdInt int userId, int notificationId)17998 public void notifyActiveMediaForegroundService(@NonNull String packageName, 17999 @UserIdInt int userId, int notificationId) { 18000 synchronized (ActivityManagerService.this) { 18001 mServices.notifyActiveMediaForegroundServiceLocked(packageName, userId, 18002 notificationId); 18003 } 18004 } 18005 18006 @Override notifyInactiveMediaForegroundService(@onNull String packageName, @UserIdInt int userId, int notificationId)18007 public void notifyInactiveMediaForegroundService(@NonNull String packageName, 18008 @UserIdInt int userId, int notificationId) { 18009 synchronized (ActivityManagerService.this) { 18010 mServices.notifyInactiveMediaForegroundServiceLocked(packageName, userId, 18011 notificationId); 18012 } 18013 } 18014 18015 @Override getClientPackages(String servicePackageName)18016 public ArraySet<String> getClientPackages(String servicePackageName) { 18017 synchronized (ActivityManagerService.this) { 18018 return mServices.getClientPackagesLocked(servicePackageName); 18019 } 18020 } 18021 18022 @Override triggerUnsafeIntentStrictMode(int callingPid, int type, Intent intent)18023 public void triggerUnsafeIntentStrictMode(int callingPid, int type, Intent intent) { 18024 final IUnsafeIntentStrictModeCallback callback; 18025 final Intent i = intent.cloneFilter(); 18026 synchronized (mStrictModeCallbacks) { 18027 callback = mStrictModeCallbacks.get(callingPid); 18028 } 18029 if (callback != null) { 18030 BackgroundThread.getExecutor().execute(() -> { 18031 try { 18032 callback.onUnsafeIntent(type, i); 18033 } catch (RemoteException e) { 18034 synchronized (mStrictModeCallbacks) { 18035 mStrictModeCallbacks.remove(callingPid); 18036 } 18037 } 18038 }); 18039 } 18040 } 18041 18042 @Override startProfileEvenWhenDisabled(@serIdInt int userId)18043 public boolean startProfileEvenWhenDisabled(@UserIdInt int userId) { 18044 return mUserController.startProfile(userId, /* evenWhenDisabled= */ true, 18045 /* unlockListener= */ null); 18046 } 18047 18048 @Override logFgsApiBegin(@oregroundServiceApiType int apiType, int uid, int pid)18049 public void logFgsApiBegin(@ForegroundServiceApiType int apiType, 18050 int uid, int pid) { 18051 synchronized (this) { 18052 mServices.logFgsApiBeginLocked(apiType, uid, pid); 18053 } 18054 } 18055 18056 @Override logFgsApiEnd(@oregroundServiceApiType int apiType, int uid, int pid)18057 public void logFgsApiEnd(@ForegroundServiceApiType int apiType, 18058 int uid, int pid) { 18059 synchronized (this) { 18060 mServices.logFgsApiEndLocked(apiType, uid, pid); 18061 } 18062 } 18063 18064 @Override notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, @MediaProjectionTokenEvent int event)18065 public void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, 18066 @MediaProjectionTokenEvent int event) { 18067 ActivityManagerService.this.notifyMediaProjectionEvent(uid, projectionToken, event); 18068 } 18069 18070 @Override 18071 @NonNull getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull)18072 public StatsEvent getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull) { 18073 return mAppProfiler.mCachedAppsWatermarkData.getCachedAppsHighWatermarkStats( 18074 atomTag, resetAfterPull); 18075 } 18076 18077 @Override clearApplicationUserData(final String packageName, boolean keepState, boolean isRestore, final IPackageDataObserver observer, int userId)18078 public boolean clearApplicationUserData(final String packageName, boolean keepState, 18079 boolean isRestore, final IPackageDataObserver observer, int userId) { 18080 return ActivityManagerService.this.clearApplicationUserData(packageName, keepState, 18081 isRestore, observer, userId); 18082 } 18083 18084 @Override shouldDelayHomeLaunch(int userId)18085 public boolean shouldDelayHomeLaunch(int userId) { 18086 if (!isHomeLaunchDelayable()) return false; 18087 18088 synchronized (mThemeOverlayReadyUsers) { 18089 return !ActivityManagerService.this.mThemeOverlayReadyUsers.contains(userId); 18090 } 18091 } 18092 18093 @Override addStartInfoTimestamp(int key, long timestampNs, int uid, int pid, int userId)18094 public void addStartInfoTimestamp(int key, long timestampNs, int uid, int pid, 18095 int userId) { 18096 addStartInfoTimestampInternal(key, timestampNs, userId, uid); 18097 } 18098 18099 @Override killApplicationSync(String pkgName, int appId, @CanBeALL @UserIdInt int userId, String reason, int exitInfoReason)18100 public void killApplicationSync(String pkgName, int appId, @CanBeALL @UserIdInt int userId, 18101 String reason, int exitInfoReason) { 18102 if (pkgName == null) { 18103 return; 18104 } 18105 // Make sure the uid is valid. 18106 if (appId < 0) { 18107 Slog.w(TAG, "Invalid appid specified for pkg : " + pkgName); 18108 return; 18109 } 18110 synchronized (ActivityManagerService.this) { 18111 ActivityManagerService.this.forceStopPackageLocked(pkgName, appId, 18112 /* callerWillRestart= */ false, /*purgeCache= */ false, 18113 /* doit= */ true, /* evenPersistent= */ false, 18114 /* uninstalling= */ false, /* packageStateStopped= */ false, 18115 userId, reason, exitInfoReason); 18116 } 18117 } 18118 18119 @Override getExecutableMethodFileOffsets(@onNull String processName, int pid, int uid, @NonNull MethodDescriptor methodDescriptor, @NonNull IOffsetCallback callback)18120 public void getExecutableMethodFileOffsets(@NonNull String processName, 18121 int pid, int uid, @NonNull MethodDescriptor methodDescriptor, 18122 @NonNull IOffsetCallback callback) { 18123 final IApplicationThread thread; 18124 synchronized (ActivityManagerService.this) { 18125 ProcessRecord record = mProcessList.getProcessRecordLocked(processName, uid); 18126 if (record == null || record.getPid() != pid) { 18127 throw new NoSuchElementException(); 18128 } 18129 thread = record.getThread(); 18130 } 18131 try { 18132 thread.getExecutableMethodFileOffsets(methodDescriptor, callback); 18133 } catch (RemoteException e) { 18134 throw new RuntimeException( 18135 "IApplicationThread.getExecutableMethodFileOffsets failed", e); 18136 } 18137 } 18138 18139 @Override addCreatorToken(Intent intent, String creatorPackage)18140 public void addCreatorToken(Intent intent, String creatorPackage) { 18141 ActivityManagerService.this.addCreatorToken(intent, creatorPackage); 18142 } 18143 } 18144 18145 long inputDispatchingTimedOut(int pid, final boolean aboveSystem, TimeoutRecord timeoutRecord) { 18146 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 18147 throw new SecurityException("Requires permission " + FILTER_EVENTS); 18148 } 18149 ProcessRecord proc; 18150 timeoutRecord.mLatencyTracker.waitingOnPidLockStarted(); 18151 synchronized (mPidsSelfLocked) { 18152 timeoutRecord.mLatencyTracker.waitingOnPidLockEnded(); 18153 proc = mPidsSelfLocked.get(pid); 18154 } 18155 final long timeoutMillis = proc != null ? proc.getInputDispatchingTimeoutMillis() : 18156 DEFAULT_DISPATCHING_TIMEOUT_MILLIS; 18157 18158 if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, timeoutRecord)) { 18159 return 0; 18160 } 18161 18162 return timeoutMillis; 18163 } 18164 18165 /** 18166 * Handle input dispatching timeouts. 18167 * @return whether input dispatching should be aborted or not. 18168 */ 18169 boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, 18170 ApplicationInfo aInfo, String parentShortComponentName, 18171 WindowProcessController parentProcess, boolean aboveSystem, 18172 TimeoutRecord timeoutRecord) { 18173 try { 18174 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "inputDispatchingTimedOut()"); 18175 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 18176 throw new SecurityException("Requires permission " + FILTER_EVENTS); 18177 } 18178 18179 if (proc != null) { 18180 timeoutRecord.mLatencyTracker.waitingOnAMSLockStarted(); 18181 synchronized (this) { 18182 timeoutRecord.mLatencyTracker.waitingOnAMSLockEnded(); 18183 if (proc.isDebugging()) { 18184 return false; 18185 } 18186 18187 if (proc.getActiveInstrumentation() != null) { 18188 Bundle info = new Bundle(); 18189 info.putString("shortMsg", "keyDispatchingTimedOut"); 18190 info.putString("longMsg", timeoutRecord.mReason); 18191 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 18192 return true; 18193 } 18194 } 18195 mAnrHelper.appNotResponding(proc, activityShortComponentName, aInfo, 18196 parentShortComponentName, parentProcess, aboveSystem, timeoutRecord, 18197 /*isContinuousAnr*/ true); 18198 } 18199 18200 return true; 18201 } finally { 18202 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 18203 } 18204 } 18205 18206 /** 18207 * Called by app main thread to wait for the network policy rules to get updated. 18208 * 18209 * @param procStateSeq The sequence number indicating the process state change that the main 18210 * thread is interested in. 18211 */ 18212 @Override 18213 public void waitForNetworkStateUpdate(long procStateSeq) { 18214 final int callingUid = Binder.getCallingUid(); 18215 if (DEBUG_NETWORK) { 18216 Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq); 18217 } 18218 UidRecord record; 18219 synchronized (mProcLock) { 18220 record = mProcessList.getUidRecordLOSP(callingUid); 18221 if (record == null) { 18222 return; 18223 } 18224 } 18225 synchronized (record.networkStateLock) { 18226 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 18227 if (DEBUG_NETWORK) { 18228 Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. " 18229 + procStateSeq + ", so no need to wait. Uid: " 18230 + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: " 18231 + record.lastNetworkUpdatedProcStateSeq); 18232 } 18233 return; 18234 } 18235 try { 18236 if (DEBUG_NETWORK) { 18237 Slog.d(TAG_NETWORK, "Starting to wait for the network rules update." 18238 + " Uid: " + callingUid + " procStateSeq: " + procStateSeq); 18239 } 18240 final long startTime = SystemClock.uptimeMillis(); 18241 record.procStateSeqWaitingForNetwork = procStateSeq; 18242 record.networkStateLock.wait(mConstants.mNetworkAccessTimeoutMs); 18243 record.procStateSeqWaitingForNetwork = 0; 18244 final long totalTime = SystemClock.uptimeMillis() - startTime; 18245 if (totalTime >= mConstants.mNetworkAccessTimeoutMs || DEBUG_NETWORK) { 18246 Slog.wtf(TAG_NETWORK, "Total time waited for network rules to get updated: " 18247 + totalTime + ". Uid: " + callingUid + " procStateSeq: " 18248 + procStateSeq + " UidRec: " + record 18249 + " validateUidRec: " 18250 + mUidObserverController.getValidateUidRecord(callingUid)); 18251 } 18252 } catch (InterruptedException e) { 18253 Thread.currentThread().interrupt(); 18254 } 18255 } 18256 } 18257 18258 @Override 18259 public void waitForBroadcastIdle() { 18260 waitForBroadcastIdle(LOG_WRITER_INFO, false); 18261 } 18262 18263 void waitForBroadcastIdle(@NonNull PrintWriter pw, boolean flushBroadcastLoopers) { 18264 enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()"); 18265 if (flushBroadcastLoopers) { 18266 BroadcastLoopers.waitForIdle(pw); 18267 } 18268 mBroadcastQueue.waitForIdle(pw); 18269 pw.println("All broadcast queues are idle!"); 18270 pw.flush(); 18271 } 18272 18273 @Override 18274 public void waitForBroadcastBarrier() { 18275 waitForBroadcastBarrier(LOG_WRITER_INFO, false, false); 18276 } 18277 18278 void waitForBroadcastBarrier(@NonNull PrintWriter pw, 18279 boolean flushBroadcastLoopers, boolean flushApplicationThreads) { 18280 enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()"); 18281 if (flushBroadcastLoopers) { 18282 BroadcastLoopers.waitForBarrier(pw); 18283 } 18284 mBroadcastQueue.waitForBarrier(pw); 18285 if (flushApplicationThreads) { 18286 waitForApplicationBarrier(pw); 18287 } 18288 } 18289 18290 /** 18291 * Wait for all pending {@link IApplicationThread} events to be processed in 18292 * all currently running apps. 18293 */ 18294 void waitForApplicationBarrier(@NonNull PrintWriter pw) { 18295 final CountDownLatch finishedLatch = new CountDownLatch(1); 18296 final AtomicInteger pingCount = new AtomicInteger(0); 18297 final AtomicInteger pongCount = new AtomicInteger(0); 18298 final RemoteCallback pongCallback = new RemoteCallback((result) -> { 18299 if (pongCount.incrementAndGet() == pingCount.get()) { 18300 finishedLatch.countDown(); 18301 } 18302 }); 18303 18304 // Insert an extra "ping" as a sentinel value to guard us from finishing 18305 // too quickly in parallel below 18306 pingCount.incrementAndGet(); 18307 18308 synchronized (ActivityManagerService.this) { 18309 synchronized (mProcLock) { 18310 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 18311 mProcessList.getProcessNamesLOSP().getMap(); 18312 final int numProc = pmap.size(); 18313 for (int iProc = 0; iProc < numProc; iProc++) { 18314 final SparseArray<ProcessRecord> apps = pmap.valueAt(iProc); 18315 for (int iApp = 0, numApps = apps.size(); iApp < numApps; iApp++) { 18316 final ProcessRecord app = apps.valueAt(iApp); 18317 final IApplicationThread thread = app.getOnewayThread(); 18318 if (thread != null) { 18319 mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(app, 18320 CachedAppOptimizer.UNFREEZE_REASON_PING); 18321 pingCount.incrementAndGet(); 18322 try { 18323 thread.schedulePing(pongCallback); 18324 } catch (RemoteException ignored) { 18325 // When we failed to ping remote process, pretend as 18326 // if we received the expected pong 18327 pongCallback.sendResult(null); 18328 } 18329 } 18330 } 18331 } 18332 } 18333 } 18334 18335 // Now that we've dispatched all "ping" events above, we can send our 18336 // "pong" sentinel value 18337 pongCallback.sendResult(null); 18338 18339 // Wait for any remaining "pong" events to trickle in 18340 for (int i = 0; i < 30; i++) { 18341 try { 18342 if (finishedLatch.await(1, TimeUnit.SECONDS)) { 18343 pw.println("Finished application barriers!"); 18344 pw.flush(); 18345 return; 18346 } else { 18347 pw.println("Waiting for application barriers, at " + pongCount.get() + " of " 18348 + pingCount.get() + "..."); 18349 pw.flush(); 18350 } 18351 } catch (InterruptedException ignored) { 18352 } 18353 } 18354 pw.println("Gave up waiting for application barriers!"); 18355 pw.flush(); 18356 } 18357 18358 void waitForBroadcastDispatch(@NonNull PrintWriter pw, @NonNull Intent intent) { 18359 enforceCallingPermission(permission.DUMP, "waitForBroadcastDispatch"); 18360 mBroadcastQueue.waitForDispatched(intent, pw); 18361 } 18362 18363 void setIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) { 18364 Objects.requireNonNull(broadcastAction); 18365 enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()"); 18366 synchronized (mDeliveryGroupPolicyIgnoredActions) { 18367 mDeliveryGroupPolicyIgnoredActions.add(broadcastAction); 18368 } 18369 } 18370 18371 void clearIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) { 18372 Objects.requireNonNull(broadcastAction); 18373 enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()"); 18374 synchronized (mDeliveryGroupPolicyIgnoredActions) { 18375 mDeliveryGroupPolicyIgnoredActions.remove(broadcastAction); 18376 } 18377 } 18378 18379 boolean shouldIgnoreDeliveryGroupPolicy(@Nullable String broadcastAction) { 18380 if (broadcastAction == null) { 18381 return false; 18382 } 18383 synchronized (mDeliveryGroupPolicyIgnoredActions) { 18384 return mDeliveryGroupPolicyIgnoredActions.contains(broadcastAction); 18385 } 18386 } 18387 18388 void dumpDeliveryGroupPolicyIgnoredActions(IndentingPrintWriter ipw) { 18389 synchronized (mDeliveryGroupPolicyIgnoredActions) { 18390 ipw.println(mDeliveryGroupPolicyIgnoredActions); 18391 } 18392 } 18393 18394 @Override 18395 public void forceDelayBroadcastDelivery(@NonNull String targetPackage, 18396 long delayedDurationMs) { 18397 Objects.requireNonNull(targetPackage); 18398 Preconditions.checkArgumentNonnegative(delayedDurationMs); 18399 enforceCallingPermission(permission.DUMP, "forceDelayBroadcastDelivery()"); 18400 18401 mBroadcastQueue.forceDelayBroadcastDelivery(targetPackage, delayedDurationMs); 18402 } 18403 18404 @Override 18405 public boolean isProcessFrozen(int pid) { 18406 enforceCallingPermission(permission.DUMP, "isProcessFrozen()"); 18407 return mOomAdjuster.mCachedAppOptimizer.isProcessFrozen(pid); 18408 } 18409 18410 @Override 18411 @ReasonCode 18412 public int getBackgroundRestrictionExemptionReason(int uid) { 18413 enforceCallingPermission(android.Manifest.permission.DEVICE_POWER, 18414 "getBackgroundRestrictionExemptionReason()"); 18415 return mAppRestrictionController.getBackgroundRestrictionExemptionReason(uid); 18416 } 18417 18418 /** 18419 * Set an app's background restriction level. 18420 * This interface is intended for the shell command to use. 18421 */ 18422 void setBackgroundRestrictionLevel(String packageName, int uid, int userId, 18423 @RestrictionLevel int level, int reason, int subReason) { 18424 final int callingUid = Binder.getCallingUid(); 18425 if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) { 18426 throw new SecurityException( 18427 "No permission to change app restriction level"); 18428 } 18429 final long callingId = Binder.clearCallingIdentity(); 18430 try { 18431 final int curBucket = mUsageStatsService.getAppStandbyBucket(packageName, userId, 18432 SystemClock.elapsedRealtime()); 18433 mAppRestrictionController.applyRestrictionLevel(packageName, uid, level, 18434 null /* trackerInfo */, curBucket, true /* allowUpdateBucket */, 18435 reason, subReason); 18436 } finally { 18437 Binder.restoreCallingIdentity(callingId); 18438 } 18439 } 18440 18441 /** 18442 * Log the reason for changing an app restriction. Purely used for logging purposes and does not 18443 * cause any change to app state. 18444 * 18445 * @see ActivityManager#noteAppRestrictionEnabled(String, int, int, boolean, int, 18446 * String, int, long) 18447 */ 18448 @Override 18449 public void noteAppRestrictionEnabled(String packageName, int uid, 18450 @RestrictionLevel int restrictionType, boolean enabled, 18451 @ActivityManager.RestrictionReason int reason, String subReason, 18452 @ActivityManager.RestrictionSource int source, long threshold) { 18453 if (!android.app.Flags.appRestrictionsApi()) return; 18454 18455 enforceCallingPermission(android.Manifest.permission.DEVICE_POWER, 18456 "noteAppRestrictionEnabled()"); 18457 18458 final int userId = UserHandle.getCallingUserId(); 18459 final long callingId = Binder.clearCallingIdentity(); 18460 try { 18461 if (uid == INVALID_UID) { 18462 uid = mPackageManagerInt.getPackageUid(packageName, 0, userId); 18463 } 18464 mAppRestrictionController.noteAppRestrictionEnabled(packageName, uid, restrictionType, 18465 enabled, reason, subReason, source, threshold); 18466 } finally { 18467 Binder.restoreCallingIdentity(callingId); 18468 } 18469 } 18470 18471 /** 18472 * Get an app's background restriction level. 18473 * This interface is intended for the shell command to use. 18474 */ 18475 @RestrictionLevel int getBackgroundRestrictionLevel(String packageName, int userId) { 18476 final int callingUid = Binder.getCallingUid(); 18477 if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) { 18478 throw new SecurityException( 18479 "Don't have permission to query app background restriction level"); 18480 } 18481 final long callingId = Binder.clearCallingIdentity(); 18482 try { 18483 return mInternal.getRestrictionLevel(packageName, userId); 18484 } finally { 18485 Binder.restoreCallingIdentity(callingId); 18486 } 18487 } 18488 18489 /** 18490 * Start/stop foreground service delegate on a app's process. 18491 * This interface is intended for the shell command to use. 18492 */ 18493 void setForegroundServiceDelegate(String packageName, int uid, boolean isStart, 18494 @ForegroundServiceDelegationOptions.DelegationService int delegateService, 18495 String clientInstanceName) { 18496 final int callingUid = Binder.getCallingUid(); 18497 if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) { 18498 throw new SecurityException( 18499 "No permission to start/stop foreground service delegate"); 18500 } 18501 final long callingId = Binder.clearCallingIdentity(); 18502 try { 18503 boolean foundPid = false; 18504 synchronized (this) { 18505 ArrayList<ForegroundServiceDelegationOptions> delegates = new ArrayList<>(); 18506 synchronized (mPidsSelfLocked) { 18507 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 18508 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 18509 final IApplicationThread thread = p.getThread(); 18510 if (p.uid == uid && thread != null) { 18511 foundPid = true; 18512 int pid = mPidsSelfLocked.keyAt(i); 18513 ForegroundServiceDelegationOptions options = 18514 new ForegroundServiceDelegationOptions(pid, uid, packageName, 18515 null /* clientAppThread */, 18516 false /* isSticky */, 18517 clientInstanceName, 0 /* foregroundServiceType */, 18518 delegateService); 18519 delegates.add(options); 18520 } 18521 } 18522 } 18523 for (int i = delegates.size() - 1; i >= 0; i--) { 18524 final ForegroundServiceDelegationOptions options = delegates.get(i); 18525 if (isStart) { 18526 mInternal.startForegroundServiceDelegate(options, 18527 null /* connection */); 18528 } else { 18529 mInternal.stopForegroundServiceDelegate(options); 18530 } 18531 } 18532 } 18533 if (!foundPid) { 18534 Slog.e(TAG, "setForegroundServiceDelegate can not find process for packageName:" 18535 + packageName + " uid:" + uid); 18536 } 18537 } finally { 18538 Binder.restoreCallingIdentity(callingId); 18539 } 18540 } 18541 18542 /** 18543 * Force the settings cache to be loaded 18544 */ 18545 void refreshSettingsCache() { 18546 mCoreSettingsObserver.onChange(true); 18547 } 18548 18549 /** 18550 * Reset the dropbox rate limiter here and in BootReceiver 18551 */ 18552 void resetDropboxRateLimiter() { 18553 mDropboxRateLimiter.reset(); 18554 BootReceiver.resetDropboxRateLimiter(); 18555 } 18556 18557 /** 18558 * Kill processes for the user with id userId and that depend on the package named packageName 18559 */ 18560 @Override 18561 public void killPackageDependents(String packageName, int userId) { 18562 enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()"); 18563 if (packageName == null) { 18564 throw new NullPointerException( 18565 "Cannot kill the dependents of a package without its name."); 18566 } 18567 18568 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 18569 userId, true, ALLOW_FULL_ONLY, "killPackageDependents", null); 18570 final int[] userIds = mUserController.expandUserId(userId); 18571 18572 final long callingId = Binder.clearCallingIdentity(); 18573 IPackageManager pm = AppGlobals.getPackageManager(); 18574 try { 18575 for (int targetUserId : userIds) { 18576 int pkgUid = -1; 18577 try { 18578 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 18579 targetUserId); 18580 } catch (RemoteException e) { 18581 } 18582 if (userId != UserHandle.USER_ALL && pkgUid == -1) { 18583 throw new IllegalArgumentException( 18584 "Cannot kill dependents of non-existing package " + packageName); 18585 } 18586 synchronized (this) { 18587 synchronized (mProcLock) { 18588 mProcessList.killPackageProcessesLSP(packageName, 18589 UserHandle.getAppId(pkgUid), 18590 targetUserId, 18591 ProcessList.FOREGROUND_APP_ADJ, 18592 ApplicationExitInfo.REASON_DEPENDENCY_DIED, 18593 ApplicationExitInfo.SUBREASON_UNKNOWN, 18594 "dep: " + packageName); 18595 } 18596 } 18597 } 18598 } finally { 18599 Binder.restoreCallingIdentity(callingId); 18600 } 18601 } 18602 18603 @Override 18604 public int restartUserInBackground(int userId, int userStartMode) { 18605 return mUserController.restartUser(userId, userStartMode); 18606 } 18607 18608 @Override 18609 public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) { 18610 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 18611 "scheduleApplicationInfoChanged()"); 18612 18613 final long origId = Binder.clearCallingIdentity(); 18614 try { 18615 final boolean updateFrameworkRes = packageNames.contains("android"); 18616 synchronized (mProcLock) { 18617 updateApplicationInfoLOSP(packageNames, updateFrameworkRes, userId); 18618 } 18619 18620 AppWidgetManagerInternal widgets = LocalServices.getService( 18621 AppWidgetManagerInternal.class); 18622 if (widgets != null) { 18623 widgets.applyResourceOverlaysToWidgets(new HashSet<>(packageNames), userId, 18624 updateFrameworkRes); 18625 } 18626 } finally { 18627 Binder.restoreCallingIdentity(origId); 18628 } 18629 } 18630 18631 /** 18632 * Synchronously update the system ActivityThread, bypassing any deferred threading so any 18633 * resources and overlaid values are available immediately. 18634 */ 18635 public void updateSystemUiContext() { 18636 final PackageManagerInternal packageManagerInternal = getPackageManagerInternal(); 18637 18638 ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android", 18639 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM); 18640 ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai); 18641 } 18642 18643 @GuardedBy(anyOf = {"this", "mProcLock"}) 18644 private void updateApplicationInfoLOSP(@NonNull List<String> packagesToUpdate, 18645 boolean updateFrameworkRes, int userId) { 18646 if (updateFrameworkRes) { 18647 ParsingPackageUtils.readConfigUseRoundIcon(null); 18648 } 18649 18650 mProcessList.updateApplicationInfoLOSP(packagesToUpdate, userId, updateFrameworkRes); 18651 18652 if (updateFrameworkRes) { 18653 // Update system server components that need to know about changed overlays. Because the 18654 // overlay is applied in ActivityThread, we need to serialize through its thread too. 18655 final Executor executor = ActivityThread.currentActivityThread().getExecutor(); 18656 final DisplayManagerInternal display = 18657 LocalServices.getService(DisplayManagerInternal.class); 18658 if (display != null) { 18659 executor.execute(display::onOverlayChanged); 18660 } 18661 if (mWindowManager != null) { 18662 executor.execute(mWindowManager::onOverlayChanged); 18663 } 18664 } 18665 } 18666 18667 /** 18668 * Update the binder call heavy hitter watcher per the new configuration 18669 */ 18670 void scheduleUpdateBinderHeavyHitterWatcherConfig() { 18671 // There are two sets of configs: the default watcher and the auto sampler, 18672 // the default one takes precedence. System would kick off auto sampler when there is 18673 // an anomaly (i.e., consecutive ANRs), but it'll be stopped automatically after a while. 18674 mHandler.post(() -> { 18675 final boolean enabled; 18676 final int batchSize; 18677 final float threshold; 18678 final BinderCallHeavyHitterListener listener; 18679 synchronized (mProcLock) { 18680 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 18681 // Default watcher takes precedence, ignore the auto sampler. 18682 mHandler.removeMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG); 18683 // Set the watcher with the default watcher's config 18684 enabled = true; 18685 batchSize = mConstants.BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE; 18686 threshold = mConstants.BINDER_HEAVY_HITTER_WATCHER_THRESHOLD; 18687 listener = (a, b, c, d) -> mHandler.post( 18688 () -> handleBinderHeavyHitters(a, b, c, d)); 18689 } else if (mHandler.hasMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG)) { 18690 // There is an ongoing auto sampler session, update it 18691 enabled = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED; 18692 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE; 18693 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD; 18694 listener = (a, b, c, d) -> mHandler.post( 18695 () -> handleBinderHeavyHitters(a, b, c, d)); 18696 } else { 18697 // Stop it 18698 enabled = false; 18699 batchSize = 0; 18700 threshold = 0.0f; 18701 listener = null; 18702 } 18703 } 18704 Binder.setHeavyHitterWatcherConfig(enabled, batchSize, threshold, listener); 18705 }); 18706 } 18707 18708 /** 18709 * Kick off the watcher to run for given timeout, it could be throttled however. 18710 */ 18711 void scheduleBinderHeavyHitterAutoSampler() { 18712 mHandler.post(() -> { 18713 final int batchSize; 18714 final float threshold; 18715 final long now; 18716 synchronized (mProcLock) { 18717 if (!mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED) { 18718 // It's configured OFF 18719 return; 18720 } 18721 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 18722 // If the default watcher is active already, don't start the auto sampler 18723 return; 18724 } 18725 now = SystemClock.uptimeMillis(); 18726 if (mLastBinderHeavyHitterAutoSamplerStart 18727 + BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS > now) { 18728 // Too frequent, throttle it 18729 return; 18730 } 18731 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE; 18732 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD; 18733 } 18734 // No lock is needed because we are accessing these variables in handle thread only. 18735 mLastBinderHeavyHitterAutoSamplerStart = now; 18736 // Start the watcher with the auto sampler's config. 18737 Binder.setHeavyHitterWatcherConfig(true, batchSize, threshold, 18738 (a, b, c, d) -> mHandler.post(() -> handleBinderHeavyHitters(a, b, c, d))); 18739 // Schedule to stop it after given timeout. 18740 mHandler.sendMessageDelayed(mHandler.obtainMessage( 18741 BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG), 18742 BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS); 18743 }); 18744 } 18745 18746 /** 18747 * Stop the binder heavy hitter auto sampler after given timeout. 18748 */ 18749 private void handleBinderHeavyHitterAutoSamplerTimeOut() { 18750 synchronized (mProcLock) { 18751 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 18752 // The default watcher is ON, don't bother to stop it. 18753 return; 18754 } 18755 } 18756 Binder.setHeavyHitterWatcherConfig(false, 0, 0.0f, null); 18757 } 18758 18759 /** 18760 * Handle the heavy hitters 18761 */ 18762 private void handleBinderHeavyHitters(@NonNull final List<HeavyHitterContainer> hitters, 18763 final int totalBinderCalls, final float threshold, final long timeSpan) { 18764 final int size = hitters.size(); 18765 if (size == 0) { 18766 return; 18767 } 18768 // Simply log it for now 18769 final String pfmt = "%.1f%%"; 18770 final BinderTransactionNameResolver resolver = new BinderTransactionNameResolver(); 18771 final StringBuilder sb = new StringBuilder("Excessive incoming binder calls(>") 18772 .append(String.format(pfmt, threshold * 100)) 18773 .append(',').append(totalBinderCalls) 18774 .append(',').append(timeSpan) 18775 .append("ms): "); 18776 for (int i = 0; i < size; i++) { 18777 if (i > 0) { 18778 sb.append(", "); 18779 } 18780 final HeavyHitterContainer container = hitters.get(i); 18781 sb.append('[').append(container.mUid) 18782 .append(',').append(container.mClass.getName()) 18783 .append(',').append(resolver.getMethodName(container.mClass, container.mCode)) 18784 .append(',').append(container.mCode) 18785 .append(',').append(String.format(pfmt, container.mFrequency * 100)) 18786 .append(']'); 18787 } 18788 Slog.w(TAG, sb.toString()); 18789 } 18790 18791 /** 18792 * Attach an agent to the specified process (proces name or PID) 18793 */ 18794 public void attachAgent(String process, String path) { 18795 try { 18796 synchronized (mProcLock) { 18797 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_SYSTEM, 18798 "attachAgent"); 18799 IApplicationThread thread; 18800 if (proc == null || (thread = proc.getThread()) == null) { 18801 throw new IllegalArgumentException("Unknown process: " + process); 18802 } 18803 18804 enforceDebuggable(proc); 18805 18806 thread.attachAgent(path); 18807 } 18808 } catch (RemoteException e) { 18809 throw new IllegalStateException("Process disappeared"); 18810 } 18811 } 18812 18813 /** 18814 * When power button is very long pressed, call this interface to do some pre-shutdown work 18815 * like persisting database etc. 18816 */ 18817 public void prepareForPossibleShutdown() { 18818 if (mUsageStatsService != null) { 18819 mUsageStatsService.prepareForPossibleShutdown(); 18820 } 18821 } 18822 18823 @VisibleForTesting 18824 public static class Injector { 18825 private final Context mContext; 18826 private NetworkManagementInternal mNmi; 18827 18828 private UserController mUserController; 18829 18830 public Injector(Context context) { 18831 mContext = context; 18832 } 18833 18834 public Context getContext() { 18835 return mContext; 18836 } 18837 18838 public AppOpsService getAppOpsService(File recentAccessesFile, File storageFile, 18839 Handler handler) { 18840 return new AppOpsService(recentAccessesFile, storageFile, handler, getContext()); 18841 } 18842 18843 public Handler getUiHandler(ActivityManagerService service) { 18844 return service.new UiHandler(); 18845 } 18846 18847 public boolean isNetworkRestrictedForUid(int uid) { 18848 if (ensureHasNetworkManagementInternal()) { 18849 return mNmi.isNetworkRestrictedForUid(uid); 18850 } 18851 return false; 18852 } 18853 18854 /** 18855 * Called by {@code AMS.getDisplayIdsForStartingVisibleBackgroundUsers()}. 18856 */ 18857 // NOTE: ideally Injector should have no complex logic, but if this logic was moved to AMS, 18858 // it could not be tested with the existing ActivityManagerServiceTest (as DisplayManager, 18859 // DisplayInfo, etc... are final and UserManager.isUsersOnSecondaryDisplaysEnabled is 18860 // static). 18861 // So, the logic was added here, and tested on ActivityManagerServiceInjectorTest (which 18862 // was added on FrameworksMockingServicesTests and hence uses Extended Mockito to mock 18863 // final and static stuff) 18864 @Nullable 18865 public int[] getDisplayIdsForStartingVisibleBackgroundUsers() { 18866 if (!UserManager.isVisibleBackgroundUsersEnabled()) { 18867 Slogf.w(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): not supported"); 18868 return null; 18869 } 18870 18871 // NOTE: DisplayManagerInternal doesn't have a method to list all displays 18872 DisplayManager displayManager = mContext.getSystemService(DisplayManager.class); 18873 18874 Display[] allDisplays = displayManager.getDisplays(); 18875 18876 // allDisplays should contain at least Display.DEFAULT_DISPLAY, but it's better to 18877 // double check, just in case... 18878 if (allDisplays == null || allDisplays.length == 0) { 18879 Slogf.wtf(TAG, "displayManager (%s) returned no displays", displayManager); 18880 return null; 18881 } 18882 boolean hasDefaultDisplay = false; 18883 for (Display display : allDisplays) { 18884 if (display.getDisplayId() == Display.DEFAULT_DISPLAY) { 18885 hasDefaultDisplay = true; 18886 break; 18887 } 18888 } 18889 if (!hasDefaultDisplay) { 18890 Slogf.wtf(TAG, "displayManager (%s) has %d displays (%s), but none has id " 18891 + "DEFAULT_DISPLAY (%d)", displayManager, allDisplays.length, 18892 Arrays.toString(allDisplays), Display.DEFAULT_DISPLAY); 18893 return null; 18894 } 18895 18896 boolean allowOnDefaultDisplay = UserManager 18897 .isVisibleBackgroundUsersOnDefaultDisplayEnabled(); 18898 int displaysSize = allDisplays.length; 18899 if (!allowOnDefaultDisplay) { 18900 displaysSize--; 18901 } 18902 int[] displayIds = new int[displaysSize]; 18903 18904 int numberValidDisplays = 0; 18905 for (Display display : allDisplays) { 18906 int displayId = display.getDisplayId(); 18907 // TODO(b/247592632): check other properties like isSecure or proper display type 18908 if (display.isValid() && ((display.getFlags() & Display.FLAG_PRIVATE) == 0) 18909 && (allowOnDefaultDisplay || displayId != Display.DEFAULT_DISPLAY)) { 18910 displayIds[numberValidDisplays++] = displayId; 18911 } 18912 } 18913 18914 if (numberValidDisplays == 0) { 18915 // TODO(b/247580038): remove this workaround once a virtual display on Car's 18916 // KitchenSink (or other app) can be used while running CTS tests on devices that 18917 // don't have a real display. 18918 // STOPSHIP: if not removed, it should at least be unit tested 18919 String testingProp = "fw.display_ids_for_starting_users_for_testing_purposes"; 18920 int displayId = SystemProperties.getInt(testingProp, Display.DEFAULT_DISPLAY); 18921 if (allowOnDefaultDisplay && displayId == Display.DEFAULT_DISPLAY 18922 || displayId > 0) { 18923 Slogf.w(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): no valid " 18924 + "display found, but returning %d as set by property %s", displayId, 18925 testingProp); 18926 return new int[] { displayId }; 18927 } 18928 Slogf.e(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): no valid display" 18929 + " on %s", Arrays.toString(allDisplays)); 18930 return null; 18931 } 18932 18933 if (numberValidDisplays != displayIds.length) { 18934 int[] validDisplayIds = new int[numberValidDisplays]; 18935 System.arraycopy(displayIds, 0, validDisplayIds, 0, numberValidDisplays); 18936 if (DEBUG_MU) { 18937 Slogf.d(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): returning " 18938 + "only valid displays (%d instead of %d): %s", numberValidDisplays, 18939 displayIds.length, Arrays.toString(validDisplayIds)); 18940 } 18941 return validDisplayIds; 18942 } 18943 18944 if (DEBUG_MU) { 18945 Slogf.d(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): returning all (but " 18946 + "DEFAULT_DISPLAY) displays : %s", Arrays.toString(displayIds)); 18947 } 18948 return displayIds; 18949 } 18950 18951 /** 18952 * Called by {@code AMS.startUserInBackgroundVisibleOnDisplay()}. 18953 */ 18954 public boolean startUserInBackgroundVisibleOnDisplay(int userId, int displayId, 18955 @Nullable IProgressListener unlockProgressListener) { 18956 return mUserController.startUserVisibleOnDisplay(userId, displayId, 18957 unlockProgressListener); 18958 } 18959 18960 /** 18961 * Return the process list instance 18962 */ 18963 public ProcessList getProcessList(ActivityManagerService service) { 18964 return new ProcessList(); 18965 } 18966 18967 /** 18968 * Returns the {@link BatteryStatsService} instance 18969 */ 18970 public BatteryStatsService getBatteryStatsService() { 18971 return new BatteryStatsService(mContext, SystemServiceManager.ensureSystemDir()); 18972 } 18973 18974 /** 18975 * Returns the {@link ActiveServices} instance 18976 */ 18977 public ActiveServices getActiveServices(ActivityManagerService service) { 18978 return new ActiveServices(service); 18979 } 18980 18981 private boolean ensureHasNetworkManagementInternal() { 18982 if (mNmi == null) { 18983 mNmi = LocalServices.getService(NetworkManagementInternal.class); 18984 } 18985 return mNmi != null; 18986 } 18987 18988 public BroadcastQueue getBroadcastQueue(ActivityManagerService service) { 18989 // Broadcast policy parameters 18990 final BroadcastConstants foreConstants = new BroadcastConstants( 18991 Settings.Global.BROADCAST_FG_CONSTANTS); 18992 foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT; 18993 18994 final BroadcastConstants backConstants = new BroadcastConstants( 18995 Settings.Global.BROADCAST_BG_CONSTANTS); 18996 backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; 18997 18998 return new BroadcastQueueImpl(service, service.mHandler, 18999 foreConstants, backConstants); 19000 } 19001 19002 /** @see Binder#getCallingUid */ 19003 public int getCallingUid() { 19004 return Binder.getCallingUid(); 19005 } 19006 19007 /** @see Binder#getCallingPid */ 19008 public int getCallingPid() { 19009 return Binder.getCallingPid(); 19010 } 19011 19012 /** @see Binder#clearCallingIdentity */ 19013 public long clearCallingIdentity() { 19014 return Binder.clearCallingIdentity(); 19015 } 19016 19017 /** @see Binder#clearCallingIdentity */ 19018 public void restoreCallingIdentity(long ident) { 19019 Binder.restoreCallingIdentity(ident); 19020 } 19021 19022 /** @return the default instance of AppErrors */ 19023 public AppErrors getAppErrors() { 19024 return null; 19025 } 19026 19027 /** @return the default instance of intent firewall */ 19028 public IntentFirewall getIntentFirewall() { 19029 return null; 19030 } 19031 19032 /** @return the default Freezer. */ 19033 public Freezer getFreezer() { 19034 return new Freezer(); 19035 } 19036 } 19037 19038 @Override 19039 public void startDelegateShellPermissionIdentity(int delegateUid, 19040 @Nullable String[] permissions) { 19041 getAccessCheckDelegateHelper() 19042 .startDelegateShellPermissionIdentity(delegateUid, permissions); 19043 } 19044 19045 @Override 19046 public void stopDelegateShellPermissionIdentity() { 19047 getAccessCheckDelegateHelper().stopDelegateShellPermissionIdentity(); 19048 } 19049 19050 @Override 19051 public List<String> getDelegatedShellPermissions() { 19052 return getAccessCheckDelegateHelper().getDelegatedShellPermissions(); 19053 } 19054 19055 @Override 19056 public void addOverridePermissionState(int originatingUid, int uid, String permission, 19057 int result) { 19058 getAccessCheckDelegateHelper() 19059 .addOverridePermissionState(originatingUid, uid, permission, result); 19060 } 19061 19062 @Override 19063 public void removeOverridePermissionState(int originatingUid, int uid, String permission) { 19064 getAccessCheckDelegateHelper() 19065 .removeOverridePermissionState(originatingUid, uid, permission); 19066 } 19067 19068 @Override 19069 public void clearOverridePermissionStates(int originatingUid, int uid) { 19070 getAccessCheckDelegateHelper().clearOverridePermissionStates(originatingUid, uid); 19071 } 19072 19073 @Override 19074 public void clearAllOverridePermissionStates(int originatingUid) { 19075 getAccessCheckDelegateHelper().clearAllOverridePermissionStates(originatingUid); 19076 } 19077 19078 /** 19079 * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would 19080 * cause a watchdog kill. 19081 */ 19082 void maybeTriggerWatchdog() { 19083 final String key = "debug.trigger.watchdog"; 19084 if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) { 19085 Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!"); 19086 19087 // Clear the property; otherwise the system would hang again after a watchdog restart. 19088 SystemProperties.set(key, ""); 19089 synchronized (ActivityManagerService.this) { 19090 try { 19091 // Arbitrary long sleep for watchdog to catch. 19092 Thread.sleep(60 * 60 * 1000); 19093 } catch (InterruptedException e) { 19094 } 19095 } 19096 } 19097 } 19098 19099 @Override 19100 public ParcelFileDescriptor getLifeMonitor() { 19101 if (!isCallerShell()) { 19102 throw new SecurityException("Only shell can call it"); 19103 } 19104 synchronized (mProcLock) { 19105 try { 19106 if (mLifeMonitorFds == null) { 19107 mLifeMonitorFds = ParcelFileDescriptor.createPipe(); 19108 } 19109 // The returned FD will be closed, but we want to keep our reader open, 19110 // so return a dup instead. 19111 return mLifeMonitorFds[0].dup(); 19112 } catch (IOException e) { 19113 Slog.w(TAG, "Unable to create pipe", e); 19114 return null; 19115 } 19116 } 19117 } 19118 19119 @Override 19120 public void setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken) { 19121 final int callingUid = Binder.getCallingUid(); 19122 final int userId = UserHandle.getCallingUserId(); 19123 if (getPackageManagerInternal().getPackageUid(activity.getPackageName(), 19124 /*flags=*/ 0, userId) != callingUid) { 19125 throw new SecurityException("Calling uid " + callingUid + " cannot set locusId" 19126 + "for package " + activity.getPackageName()); 19127 } 19128 mActivityTaskManager.setLocusId(locusId, appToken); 19129 if (mUsageStatsService != null) { 19130 mUsageStatsService.reportLocusUpdate(activity, userId, locusId, appToken); 19131 } 19132 } 19133 19134 @Override 19135 public boolean isAppFreezerSupported() { 19136 final long token = Binder.clearCallingIdentity(); 19137 19138 try { 19139 return mFreezer.isFreezerSupported(); 19140 } finally { 19141 Binder.restoreCallingIdentity(token); 19142 } 19143 } 19144 19145 @Override 19146 public boolean isAppFreezerEnabled() { 19147 return mOomAdjuster.mCachedAppOptimizer.useFreezer(); 19148 } 19149 19150 public boolean isAppFreezerExemptInstPkg() { 19151 return mOomAdjuster.mCachedAppOptimizer.freezerExemptInstPkg(); 19152 } 19153 19154 /** 19155 * Resets the state of the {@link com.android.server.am.AppErrors} instance. 19156 * This is intended for testing within the CTS only and is protected by 19157 * android.permission.RESET_APP_ERRORS. 19158 */ 19159 @Override 19160 public void resetAppErrors() { 19161 enforceCallingPermission(Manifest.permission.RESET_APP_ERRORS, "resetAppErrors"); 19162 mAppErrors.resetState(); 19163 } 19164 19165 @Override 19166 public boolean enableAppFreezer(boolean enable) { 19167 int callerUid = Binder.getCallingUid(); 19168 19169 // Only system can toggle the freezer state 19170 if (callerUid == SYSTEM_UID || Build.IS_DEBUGGABLE) { 19171 return mOomAdjuster.mCachedAppOptimizer.enableFreezer(enable); 19172 } else { 19173 throw new SecurityException("Caller uid " + callerUid + " cannot set freezer state "); 19174 } 19175 } 19176 19177 /** 19178 * Suppress or reenable the rate limit on foreground service notification deferral. 19179 * @param enable false to suppress rate-limit policy; true to reenable it. 19180 */ 19181 @Override 19182 public boolean enableFgsNotificationRateLimit(boolean enable) { 19183 if (android.security.Flags.protectDeviceConfigFlags()) { 19184 enforceCallingHasAtLeastOnePermission("enableFgsNotificationRateLimit", 19185 permission.WRITE_DEVICE_CONFIG, permission.WRITE_ALLOWLISTED_DEVICE_CONFIG); 19186 } else { 19187 enforceCallingPermission(permission.WRITE_DEVICE_CONFIG, 19188 "enableFgsNotificationRateLimit"); 19189 } 19190 synchronized (this) { 19191 return mServices.enableFgsNotificationRateLimitLocked(enable); 19192 } 19193 } 19194 19195 /** 19196 * Holds the AM lock for the specified amount of milliseconds. 19197 * Intended for use by the tests that need to imitate lock contention. 19198 * The token should be obtained by 19199 * {@link android.content.pm.PackageManager#getHoldLockToken()}. 19200 */ 19201 @Override 19202 public void holdLock(IBinder token, int durationMs) { 19203 getTestUtilityServiceLocked().verifyHoldLockToken(token); 19204 19205 synchronized (this) { 19206 SystemClock.sleep(durationMs); 19207 } 19208 } 19209 19210 static void traceBegin(long traceTag, String methodName, String subInfo) { 19211 if (Trace.isTagEnabled(traceTag)) { 19212 Trace.traceBegin(traceTag, methodName + subInfo); 19213 } 19214 } 19215 19216 private void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, 19217 @MediaProjectionTokenEvent int event) { 19218 synchronized (mMediaProjectionTokenMap) { 19219 final int index = mMediaProjectionTokenMap.indexOfKey(uid); 19220 ArraySet<IBinder> tokens; 19221 if (event == MEDIA_PROJECTION_TOKEN_EVENT_CREATED) { 19222 if (index < 0) { 19223 tokens = new ArraySet(); 19224 mMediaProjectionTokenMap.put(uid, tokens); 19225 } else { 19226 tokens = mMediaProjectionTokenMap.valueAt(index); 19227 } 19228 tokens.add(projectionToken); 19229 } else if (event == MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED && index >= 0) { 19230 tokens = mMediaProjectionTokenMap.valueAt(index); 19231 tokens.remove(projectionToken); 19232 if (tokens.isEmpty()) { 19233 mMediaProjectionTokenMap.removeAt(index); 19234 } 19235 } 19236 } 19237 } 19238 19239 /** 19240 * @return {@code true} if the MediaProjectionManagerService has created a media projection 19241 * for the given {@code uid} because the user has granted the permission; 19242 * it doesn't necessarily mean it has started the projection. 19243 * 19244 * <p>It doesn't check the {@link AppOpsManager#OP_PROJECT_MEDIA}.</p> 19245 */ 19246 boolean isAllowedMediaProjectionNoOpCheck(int uid) { 19247 synchronized (mMediaProjectionTokenMap) { 19248 final int index = mMediaProjectionTokenMap.indexOfKey(uid); 19249 return index >= 0 && !mMediaProjectionTokenMap.valueAt(index).isEmpty(); 19250 } 19251 } 19252 19253 /** 19254 * Deal with binder transactions to frozen apps. 19255 * 19256 * @param debugPid The binder transaction sender 19257 * @param code The binder transaction code 19258 * @param flags The binder transaction flags 19259 * @param err The binder transaction error 19260 */ 19261 @Override 19262 public void frozenBinderTransactionDetected(int debugPid, int code, int flags, int err) { 19263 final ProcessRecord app; 19264 synchronized (mPidsSelfLocked) { 19265 app = mPidsSelfLocked.get(debugPid); 19266 } 19267 mOomAdjuster.mCachedAppOptimizer.binderError(debugPid, app, code, flags, err); 19268 } 19269 19270 @GuardedBy("this") 19271 void enqueuePendingTopAppIfNecessaryLocked() { 19272 mPendingStartActivityUids.enqueuePendingTopAppIfNecessaryLocked(this); 19273 } 19274 19275 @GuardedBy("this") 19276 void clearPendingTopAppLocked() { 19277 mPendingStartActivityUids.clear(); 19278 } 19279 19280 @NonNull 19281 Freezer getFreezer() { 19282 return mFreezer; 19283 } 19284 19285 // Set of IntentCreatorToken objects that are currently active. 19286 private static final Map<IntentCreatorToken.Key, WeakReference<IntentCreatorToken>> 19287 sIntentCreatorTokenCache = new ConcurrentHashMap<>(); 19288 19289 private static Handler sCreatorTokenCacheCleaner; 19290 /** 19291 * A binder token used to keep track of which app created the intent. This token can be used to 19292 * defend against intent redirect attacks. It stores uid of the intent creator and key fields of 19293 * the intent to make it impossible for attacker to fake uid with a malicious intent. 19294 * 19295 * @hide 19296 */ 19297 @VisibleForTesting 19298 public static final class IntentCreatorToken extends Binder { 19299 @NonNull 19300 private final Key mKeyFields; 19301 private final WeakReference<IntentCreatorToken> mRef; 19302 19303 public IntentCreatorToken(int creatorUid, String creatorPackage, Intent intent) { 19304 super(); 19305 this.mKeyFields = new Key(creatorUid, creatorPackage, intent); 19306 mRef = new WeakReference<>(this); 19307 } 19308 19309 public int getCreatorUid() { 19310 return mKeyFields.mCreatorUid; 19311 } 19312 19313 public String getCreatorPackage() { 19314 return mKeyFields.mCreatorPackage; 19315 } 19316 19317 @VisibleForTesting 19318 public @NonNull Key getKeyFields() { 19319 return mKeyFields; 19320 } 19321 19322 public static boolean isValid(@NonNull Intent intent) { 19323 IBinder binder = intent.getCreatorToken(); 19324 IntentCreatorToken token = null; 19325 if (binder instanceof IntentCreatorToken) { 19326 token = (IntentCreatorToken) binder; 19327 } 19328 return token != null && token.mKeyFields.equals( 19329 new Key(token.mKeyFields.mCreatorUid, token.mKeyFields.mCreatorPackage, 19330 intent)); 19331 } 19332 19333 @Override 19334 protected void finalize() throws Throwable { 19335 try { 19336 sCreatorTokenCacheCleaner.sendMessage(PooledLambda.obtainMessage( 19337 IntentCreatorToken::completeFinalize, this)); 19338 } finally { 19339 super.finalize(); 19340 } 19341 } 19342 19343 private void completeFinalize() { 19344 synchronized (sIntentCreatorTokenCache) { 19345 WeakReference<IntentCreatorToken> current = sIntentCreatorTokenCache.get( 19346 mKeyFields); 19347 if (current == mRef) { 19348 sIntentCreatorTokenCache.remove(mKeyFields); 19349 } 19350 } 19351 } 19352 19353 private static class Key { 19354 private Key(int creatorUid, String creatorPackage, Intent intent) { 19355 this.mCreatorUid = creatorUid; 19356 this.mCreatorPackage = creatorPackage; 19357 this.mAction = intent.getAction(); 19358 this.mData = intent.getData(); 19359 this.mType = intent.getType(); 19360 this.mPackage = intent.getPackage(); 19361 this.mComponent = intent.getComponent(); 19362 this.mFlags = intent.getFlags() & Intent.IMMUTABLE_FLAGS; 19363 ClipData clipData = intent.getClipData(); 19364 if (clipData != null) { 19365 clipData = clipData.cloneOnlyUriItems(); 19366 if (clipData != null) { 19367 List<Uri> clipDataUris = new ArrayList<>(); 19368 clipData.collectUris(clipDataUris); 19369 if (!clipDataUris.isEmpty()) { 19370 this.mClipDataUris = clipDataUris; 19371 } 19372 } 19373 } 19374 } 19375 19376 private final int mCreatorUid; 19377 private final String mCreatorPackage; 19378 private final String mAction; 19379 private final Uri mData; 19380 private final String mType; 19381 private final String mPackage; 19382 private final ComponentName mComponent; 19383 private final int mFlags; 19384 private List<Uri> mClipDataUris; 19385 19386 @Override 19387 public boolean equals(Object o) { 19388 if (this == o) return true; 19389 if (o == null || getClass() != o.getClass()) return false; 19390 Key key = (Key) o; 19391 return mCreatorUid == key.mCreatorUid && mFlags == key.mFlags 19392 && Objects.equals(mCreatorPackage, key.mCreatorPackage) 19393 && Objects.equals(mAction, key.mAction) 19394 && Objects.equals(mData, key.mData) 19395 && Objects.equals(mType, key.mType) 19396 && Objects.equals(mPackage, key.mPackage) 19397 && Objects.equals(mComponent, key.mComponent) 19398 && Objects.equals(mClipDataUris, key.mClipDataUris); 19399 } 19400 19401 @Override 19402 public int hashCode() { 19403 return Objects.hash(mCreatorUid, mCreatorPackage, mAction, mData, mType, mPackage, 19404 mComponent, mFlags, mClipDataUris); 19405 } 19406 } 19407 } 19408 19409 /** 19410 * Add a creator token for all embedded intents (stored as extra) of the given intent. 19411 * 19412 * @param intent The given intent 19413 * @hide 19414 */ 19415 public void addCreatorToken(@Nullable Intent intent, String creatorPackage) { 19416 if (!preventIntentRedirect()) return; 19417 if (intent == null) return; 19418 19419 int callingUid = Binder.getCallingUid(); 19420 if (((intent.getExtendedFlags() & Intent.EXTENDED_FLAG_NESTED_INTENT_KEYS_COLLECTED) == 0) 19421 && intent.getExtras() != null && intent.getExtras().hasIntent()) { 19422 Slog.wtf(TAG, 19423 "[IntentRedirect Hardening] The intent does not have its nested keys collected as a " 19424 + "preparation for creating intent creator tokens. Intent: " 19425 + intent + "; creatorPackage: " + creatorPackage); 19426 FrameworkStatsLog.write(EXTRA_INTENT_KEYS_COLLECTED_ON_SERVER, callingUid); 19427 if (preventIntentRedirectShowToastIfNestedKeysNotCollectedRW()) { 19428 UiThread.getHandler().post( 19429 () -> Toast.makeText(mContext, 19430 "Nested keys not collected, activity launch won't be blocked. go/report-bug-intentRedir to report a" 19431 + " bug", Toast.LENGTH_LONG).show()); 19432 } 19433 if (preventIntentRedirectThrowExceptionIfNestedKeysNotCollected()) { 19434 // this flag will be internal only, not ramped to public. 19435 throw new SecurityException( 19436 "The intent does not have its nested keys collected as a preparation for " 19437 + "creating intent creator tokens. Intent: " 19438 + intent + "; creatorPackage: " + creatorPackage); 19439 } 19440 if (preventIntentRedirectCollectNestedKeysOnServerIfNotCollected()) { 19441 // this flag will be ramped to public. 19442 intent.collectExtraIntentKeys(true); 19443 } 19444 } 19445 19446 String targetPackage = intent.getComponent() != null 19447 ? intent.getComponent().getPackageName() 19448 : intent.getPackage(); 19449 final boolean isCreatorSameAsTarget = creatorPackage != null && creatorPackage.equals( 19450 targetPackage); 19451 final boolean noExtraIntentKeys = 19452 intent.getExtraIntentKeys() == null || intent.getExtraIntentKeys().isEmpty(); 19453 final int creatorUid = noExtraIntentKeys ? DEFAULT_INTENT_CREATOR_UID : callingUid; 19454 19455 intent.forEachNestedCreatorToken(extraIntent -> { 19456 if (isCreatorSameAsTarget) { 19457 FrameworkStatsLog.write(INTENT_CREATOR_TOKEN_ADDED, creatorUid, true); 19458 return; 19459 } 19460 IntentCreatorToken creatorToken = createIntentCreatorToken(extraIntent, creatorUid, 19461 creatorPackage); 19462 if (creatorToken != null) { 19463 extraIntent.setCreatorToken(creatorToken); 19464 FrameworkStatsLog.write(INTENT_CREATOR_TOKEN_ADDED, creatorUid, false); 19465 } 19466 }); 19467 } 19468 19469 private IntentCreatorToken createIntentCreatorToken(Intent intent, int creatorUid, 19470 String creatorPackage) { 19471 if (IntentCreatorToken.isValid(intent)) return null; 19472 IntentCreatorToken.Key key = new IntentCreatorToken.Key(creatorUid, creatorPackage, intent); 19473 return createOrGetIntentCreatorToken(intent, key); 19474 } 19475 19476 /** 19477 * @hide 19478 */ 19479 @EnforcePermission(INTERACT_ACROSS_USERS_FULL) 19480 public IBinder refreshIntentCreatorToken(Intent intent) { 19481 refreshIntentCreatorToken_enforcePermission(); 19482 IBinder binder = intent.getCreatorToken(); 19483 if (binder instanceof IntentCreatorToken) { 19484 IntentCreatorToken token = (IntentCreatorToken) binder; 19485 IntentCreatorToken.Key key = new IntentCreatorToken.Key(token.getCreatorUid(), 19486 token.getCreatorPackage(), intent); 19487 return createOrGetIntentCreatorToken(intent, key); 19488 19489 } else { 19490 return null; 19491 } 19492 } 19493 19494 private static IntentCreatorToken createOrGetIntentCreatorToken(Intent intent, 19495 IntentCreatorToken.Key key) { 19496 IntentCreatorToken token; 19497 synchronized (sIntentCreatorTokenCache) { 19498 WeakReference<IntentCreatorToken> ref = sIntentCreatorTokenCache.get(key); 19499 if (ref == null || ref.get() == null) { 19500 token = new IntentCreatorToken(key.mCreatorUid, key.mCreatorPackage, intent); 19501 sIntentCreatorTokenCache.put(key, token.mRef); 19502 } else { 19503 token = ref.get(); 19504 } 19505 } 19506 return token; 19507 } 19508 } 19509