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.START_ACTIVITIES_FROM_BACKGROUND; 26 import static android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND; 27 import static android.app.ActivityManager.INSTR_FLAG_ALWAYS_CHECK_SIGNATURE; 28 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS; 29 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_ISOLATED_STORAGE; 30 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_TEST_API_CHECKS; 31 import static android.app.ActivityManager.INSTR_FLAG_NO_RESTART; 32 import static android.app.ActivityManager.INTENT_SENDER_ACTIVITY; 33 import static android.app.ActivityManager.PROCESS_CAPABILITY_ALL; 34 import static android.app.ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 35 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT; 36 import static android.app.ActivityManager.PROCESS_STATE_TOP; 37 import static android.app.ActivityManager.StopUserOnSwitch; 38 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY; 39 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL; 40 import static android.app.AppOpsManager.MODE_ALLOWED; 41 import static android.app.AppOpsManager.OP_NONE; 42 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 43 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES; 44 import static android.content.pm.PackageManager.MATCH_ALL; 45 import static android.content.pm.PackageManager.MATCH_ANY_USER; 46 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 47 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 48 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 49 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 50 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 51 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 52 import static android.net.ConnectivityManager.BLOCKED_REASON_NONE; 53 import static android.os.FactoryTest.FACTORY_TEST_OFF; 54 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL; 55 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH; 56 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL; 57 import static android.os.IServiceManager.DUMP_FLAG_PROTO; 58 import static android.os.InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS; 59 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALLOW_LISTED; 60 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED; 61 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_NONE; 62 import static android.os.Process.BLUETOOTH_UID; 63 import static android.os.Process.FIRST_APPLICATION_UID; 64 import static android.os.Process.INVALID_UID; 65 import static android.os.Process.NETWORK_STACK_UID; 66 import static android.os.Process.NFC_UID; 67 import static android.os.Process.PHONE_UID; 68 import static android.os.Process.PROC_OUT_LONG; 69 import static android.os.Process.PROC_SPACE_TERM; 70 import static android.os.Process.ROOT_UID; 71 import static android.os.Process.SCHED_FIFO; 72 import static android.os.Process.SCHED_RESET_ON_FORK; 73 import static android.os.Process.SE_UID; 74 import static android.os.Process.SHELL_UID; 75 import static android.os.Process.SIGNAL_USR1; 76 import static android.os.Process.SYSTEM_UID; 77 import static android.os.Process.THREAD_PRIORITY_FOREGROUND; 78 import static android.os.Process.THREAD_PRIORITY_TOP_APP_BOOST; 79 import static android.os.Process.ZYGOTE_POLICY_FLAG_BATCH_LAUNCH; 80 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY; 81 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE; 82 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS; 83 import static android.os.Process.ZYGOTE_PROCESS; 84 import static android.os.Process.getTotalMemory; 85 import static android.os.Process.isSdkSandboxUid; 86 import static android.os.Process.isThreadInProcess; 87 import static android.os.Process.killProcess; 88 import static android.os.Process.killProcessQuiet; 89 import static android.os.Process.myPid; 90 import static android.os.Process.myUid; 91 import static android.os.Process.readProcFile; 92 import static android.os.Process.sendSignal; 93 import static android.os.Process.setThreadPriority; 94 import static android.os.Process.setThreadScheduler; 95 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES; 96 import static android.provider.Settings.Global.DEBUG_APP; 97 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER; 98 import static android.text.format.DateUtils.DAY_IN_MILLIS; 99 import static android.util.FeatureFlagUtils.SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS; 100 101 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_CONFIGURATION; 102 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL; 103 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALLOWLISTS; 104 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR; 105 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK; 106 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP; 107 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; 108 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND; 109 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; 110 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 111 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK; 112 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ; 113 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER; 114 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES; 115 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE; 116 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP; 117 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; 118 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP; 119 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU; 120 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; 121 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK; 122 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ; 123 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER; 124 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES; 125 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE; 126 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS; 127 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 128 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 129 import static com.android.server.am.MemoryStatUtil.hasMemcg; 130 import static com.android.server.am.ProcessList.ProcStartHandler; 131 import static com.android.server.am.ProcessProfileRecord.HOSTING_COMPONENT_TYPE_BACKUP; 132 import static com.android.server.am.ProcessProfileRecord.HOSTING_COMPONENT_TYPE_INSTRUMENTATION; 133 import static com.android.server.am.ProcessProfileRecord.HOSTING_COMPONENT_TYPE_PERSISTENT; 134 import static com.android.server.am.ProcessProfileRecord.HOSTING_COMPONENT_TYPE_SYSTEM; 135 import static com.android.server.net.NetworkPolicyManagerInternal.updateBlockedReasonsWithProcState; 136 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 137 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP; 138 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH; 139 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION; 140 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK; 141 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH; 142 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD; 143 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD; 144 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD; 145 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD; 146 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD; 147 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD; 148 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD; 149 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD; 150 import static com.android.server.wm.ActivityTaskManagerService.DUMP_TOP_RESUMED_ACTIVITY; 151 import static com.android.server.wm.ActivityTaskManagerService.DUMP_VISIBLE_ACTIVITIES; 152 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE; 153 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString; 154 155 import android.Manifest; 156 import android.Manifest.permission; 157 import android.annotation.NonNull; 158 import android.annotation.Nullable; 159 import android.annotation.UserIdInt; 160 import android.app.Activity; 161 import android.app.ActivityClient; 162 import android.app.ActivityManager; 163 import android.app.ActivityManager.PendingIntentInfo; 164 import android.app.ActivityManager.ProcessCapability; 165 import android.app.ActivityManager.RestrictionLevel; 166 import android.app.ActivityManager.RunningTaskInfo; 167 import android.app.ActivityManagerInternal; 168 import android.app.ActivityManagerInternal.BindServiceEventListener; 169 import android.app.ActivityManagerInternal.BroadcastEventListener; 170 import android.app.ActivityManagerInternal.ForegroundServiceStateListener; 171 import android.app.ActivityTaskManager.RootTaskInfo; 172 import android.app.ActivityThread; 173 import android.app.AnrController; 174 import android.app.AppGlobals; 175 import android.app.AppOpsManager; 176 import android.app.AppOpsManager.AttributionFlags; 177 import android.app.AppOpsManagerInternal.CheckOpsDelegate; 178 import android.app.ApplicationErrorReport; 179 import android.app.ApplicationExitInfo; 180 import android.app.ApplicationThreadConstants; 181 import android.app.BroadcastOptions; 182 import android.app.ContentProviderHolder; 183 import android.app.IActivityController; 184 import android.app.IActivityManager; 185 import android.app.IApplicationThread; 186 import android.app.IForegroundServiceObserver; 187 import android.app.IInstrumentationWatcher; 188 import android.app.INotificationManager; 189 import android.app.IProcessObserver; 190 import android.app.IServiceConnection; 191 import android.app.IStopUserCallback; 192 import android.app.ITaskStackListener; 193 import android.app.IUiAutomationConnection; 194 import android.app.IUidObserver; 195 import android.app.IUserSwitchObserver; 196 import android.app.Instrumentation; 197 import android.app.Notification; 198 import android.app.NotificationManager; 199 import android.app.PendingIntent; 200 import android.app.PendingIntentStats; 201 import android.app.ProcessMemoryState; 202 import android.app.ProfilerInfo; 203 import android.app.SyncNotedAppOp; 204 import android.app.WaitResult; 205 import android.app.backup.BackupManager.OperationType; 206 import android.app.backup.IBackupManager; 207 import android.app.compat.CompatChanges; 208 import android.app.job.JobParameters; 209 import android.app.usage.UsageEvents; 210 import android.app.usage.UsageEvents.Event; 211 import android.app.usage.UsageStatsManager; 212 import android.app.usage.UsageStatsManagerInternal; 213 import android.appwidget.AppWidgetManager; 214 import android.appwidget.AppWidgetManagerInternal; 215 import android.compat.annotation.ChangeId; 216 import android.compat.annotation.Disabled; 217 import android.content.AttributionSource; 218 import android.content.AutofillOptions; 219 import android.content.BroadcastReceiver; 220 import android.content.ComponentCallbacks2; 221 import android.content.ComponentName; 222 import android.content.ContentCaptureOptions; 223 import android.content.ContentProvider; 224 import android.content.ContentResolver; 225 import android.content.Context; 226 import android.content.IIntentReceiver; 227 import android.content.IIntentSender; 228 import android.content.Intent; 229 import android.content.IntentFilter; 230 import android.content.LocusId; 231 import android.content.ServiceConnection; 232 import android.content.pm.ActivityInfo; 233 import android.content.pm.ActivityPresentationInfo; 234 import android.content.pm.ApplicationInfo; 235 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy; 236 import android.content.pm.IPackageDataObserver; 237 import android.content.pm.IPackageManager; 238 import android.content.pm.IncrementalStatesInfo; 239 import android.content.pm.InstrumentationInfo; 240 import android.content.pm.PackageInfo; 241 import android.content.pm.PackageManager; 242 import android.content.pm.PackageManager.NameNotFoundException; 243 import android.content.pm.PackageManagerInternal; 244 import android.content.pm.ParceledListSlice; 245 import android.content.pm.PermissionInfo; 246 import android.content.pm.ProcessInfo; 247 import android.content.pm.ProviderInfo; 248 import android.content.pm.ProviderInfoList; 249 import android.content.pm.ResolveInfo; 250 import android.content.pm.ServiceInfo; 251 import android.content.pm.TestUtilityService; 252 import android.content.pm.UserInfo; 253 import android.content.res.CompatibilityInfo; 254 import android.content.res.Configuration; 255 import android.content.res.Resources; 256 import android.database.ContentObserver; 257 import android.graphics.Rect; 258 import android.hardware.display.DisplayManagerInternal; 259 import android.media.audiofx.AudioEffect; 260 import android.net.ConnectivityManager; 261 import android.net.Proxy; 262 import android.net.Uri; 263 import android.os.AppZygote; 264 import android.os.BatteryStats; 265 import android.os.Binder; 266 import android.os.BinderProxy; 267 import android.os.BugreportParams; 268 import android.os.Build; 269 import android.os.Bundle; 270 import android.os.Debug; 271 import android.os.DropBoxManager; 272 import android.os.FactoryTest; 273 import android.os.FileUtils; 274 import android.os.Handler; 275 import android.os.IBinder; 276 import android.os.IDeviceIdentifiersPolicyService; 277 import android.os.IPermissionController; 278 import android.os.IProcessInfoService; 279 import android.os.IProgressListener; 280 import android.os.InputConstants; 281 import android.os.Looper; 282 import android.os.Message; 283 import android.os.Parcel; 284 import android.os.ParcelFileDescriptor; 285 import android.os.PowerExemptionManager; 286 import android.os.PowerExemptionManager.ReasonCode; 287 import android.os.PowerExemptionManager.TempAllowListType; 288 import android.os.PowerManager; 289 import android.os.PowerManager.ServiceType; 290 import android.os.PowerManagerInternal; 291 import android.os.Process; 292 import android.os.RemoteCallback; 293 import android.os.RemoteException; 294 import android.os.ResultReceiver; 295 import android.os.ServiceManager; 296 import android.os.SharedMemory; 297 import android.os.ShellCallback; 298 import android.os.StrictMode; 299 import android.os.SystemClock; 300 import android.os.SystemProperties; 301 import android.os.Trace; 302 import android.os.TransactionTooLargeException; 303 import android.os.UserHandle; 304 import android.os.UserManager; 305 import android.os.WorkSource; 306 import android.os.incremental.IIncrementalService; 307 import android.os.incremental.IncrementalManager; 308 import android.os.incremental.IncrementalMetrics; 309 import android.os.storage.IStorageManager; 310 import android.os.storage.StorageManager; 311 import android.provider.DeviceConfig; 312 import android.provider.Settings; 313 import android.server.ServerProtoEnums; 314 import android.sysprop.InitProperties; 315 import android.sysprop.VoldProperties; 316 import android.telephony.TelephonyManager; 317 import android.text.TextUtils; 318 import android.text.style.SuggestionSpan; 319 import android.util.ArrayMap; 320 import android.util.ArraySet; 321 import android.util.EventLog; 322 import android.util.FeatureFlagUtils; 323 import android.util.IntArray; 324 import android.util.Log; 325 import android.util.Pair; 326 import android.util.PrintWriterPrinter; 327 import android.util.Slog; 328 import android.util.SparseArray; 329 import android.util.SparseIntArray; 330 import android.util.TimeUtils; 331 import android.util.proto.ProtoOutputStream; 332 import android.util.proto.ProtoUtils; 333 import android.view.Gravity; 334 import android.view.LayoutInflater; 335 import android.view.View; 336 import android.view.WindowManager; 337 import android.view.autofill.AutofillManagerInternal; 338 339 import com.android.internal.annotations.CompositeRWLock; 340 import com.android.internal.annotations.GuardedBy; 341 import com.android.internal.annotations.VisibleForTesting; 342 import com.android.internal.app.IAppOpsActiveCallback; 343 import com.android.internal.app.IAppOpsCallback; 344 import com.android.internal.app.IAppOpsService; 345 import com.android.internal.app.ProcessMap; 346 import com.android.internal.app.SystemUserHomeActivity; 347 import com.android.internal.app.procstats.ProcessState; 348 import com.android.internal.app.procstats.ProcessStats; 349 import com.android.internal.content.InstallLocationUtils; 350 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 351 import com.android.internal.notification.SystemNotificationChannels; 352 import com.android.internal.os.BackgroundThread; 353 import com.android.internal.os.BatteryStatsImpl; 354 import com.android.internal.os.BinderCallHeavyHitterWatcher.BinderCallHeavyHitterListener; 355 import com.android.internal.os.BinderCallHeavyHitterWatcher.HeavyHitterContainer; 356 import com.android.internal.os.BinderInternal; 357 import com.android.internal.os.BinderTransactionNameResolver; 358 import com.android.internal.os.ByteTransferPipe; 359 import com.android.internal.os.IResultReceiver; 360 import com.android.internal.os.ProcessCpuTracker; 361 import com.android.internal.os.SomeArgs; 362 import com.android.internal.os.TransferPipe; 363 import com.android.internal.os.Zygote; 364 import com.android.internal.policy.AttributeCache; 365 import com.android.internal.protolog.common.ProtoLog; 366 import com.android.internal.util.ArrayUtils; 367 import com.android.internal.util.DumpUtils; 368 import com.android.internal.util.FastPrintWriter; 369 import com.android.internal.util.FrameworkStatsLog; 370 import com.android.internal.util.MemInfoReader; 371 import com.android.internal.util.Preconditions; 372 import com.android.internal.util.function.HeptFunction; 373 import com.android.internal.util.function.HexFunction; 374 import com.android.internal.util.function.QuadFunction; 375 import com.android.internal.util.function.QuintFunction; 376 import com.android.internal.util.function.UndecFunction; 377 import com.android.server.AlarmManagerInternal; 378 import com.android.server.DeviceIdleInternal; 379 import com.android.server.DisplayThread; 380 import com.android.server.IntentResolver; 381 import com.android.server.IoThread; 382 import com.android.server.LocalManagerRegistry; 383 import com.android.server.LocalServices; 384 import com.android.server.LockGuard; 385 import com.android.server.NetworkManagementInternal; 386 import com.android.server.PackageWatchdog; 387 import com.android.server.ServiceThread; 388 import com.android.server.SystemConfig; 389 import com.android.server.SystemService; 390 import com.android.server.SystemServiceManager; 391 import com.android.server.ThreadPriorityBooster; 392 import com.android.server.UserspaceRebootLogger; 393 import com.android.server.Watchdog; 394 import com.android.server.am.ComponentAliasResolver.Resolution; 395 import com.android.server.am.LowMemDetector.MemFactor; 396 import com.android.server.appop.AppOpsService; 397 import com.android.server.compat.PlatformCompat; 398 import com.android.server.contentcapture.ContentCaptureManagerInternal; 399 import com.android.server.criticalevents.CriticalEventLog; 400 import com.android.server.firewall.IntentFirewall; 401 import com.android.server.graphics.fonts.FontManagerInternal; 402 import com.android.server.job.JobSchedulerInternal; 403 import com.android.server.os.NativeTombstoneManager; 404 import com.android.server.pm.Computer; 405 import com.android.server.pm.Installer; 406 import com.android.server.pm.UserManagerInternal; 407 import com.android.server.pm.parsing.pkg.AndroidPackage; 408 import com.android.server.pm.permission.PermissionManagerServiceInternal; 409 import com.android.server.pm.pkg.SELinuxUtil; 410 import com.android.server.pm.pkg.parsing.ParsingPackageUtils; 411 import com.android.server.pm.snapshot.PackageDataSnapshot; 412 import com.android.server.sdksandbox.SdkSandboxManagerLocal; 413 import com.android.server.uri.GrantUri; 414 import com.android.server.uri.NeededUriGrants; 415 import com.android.server.uri.UriGrantsManagerInternal; 416 import com.android.server.utils.PriorityDump; 417 import com.android.server.utils.TimingsTraceAndSlog; 418 import com.android.server.vr.VrManagerInternal; 419 import com.android.server.wm.ActivityMetricsLaunchObserver; 420 import com.android.server.wm.ActivityServiceConnectionsHolder; 421 import com.android.server.wm.ActivityTaskManagerInternal; 422 import com.android.server.wm.ActivityTaskManagerService; 423 import com.android.server.wm.WindowManagerInternal; 424 import com.android.server.wm.WindowManagerService; 425 import com.android.server.wm.WindowProcessController; 426 427 import dalvik.annotation.optimization.NeverCompile; 428 import dalvik.system.VMRuntime; 429 430 import libcore.util.EmptyArray; 431 432 import java.io.File; 433 import java.io.FileDescriptor; 434 import java.io.FileNotFoundException; 435 import java.io.FileOutputStream; 436 import java.io.IOException; 437 import java.io.InputStreamReader; 438 import java.io.PrintWriter; 439 import java.io.StringWriter; 440 import java.nio.charset.StandardCharsets; 441 import java.text.SimpleDateFormat; 442 import java.util.ArrayList; 443 import java.util.Arrays; 444 import java.util.Collections; 445 import java.util.Comparator; 446 import java.util.Date; 447 import java.util.HashMap; 448 import java.util.HashSet; 449 import java.util.Iterator; 450 import java.util.LinkedList; 451 import java.util.List; 452 import java.util.Locale; 453 import java.util.Map; 454 import java.util.Objects; 455 import java.util.Set; 456 import java.util.UUID; 457 import java.util.concurrent.CopyOnWriteArrayList; 458 import java.util.concurrent.Executor; 459 import java.util.concurrent.atomic.AtomicInteger; 460 461 public class ActivityManagerService extends IActivityManager.Stub 462 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock { 463 464 private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED = 465 "persist.sys.device_provisioned"; 466 467 static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM; 468 static final String TAG_BACKUP = TAG + POSTFIX_BACKUP; 469 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 470 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 471 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION; 472 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; 473 static final String TAG_LRU = TAG + POSTFIX_LRU; 474 static final String TAG_MU = TAG + POSTFIX_MU; 475 static final String TAG_NETWORK = TAG + POSTFIX_NETWORK; 476 static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ; 477 private static final String TAG_POWER = TAG + POSTFIX_POWER; 478 static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES; 479 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 480 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 481 static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS; 482 483 // Mock "pretend we're idle now" broadcast action to the job scheduler; declared 484 // here so that while the job scheduler can depend on AMS, the other way around 485 // need not be the case. 486 public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE"; 487 488 private static final String INTENT_BUGREPORT_REQUESTED = 489 "com.android.internal.intent.action.BUGREPORT_REQUESTED"; 490 private static final String SHELL_APP_PACKAGE = "com.android.shell"; 491 492 // The flags that are set for all calls we make to the package manager. 493 public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 494 495 static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed"; 496 497 public static final String ANR_TRACE_DIR = "/data/anr"; 498 499 // Maximum number of receivers an app can register. 500 private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000; 501 502 // How long we wait for a launched process to attach to the activity manager 503 // before we decide it's never going to come up for real. 504 static final int PROC_START_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 505 // How long we wait to kill an application zygote, after the last process using 506 // it has gone away. 507 static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000; 508 509 // How long we wait for a launched process to attach to the activity manager 510 // before we decide it's never going to come up for real, when the process was 511 // started with a wrapper for instrumentation (such as Valgrind) because it 512 // could take much longer than usual. 513 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 514 515 // How long we allow a receiver to run before giving up on it. 516 static final int BROADCAST_FG_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 517 static final int BROADCAST_BG_TIMEOUT = 60 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 518 519 public static final int MY_PID = myPid(); 520 521 static final String[] EMPTY_STRING_ARRAY = new String[0]; 522 523 // How many bytes to write into the dropbox log before truncating 524 static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024; 525 // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count 526 // as one line, but close enough for now. 527 static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100; 528 529 // Necessary ApplicationInfo flags to mark an app as persistent 530 static final int PERSISTENT_MASK = 531 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT; 532 533 // Intent sent when remote bugreport collection has been completed 534 private static final String INTENT_REMOTE_BUGREPORT_FINISHED = 535 "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED"; 536 537 // If set, we will push process association information in to procstats. 538 static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true; 539 540 // The minimum memory growth threshold (in KB) for low RAM devices. 541 private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB 542 543 /** 544 * The number of binder proxies we need to have before we start warning and 545 * dumping debug info. 546 */ 547 private static final int BINDER_PROXY_HIGH_WATERMARK = 6000; 548 549 /** 550 * Low watermark that needs to be met before we consider dumping info again, 551 * after already hitting the high watermark. 552 */ 553 private static final int BINDER_PROXY_LOW_WATERMARK = 5500; 554 555 // Max character limit for a notification title. If the notification title is larger than this 556 // the notification will not be legible to the user. 557 private static final int MAX_BUGREPORT_TITLE_SIZE = 100; 558 private static final int MAX_BUGREPORT_DESCRIPTION_SIZE = 150; 559 560 private static final int NATIVE_DUMP_TIMEOUT_MS = 561 2000 * Build.HW_TIMEOUT_MULTIPLIER; // 2 seconds; 562 private static final int JAVA_DUMP_MINIMUM_SIZE = 100; // 100 bytes. 563 564 OomAdjuster mOomAdjuster; 565 566 static final String EXTRA_TITLE = "android.intent.extra.TITLE"; 567 static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION"; 568 static final String EXTRA_BUGREPORT_TYPE = "android.intent.extra.BUGREPORT_TYPE"; 569 static final String EXTRA_BUGREPORT_NONCE = "android.intent.extra.BUGREPORT_NONCE"; 570 571 /** 572 * It is now required for apps to explicitly set either 573 * {@link android.content.Context#RECEIVER_EXPORTED} or 574 * {@link android.content.Context#RECEIVER_NOT_EXPORTED} when registering a receiver for an 575 * unprotected broadcast in code. 576 */ 577 @ChangeId 578 @Disabled 579 private static final long DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED = 161145287L; 580 581 /** 582 * The maximum number of bytes that {@link #setProcessStateSummary} accepts. 583 * 584 * @see {@link android.app.ActivityManager#setProcessStateSummary(byte[])} 585 */ 586 static final int MAX_STATE_DATA_SIZE = 128; 587 588 /** All system services */ 589 SystemServiceManager mSystemServiceManager; 590 591 private Installer mInstaller; 592 593 final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter(); 594 595 @CompositeRWLock({"this", "mProcLock"}) 596 final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>(); 597 598 public final IntentFirewall mIntentFirewall; 599 600 public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler(); 601 602 /** 603 * The global lock for AMS, it's de-facto the ActivityManagerService object as of now. 604 */ 605 final ActivityManagerGlobalLock mGlobalLock = ActivityManagerService.this; 606 607 /** 608 * Whether or not to enable the {@link #mProcLock}. If {@code false}, the {@link #mProcLock} 609 * will be equivalent to the {@link #mGlobalLock}. 610 */ 611 private static final boolean ENABLE_PROC_LOCK = true; 612 613 /** 614 * The lock for process management. 615 * 616 * <p> 617 * This lock is widely used in conjunction with the {@link #mGlobalLock} at present, 618 * where it'll require any of the locks to read from a data class, and both of the locks 619 * to write into that data class. 620 * 621 * For the naming convention of function suffixes: 622 * <ul> 623 * <li>-LOSP: Locked with any Of global am Service or Process lock</li> 624 * <li>-LSP: Locked with both of global am Service and Process lock</li> 625 * <li>-Locked: Locked with global am service lock alone</li> 626 * <li>-LPr: Locked with Process lock alone</li> 627 * </ul> 628 * For the simplicity, the getters/setters of the fields in data classes usually don't end with 629 * the above suffixes even if they're guarded by the locks here. 630 * </p> 631 * 632 * <p> 633 * In terms of locking order, it should be right below to the {@link #mGlobalLock}, 634 * and above everything else which used to be underneath the {@link #mGlobalLock}. 635 * As of today, the core components(services/providers/broadcasts) are still guarded by 636 * the {@link #mGlobalLock} alone, so be cautious, avoid from acquiring the {@link #mGlobalLock} 637 * while holding this lock. 638 * </p> 639 * 640 */ 641 final ActivityManagerGlobalLock mProcLock = ENABLE_PROC_LOCK 642 ? new ActivityManagerProcLock() : mGlobalLock; 643 644 // Whether we should use SCHED_FIFO for UI and RenderThreads. 645 final boolean mUseFifoUiScheduling; 646 647 // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED. 648 // For simplicity, since we statically declare the size of the array of BroadcastQueues, 649 // we still create this new offload queue, but never ever put anything on it. 650 final boolean mEnableOffloadQueue; 651 652 final BroadcastQueue mFgBroadcastQueue; 653 final BroadcastQueue mBgBroadcastQueue; 654 final BroadcastQueue mBgOffloadBroadcastQueue; 655 final BroadcastQueue mFgOffloadBroadcastQueue; 656 // Convenient for easy iteration over the queues. Foreground is first 657 // so that dispatch of foreground broadcasts gets precedence. 658 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[4]; 659 660 @GuardedBy("this") 661 BroadcastStats mLastBroadcastStats; 662 663 @GuardedBy("this") 664 BroadcastStats mCurBroadcastStats; 665 666 TraceErrorLogger mTraceErrorLogger; 667 broadcastQueueForIntent(Intent intent)668 BroadcastQueue broadcastQueueForIntent(Intent intent) { 669 if (isOnFgOffloadQueue(intent.getFlags())) { 670 if (DEBUG_BROADCAST_BACKGROUND) { 671 Slog.i(TAG_BROADCAST, 672 "Broadcast intent " + intent + " on foreground offload queue"); 673 } 674 return mFgOffloadBroadcastQueue; 675 } 676 677 if (isOnBgOffloadQueue(intent.getFlags())) { 678 if (DEBUG_BROADCAST_BACKGROUND) { 679 Slog.i(TAG_BROADCAST, 680 "Broadcast intent " + intent + " on background offload queue"); 681 } 682 return mBgOffloadBroadcastQueue; 683 } 684 685 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 686 if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST, 687 "Broadcast intent " + intent + " on " 688 + (isFg ? "foreground" : "background") + " queue"); 689 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 690 } 691 692 private volatile int mDeviceOwnerUid = INVALID_UID; 693 694 /** 695 * Map userId to its companion app uids. 696 */ 697 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>(); 698 699 /** 700 * The profile owner UIDs. 701 */ 702 private ArraySet<Integer> mProfileOwnerUids = null; 703 704 final UserController mUserController; 705 @VisibleForTesting 706 public final PendingIntentController mPendingIntentController; 707 708 final AppErrors mAppErrors; 709 final PackageWatchdog mPackageWatchdog; 710 711 /** 712 * Uids of apps with current active camera sessions. Access synchronized on 713 * the IntArray instance itself, and no other locks must be acquired while that 714 * one is held. 715 */ 716 @GuardedBy("mActiveCameraUids") 717 final IntArray mActiveCameraUids = new IntArray(4); 718 719 /** 720 * Helper class which strips out priority and proto arguments then calls the dump function with 721 * the appropriate arguments. If priority arguments are omitted, function calls the legacy 722 * dump command. 723 * If priority arguments are omitted all sections are dumped, otherwise sections are dumped 724 * according to their priority. 725 */ 726 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() { 727 @Override 728 public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args, 729 boolean asProto) { 730 if (asProto) return; 731 doDump(fd, pw, new String[]{"activities"}, asProto); 732 doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto); 733 } 734 735 @Override 736 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 737 doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto); 738 } 739 740 @Override 741 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 742 doDump(fd, pw, args, asProto); 743 } 744 }; 745 746 private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster( 747 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY); 748 boostPriorityForLockedSection()749 static void boostPriorityForLockedSection() { 750 sThreadPriorityBooster.boost(); 751 } 752 resetPriorityAfterLockedSection()753 static void resetPriorityAfterLockedSection() { 754 sThreadPriorityBooster.reset(); 755 } 756 757 private static ThreadPriorityBooster sProcThreadPriorityBooster = new ThreadPriorityBooster( 758 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_PROC); 759 boostPriorityForProcLockedSection()760 static void boostPriorityForProcLockedSection() { 761 if (ENABLE_PROC_LOCK) { 762 sProcThreadPriorityBooster.boost(); 763 } else { 764 sThreadPriorityBooster.boost(); 765 } 766 } 767 resetPriorityAfterProcLockedSection()768 static void resetPriorityAfterProcLockedSection() { 769 if (ENABLE_PROC_LOCK) { 770 sProcThreadPriorityBooster.reset(); 771 } else { 772 sThreadPriorityBooster.reset(); 773 } 774 } 775 776 /** 777 * Process management. 778 */ 779 final ProcessList mProcessList; 780 781 /** 782 * The list of phantom processes. 783 * @see PhantomProcessRecord 784 */ 785 final PhantomProcessList mPhantomProcessList; 786 787 /** 788 * Tracking long-term execution of processes to look for abuse and other 789 * bad app behavior. 790 */ 791 final ProcessStatsService mProcessStats; 792 793 /** 794 * Non-persistent appId allowlist for background restrictions 795 */ 796 @CompositeRWLock({"this", "mProcLock"}) 797 private int[] mBackgroundAppIdAllowlist = new int[] { 798 BLUETOOTH_UID 799 }; 800 801 /** 802 * Broadcast actions that will always be deliverable to unlaunched/background apps 803 */ 804 @GuardedBy("this") 805 private ArraySet<String> mBackgroundLaunchBroadcasts; 806 807 /** 808 * When an app has restrictions on the other apps that can have associations with it, 809 * it appears here with a set of the allowed apps and also track debuggability of the app. 810 */ 811 @GuardedBy("this") 812 private ArrayMap<String, PackageAssociationInfo> mAllowedAssociations; 813 814 @GuardedBy("this") 815 final ComponentAliasResolver mComponentAliasResolver; 816 817 /** 818 * Tracks association information for a particular package along with debuggability. 819 * <p> Associations for a package A are allowed to package B if B is part of the 820 * allowed associations for A or if A is debuggable. 821 */ 822 private final class PackageAssociationInfo { 823 private final String mSourcePackage; 824 private final ArraySet<String> mAllowedPackageAssociations; 825 private boolean mIsDebuggable; 826 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)827 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, 828 boolean isDebuggable) { 829 mSourcePackage = sourcePackage; 830 mAllowedPackageAssociations = allowedPackages; 831 mIsDebuggable = isDebuggable; 832 } 833 834 /** 835 * Returns true if {@code mSourcePackage} is allowed association with 836 * {@code targetPackage}. 837 */ isPackageAssociationAllowed(String targetPackage)838 boolean isPackageAssociationAllowed(String targetPackage) { 839 return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage); 840 } 841 isDebuggable()842 boolean isDebuggable() { 843 return mIsDebuggable; 844 } 845 setDebuggable(boolean isDebuggable)846 void setDebuggable(boolean isDebuggable) { 847 mIsDebuggable = isDebuggable; 848 } 849 getAllowedPackageAssociations()850 ArraySet<String> getAllowedPackageAssociations() { 851 return mAllowedPackageAssociations; 852 } 853 } 854 855 /** 856 * These are the currently running processes for which we have a ProcessInfo. 857 * Note: needs to be static since the permission checking call chain is static. This 858 * all probably should be refactored into a separate permission checking object. 859 */ 860 @GuardedBy("sActiveProcessInfoSelfLocked") 861 static final SparseArray<ProcessInfo> sActiveProcessInfoSelfLocked = new SparseArray<>(); 862 863 /** 864 * All of the processes we currently have running organized by pid. 865 * The keys are the pid running the application. 866 * 867 * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock! 868 */ 869 final PidMap mPidsSelfLocked = new PidMap(); 870 static final class PidMap { 871 private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>(); 872 get(int pid)873 ProcessRecord get(int pid) { 874 return mPidMap.get(pid); 875 } 876 size()877 int size() { 878 return mPidMap.size(); 879 } 880 valueAt(int index)881 ProcessRecord valueAt(int index) { 882 return mPidMap.valueAt(index); 883 } 884 keyAt(int index)885 int keyAt(int index) { 886 return mPidMap.keyAt(index); 887 } 888 indexOfKey(int key)889 int indexOfKey(int key) { 890 return mPidMap.indexOfKey(key); 891 } 892 doAddInternal(int pid, ProcessRecord app)893 void doAddInternal(int pid, ProcessRecord app) { 894 mPidMap.put(pid, app); 895 } 896 doRemoveInternal(int pid, ProcessRecord app)897 boolean doRemoveInternal(int pid, ProcessRecord app) { 898 final ProcessRecord existingApp = mPidMap.get(pid); 899 if (existingApp != null && existingApp.getStartSeq() == app.getStartSeq()) { 900 mPidMap.remove(pid); 901 return true; 902 } 903 return false; 904 } 905 doRemoveIfNoThreadInternal(int pid, ProcessRecord app)906 boolean doRemoveIfNoThreadInternal(int pid, ProcessRecord app) { 907 if (app == null || app.getThread() != null) { 908 return false; 909 } 910 return doRemoveInternal(pid, app); 911 } 912 } 913 914 private final PendingStartActivityUids mPendingStartActivityUids; 915 916 /** 917 * Puts the process record in the map. 918 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 919 * method. 920 */ 921 @GuardedBy("this") addPidLocked(ProcessRecord app)922 void addPidLocked(ProcessRecord app) { 923 final int pid = app.getPid(); 924 synchronized (mPidsSelfLocked) { 925 mPidsSelfLocked.doAddInternal(pid, app); 926 } 927 synchronized (sActiveProcessInfoSelfLocked) { 928 if (app.processInfo != null) { 929 sActiveProcessInfoSelfLocked.put(pid, app.processInfo); 930 } else { 931 sActiveProcessInfoSelfLocked.remove(pid); 932 } 933 } 934 mAtmInternal.onProcessMapped(pid, app.getWindowProcessController()); 935 } 936 937 /** 938 * Removes the process record from the map. 939 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 940 * method. 941 */ 942 @GuardedBy("this") removePidLocked(int pid, ProcessRecord app)943 void removePidLocked(int pid, ProcessRecord app) { 944 final boolean removed; 945 synchronized (mPidsSelfLocked) { 946 removed = mPidsSelfLocked.doRemoveInternal(pid, app); 947 } 948 if (removed) { 949 synchronized (sActiveProcessInfoSelfLocked) { 950 sActiveProcessInfoSelfLocked.remove(pid); 951 } 952 mAtmInternal.onProcessUnMapped(pid); 953 } 954 } 955 956 /** 957 * Removes the process record from the map if it doesn't have a thread. 958 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 959 * method. 960 */ 961 @GuardedBy("this") removePidIfNoThreadLocked(ProcessRecord app)962 private boolean removePidIfNoThreadLocked(ProcessRecord app) { 963 final boolean removed; 964 final int pid = app.getPid(); 965 synchronized (mPidsSelfLocked) { 966 removed = mPidsSelfLocked.doRemoveIfNoThreadInternal(pid, app); 967 } 968 if (removed) { 969 synchronized (sActiveProcessInfoSelfLocked) { 970 sActiveProcessInfoSelfLocked.remove(pid); 971 } 972 mAtmInternal.onProcessUnMapped(pid); 973 } 974 return removed; 975 } 976 977 /** 978 * All of the processes that have been forced to be important. The key 979 * is the pid of the caller who requested it (we hold a death 980 * link on it). 981 */ 982 abstract class ImportanceToken implements IBinder.DeathRecipient { 983 final int pid; 984 final IBinder token; 985 final String reason; 986 ImportanceToken(int _pid, IBinder _token, String _reason)987 ImportanceToken(int _pid, IBinder _token, String _reason) { 988 pid = _pid; 989 token = _token; 990 reason = _reason; 991 } 992 993 @Override toString()994 public String toString() { 995 return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this)) 996 + " " + reason + " " + pid + " " + token + " }"; 997 } 998 dumpDebug(ProtoOutputStream proto, long fieldId)999 void dumpDebug(ProtoOutputStream proto, long fieldId) { 1000 final long pToken = proto.start(fieldId); 1001 proto.write(ImportanceTokenProto.PID, pid); 1002 if (token != null) { 1003 proto.write(ImportanceTokenProto.TOKEN, token.toString()); 1004 } 1005 proto.write(ImportanceTokenProto.REASON, reason); 1006 proto.end(pToken); 1007 } 1008 } 1009 @GuardedBy("this") 1010 final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>(); 1011 1012 /** 1013 * List of records for processes that someone had tried to start before the 1014 * system was ready. We don't start them at that point, but ensure they 1015 * are started by the time booting is complete. 1016 */ 1017 @GuardedBy("this") 1018 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 1019 1020 /** 1021 * List of persistent applications that are in the process 1022 * of being started. 1023 */ 1024 @GuardedBy("this") 1025 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 1026 1027 private final ActivityMetricsLaunchObserver mActivityLaunchObserver = 1028 new ActivityMetricsLaunchObserver() { 1029 @Override 1030 public void onActivityLaunched(long id, ComponentName name, int temperature) { 1031 mAppProfiler.onActivityLaunched(); 1032 } 1033 }; 1034 1035 private volatile boolean mBinderTransactionTrackingEnabled = false; 1036 1037 /** 1038 * Fingerprints (hashCode()) of stack traces that we've 1039 * already logged DropBox entries for. Guarded by itself. If 1040 * something (rogue user app) forces this over 1041 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 1042 */ 1043 @GuardedBy("mAlreadyLoggedViolatedStacks") 1044 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 1045 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 1046 1047 /** 1048 * Keeps track of all IIntentReceivers that have been registered for broadcasts. 1049 * Hash keys are the receiver IBinder, hash value is a ReceiverList. 1050 */ 1051 @GuardedBy("this") 1052 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>(); 1053 1054 /** 1055 * Resolver for broadcast intents to registered receivers. 1056 * Holds BroadcastFilter (subclass of IntentFilter). 1057 */ 1058 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 1059 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 1060 @Override 1061 protected boolean allowFilterResult( 1062 BroadcastFilter filter, List<BroadcastFilter> dest) { 1063 IBinder target = filter.receiverList.receiver.asBinder(); 1064 for (int i = dest.size() - 1; i >= 0; i--) { 1065 if (dest.get(i).receiverList.receiver.asBinder() == target) { 1066 return false; 1067 } 1068 } 1069 return true; 1070 } 1071 1072 @Override 1073 protected BroadcastFilter newResult(@NonNull Computer computer, BroadcastFilter filter, 1074 int match, int userId, long customFlags) { 1075 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 1076 || userId == filter.owningUserId) { 1077 return super.newResult(computer, filter, match, userId, customFlags); 1078 } 1079 return null; 1080 } 1081 1082 @Override 1083 protected IntentFilter getIntentFilter(@NonNull BroadcastFilter input) { 1084 return input; 1085 } 1086 1087 @Override 1088 protected BroadcastFilter[] newArray(int size) { 1089 return new BroadcastFilter[size]; 1090 } 1091 1092 @Override 1093 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 1094 return packageName.equals(filter.packageName); 1095 } 1096 }; 1097 1098 /** 1099 * State of all active sticky broadcasts per user. Keys are the action of the 1100 * sticky Intent, values are an ArrayList of all broadcasted intents with 1101 * that action (which should usually be one). The SparseArray is keyed 1102 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 1103 * for stickies that are sent to all users. 1104 */ 1105 @GuardedBy("this") 1106 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts = 1107 new SparseArray<ArrayMap<String, ArrayList<Intent>>>(); 1108 1109 final ActiveServices mServices; 1110 1111 final static class Association { 1112 final int mSourceUid; 1113 final String mSourceProcess; 1114 final int mTargetUid; 1115 final ComponentName mTargetComponent; 1116 final String mTargetProcess; 1117 1118 int mCount; 1119 long mTime; 1120 1121 int mNesting; 1122 long mStartTime; 1123 1124 // states of the source process when the bind occurred. 1125 int mLastState = ActivityManager.MAX_PROCESS_STATE + 1; 1126 long mLastStateUptime; 1127 long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE 1128 - ActivityManager.MIN_PROCESS_STATE+1]; 1129 Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1130 Association(int sourceUid, String sourceProcess, int targetUid, 1131 ComponentName targetComponent, String targetProcess) { 1132 mSourceUid = sourceUid; 1133 mSourceProcess = sourceProcess; 1134 mTargetUid = targetUid; 1135 mTargetComponent = targetComponent; 1136 mTargetProcess = targetProcess; 1137 } 1138 } 1139 1140 /** 1141 * When service association tracking is enabled, this is all of the associations we 1142 * have seen. Mapping is target uid -> target component -> source uid -> source process name 1143 * -> association data. 1144 */ 1145 @GuardedBy("this") 1146 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>> 1147 mAssociations = new SparseArray<>(); 1148 boolean mTrackingAssociations; 1149 1150 /** 1151 * Backup/restore process management 1152 */ 1153 @GuardedBy("this") 1154 final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>(); 1155 1156 final ContentProviderHelper mCpHelper; 1157 1158 CoreSettingsObserver mCoreSettingsObserver; 1159 1160 /** 1161 * All information we have collected about the runtime performance of 1162 * any user id that can impact battery performance. 1163 */ 1164 final BatteryStatsService mBatteryStatsService; 1165 1166 /** 1167 * Information about component usage 1168 */ 1169 volatile UsageStatsManagerInternal mUsageStatsService; 1170 1171 /** 1172 * Access to DeviceIdleController service. 1173 */ 1174 DeviceIdleInternal mLocalDeviceIdleController; 1175 1176 /** 1177 * Power-save allowlisted app-ids (not including except-idle-allowlisted ones). 1178 */ 1179 @CompositeRWLock({"this", "mProcLock"}) 1180 int[] mDeviceIdleAllowlist = new int[0]; 1181 1182 /** 1183 * Power-save allowlisted app-ids (including except-idle-allowlisted ones). 1184 */ 1185 @CompositeRWLock({"this", "mProcLock"}) 1186 int[] mDeviceIdleExceptIdleAllowlist = new int[0]; 1187 1188 /** 1189 * Set of app ids that are temporarily allowed to escape bg check due to high-pri message 1190 */ 1191 @CompositeRWLock({"this", "mProcLock"}) 1192 int[] mDeviceIdleTempAllowlist = new int[0]; 1193 1194 static final class PendingTempAllowlist { 1195 final int targetUid; 1196 final long duration; 1197 final String tag; 1198 final int type; 1199 final @ReasonCode int reasonCode; 1200 final int callingUid; 1201 PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, int type, int callingUid)1202 PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, 1203 int type, int callingUid) { 1204 this.targetUid = targetUid; 1205 this.duration = duration; 1206 this.tag = tag; 1207 this.type = type; 1208 this.reasonCode = reasonCode; 1209 this.callingUid = callingUid; 1210 } 1211 dumpDebug(ProtoOutputStream proto, long fieldId)1212 void dumpDebug(ProtoOutputStream proto, long fieldId) { 1213 final long token = proto.start(fieldId); 1214 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID, 1215 targetUid); 1216 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS, 1217 duration); 1218 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag); 1219 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TYPE, type); 1220 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.REASON_CODE, 1221 reasonCode); 1222 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.CALLING_UID, 1223 callingUid); 1224 proto.end(token); 1225 } 1226 } 1227 1228 @CompositeRWLock({"this", "mProcLock"}) 1229 final PendingTempAllowlists mPendingTempAllowlist = new PendingTempAllowlists(this); 1230 1231 public static final class FgsTempAllowListItem { 1232 final long mDuration; 1233 final @PowerExemptionManager.ReasonCode int mReasonCode; 1234 final String mReason; 1235 final int mCallingUid; 1236 FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, String reason, int callingUid)1237 FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, 1238 String reason, int callingUid) { 1239 mDuration = duration; 1240 mReasonCode = reasonCode; 1241 mReason = reason; 1242 mCallingUid = callingUid; 1243 } 1244 dump(PrintWriter pw)1245 void dump(PrintWriter pw) { 1246 pw.print(" duration=" + mDuration + 1247 " callingUid=" + UserHandle.formatUid(mCallingUid) + 1248 " reasonCode=" + PowerExemptionManager.reasonCodeToString(mReasonCode) + 1249 " reason=" + mReason); 1250 } 1251 } 1252 1253 /** 1254 * The temp-allowlist that is allowed to start FGS from background. 1255 */ 1256 @CompositeRWLock({"this", "mProcLock"}) 1257 final FgsTempAllowList<FgsTempAllowListItem> mFgsStartTempAllowList = 1258 new FgsTempAllowList(); 1259 1260 static final FgsTempAllowListItem FAKE_TEMP_ALLOW_LIST_ITEM = new FgsTempAllowListItem( 1261 Long.MAX_VALUE, REASON_SYSTEM_ALLOW_LISTED, "", INVALID_UID); 1262 1263 /* 1264 * List of uids that are allowed to have while-in-use permission when FGS is started from 1265 * background. 1266 */ 1267 private final FgsTempAllowList<String> mFgsWhileInUseTempAllowList = 1268 new FgsTempAllowList(); 1269 1270 /** 1271 * Information about and control over application operations 1272 */ 1273 final AppOpsService mAppOpsService; 1274 private AppOpsManager mAppOpsManager; 1275 1276 /** 1277 * List of initialization arguments to pass to all processes when binding applications to them. 1278 * For example, references to the commonly used services. 1279 */ 1280 ArrayMap<String, IBinder> mAppBindArgs; 1281 ArrayMap<String, IBinder> mIsolatedAppBindArgs; 1282 1283 volatile boolean mProcessesReady = false; 1284 volatile boolean mSystemReady = false; 1285 volatile boolean mOnBattery = false; 1286 final int mFactoryTest; 1287 volatile boolean mBooting = false; 1288 1289 @GuardedBy("this") boolean mCallFinishBooting = false; 1290 @GuardedBy("this") boolean mBootAnimationComplete = false; 1291 1292 final Context mContext; 1293 1294 /** 1295 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can 1296 * change at runtime. Use mContext for non-UI purposes. 1297 */ 1298 final Context mUiContext; 1299 1300 /** 1301 * Last time (in uptime) at which we checked for power usage. 1302 */ 1303 @GuardedBy("mProcLock") 1304 long mLastPowerCheckUptime; 1305 1306 /** 1307 * For some direct access we need to power manager. 1308 */ 1309 PowerManagerInternal mLocalPowerManager; 1310 1311 /** 1312 * State of external calls telling us if the device is awake or asleep. 1313 */ 1314 AtomicInteger mWakefulness = new AtomicInteger(PowerManagerInternal.WAKEFULNESS_AWAKE); 1315 1316 /** 1317 * The uptime of the last time we performed idle maintenance. 1318 */ 1319 @GuardedBy("mProcLock") 1320 long mLastIdleTime = SystemClock.uptimeMillis(); 1321 1322 /** 1323 * For reporting to battery stats the current top application. 1324 * 1325 * <p>It has its own lock to avoid from the need of double locking if using the global 1326 * ActivityManagerService lock and proc lock to guard it.</p> 1327 */ 1328 @GuardedBy("mCurResumedAppLock") 1329 private String mCurResumedPackage = null; 1330 1331 @GuardedBy("mCurResumedAppLock") 1332 private int mCurResumedUid = -1; 1333 1334 /** 1335 * Dedicated lock for {@link #mCurResumedPackage} and {@link #mCurResumedUid}. 1336 */ 1337 private final Object mCurResumedAppLock = new Object(); 1338 1339 /** 1340 * For reporting to battery stats the apps currently running foreground 1341 * service. The ProcessMap is package/uid tuples; each of these contain 1342 * an array of the currently foreground processes. 1343 */ 1344 @GuardedBy("this") 1345 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1346 = new ProcessMap<ArrayList<ProcessRecord>>(); 1347 1348 /** 1349 * The list of foreground service state change listeners. 1350 */ 1351 @GuardedBy("this") 1352 final ArrayList<ForegroundServiceStateListener> mForegroundServiceStateListeners = 1353 new ArrayList<>(); 1354 1355 /** 1356 * The list of broadcast event listeners. 1357 */ 1358 final CopyOnWriteArrayList<BroadcastEventListener> mBroadcastEventListeners = 1359 new CopyOnWriteArrayList<>(); 1360 1361 /** 1362 * The list of bind service event listeners. 1363 */ 1364 final CopyOnWriteArrayList<BindServiceEventListener> mBindServiceEventListeners = 1365 new CopyOnWriteArrayList<>(); 1366 1367 /** 1368 * Set if the systemServer made a call to enterSafeMode. 1369 */ 1370 @GuardedBy("this") 1371 boolean mSafeMode; 1372 1373 @GuardedBy("this") 1374 private String mDebugApp = null; 1375 1376 @GuardedBy("this") 1377 private boolean mWaitForDebugger = false; 1378 1379 @GuardedBy("this") 1380 private boolean mDebugTransient = false; 1381 1382 @GuardedBy("this") 1383 private String mOrigDebugApp = null; 1384 1385 @GuardedBy("this") 1386 private boolean mOrigWaitForDebugger = false; 1387 1388 @GuardedBy("this") 1389 boolean mAlwaysFinishActivities = false; 1390 1391 @GuardedBy("mProcLock") 1392 private String mTrackAllocationApp = null; 1393 1394 @GuardedBy("this") 1395 String mNativeDebuggingApp = null; 1396 1397 final Injector mInjector; 1398 1399 static final class ProcessChangeItem { 1400 static final int CHANGE_ACTIVITIES = 1<<0; 1401 static final int CHANGE_FOREGROUND_SERVICES = 1<<1; 1402 static final int CHANGE_CAPABILITY = 1<<2; 1403 int changes; 1404 int uid; 1405 int pid; 1406 int processState; 1407 int capability; 1408 boolean foregroundActivities; 1409 int foregroundServiceTypes; 1410 } 1411 1412 @GuardedBy("mOomAdjObserverLock") 1413 OomAdjObserver mCurOomAdjObserver; 1414 1415 @GuardedBy("mOomAdjObserverLock") 1416 int mCurOomAdjUid; 1417 1418 /** 1419 * Dedicated lock for {@link #mCurOomAdjObserver} and {@link #mCurOomAdjUid}. 1420 */ 1421 final Object mOomAdjObserverLock = new Object(); 1422 1423 interface OomAdjObserver { onOomAdjMessage(String msg)1424 void onOomAdjMessage(String msg); 1425 } 1426 1427 final AnrHelper mAnrHelper = new AnrHelper(this); 1428 1429 /** Set to true after the system has finished booting. */ 1430 volatile boolean mBooted = false; 1431 1432 /** 1433 * Current boot phase. 1434 */ 1435 int mBootPhase; 1436 1437 @VisibleForTesting 1438 public WindowManagerService mWindowManager; 1439 WindowManagerInternal mWmInternal; 1440 @VisibleForTesting 1441 public ActivityTaskManagerService mActivityTaskManager; 1442 @VisibleForTesting 1443 public ActivityTaskManagerInternal mAtmInternal; 1444 UriGrantsManagerInternal mUgmInternal; 1445 @VisibleForTesting 1446 public final ActivityManagerInternal mInternal; 1447 final ActivityThread mSystemThread; 1448 1449 final UidObserverController mUidObserverController; 1450 private volatile IUidObserver mNetworkPolicyUidObserver; 1451 1452 @GuardedBy("mUidNetworkBlockedReasons") 1453 private final SparseIntArray mUidNetworkBlockedReasons = new SparseIntArray(); 1454 1455 final AppRestrictionController mAppRestrictionController; 1456 1457 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1458 final ProcessRecord mApp; 1459 final int mPid; 1460 final IApplicationThread mAppThread; 1461 AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1462 AppDeathRecipient(ProcessRecord app, int pid, 1463 IApplicationThread thread) { 1464 if (DEBUG_ALL) Slog.v( 1465 TAG, "New death recipient " + this 1466 + " for thread " + thread.asBinder()); 1467 mApp = app; 1468 mPid = pid; 1469 mAppThread = thread; 1470 } 1471 1472 @Override binderDied()1473 public void binderDied() { 1474 if (DEBUG_ALL) Slog.v( 1475 TAG, "Death received in " + this 1476 + " for thread " + mAppThread.asBinder()); 1477 synchronized(ActivityManagerService.this) { 1478 appDiedLocked(mApp, mPid, mAppThread, true, null); 1479 } 1480 } 1481 } 1482 1483 static final int SHOW_ERROR_UI_MSG = 1; 1484 static final int SHOW_NOT_RESPONDING_UI_MSG = 2; 1485 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1486 static final int WAIT_FOR_DEBUGGER_UI_MSG = 6; 1487 static final int SERVICE_TIMEOUT_MSG = 12; 1488 static final int UPDATE_TIME_ZONE = 13; 1489 static final int PROC_START_TIMEOUT_MSG = 20; 1490 static final int KILL_APPLICATION_MSG = 22; 1491 static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26; 1492 static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27; 1493 static final int CLEAR_DNS_CACHE_MSG = 28; 1494 static final int UPDATE_HTTP_PROXY_MSG = 29; 1495 static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31; 1496 static final int DISPATCH_PROCESS_DIED_UI_MSG = 32; 1497 static final int REPORT_MEM_USAGE_MSG = 33; 1498 static final int UPDATE_TIME_PREFERENCE_MSG = 41; 1499 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49; 1500 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50; 1501 static final int ABORT_DUMPHEAP_MSG = 51; 1502 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56; 1503 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57; 1504 static final int IDLE_UIDS_MSG = 58; 1505 static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63; 1506 static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66; 1507 static final int SERVICE_FOREGROUND_TIMEOUT_ANR_MSG = 67; 1508 static final int PUSH_TEMP_ALLOWLIST_UI_MSG = 68; 1509 static final int SERVICE_FOREGROUND_CRASH_MSG = 69; 1510 static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70; 1511 static final int KILL_APP_ZYGOTE_MSG = 71; 1512 static final int BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG = 72; 1513 static final int WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG = 73; 1514 static final int DISPATCH_SENDING_BROADCAST_EVENT = 74; 1515 static final int DISPATCH_BINDING_SERVICE_EVENT = 75; 1516 1517 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1518 1519 /** 1520 * Flag whether the current user is a "monkey", i.e. whether 1521 * the UI is driven by a UI automation tool. 1522 */ 1523 private volatile boolean mUserIsMonkey; 1524 1525 @VisibleForTesting 1526 public final ServiceThread mHandlerThread; 1527 final MainHandler mHandler; 1528 final Handler mUiHandler; 1529 final ServiceThread mProcStartHandlerThread; 1530 final ProcStartHandler mProcStartHandler; 1531 1532 ActivityManagerConstants mConstants; 1533 1534 // Encapsulates the global setting "hidden_api_blacklist_exemptions" 1535 final HiddenApiSettings mHiddenApiBlacklist; 1536 1537 final SdkSandboxSettings mSdkSandboxSettings; 1538 1539 private final PlatformCompat mPlatformCompat; 1540 1541 PackageManagerInternal mPackageManagerInt; 1542 PermissionManagerServiceInternal mPermissionManagerInt; 1543 private TestUtilityService mTestUtilityService; 1544 1545 /** 1546 * Whether to force background check on all apps (for battery saver) or not. 1547 */ 1548 @CompositeRWLock({"this", "mProcLock"}) 1549 private boolean mForceBackgroundCheck; 1550 1551 private static String sTheRealBuildSerial = Build.UNKNOWN; 1552 1553 @GuardedBy("mProcLock") 1554 private ParcelFileDescriptor[] mLifeMonitorFds; 1555 1556 static final HostingRecord sNullHostingRecord = 1557 new HostingRecord(HostingRecord.HOSTING_TYPE_EMPTY); 1558 /** 1559 * Used to notify activity lifecycle events. 1560 */ 1561 @Nullable volatile ContentCaptureManagerInternal mContentCaptureService; 1562 1563 /* 1564 * The default duration for the binder heavy hitter auto sampler 1565 */ 1566 private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS = 300000L; 1567 1568 /** 1569 * The default throttling duration for the binder heavy hitter auto sampler 1570 */ 1571 private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS = 3600000L; 1572 1573 /** 1574 * The last time when the binder heavy hitter auto sampler started. 1575 */ 1576 @GuardedBy("mProcLock") 1577 private long mLastBinderHeavyHitterAutoSamplerStart = 0L; 1578 1579 final AppProfiler mAppProfiler; 1580 1581 private static final int INDEX_NATIVE_PSS = 0; 1582 private static final int INDEX_NATIVE_SWAP_PSS = 1; 1583 private static final int INDEX_NATIVE_RSS = 2; 1584 private static final int INDEX_DALVIK_PSS = 3; 1585 private static final int INDEX_DALVIK_SWAP_PSS = 4; 1586 private static final int INDEX_DALVIK_RSS = 5; 1587 private static final int INDEX_OTHER_PSS = 6; 1588 private static final int INDEX_OTHER_SWAP_PSS = 7; 1589 private static final int INDEX_OTHER_RSS = 8; 1590 private static final int INDEX_TOTAL_PSS = 9; 1591 private static final int INDEX_TOTAL_SWAP_PSS = 10; 1592 private static final int INDEX_TOTAL_RSS = 11; 1593 private static final int INDEX_TOTAL_NATIVE_PSS = 12; 1594 private static final int INDEX_TOTAL_MEMTRACK_GRAPHICS = 13; 1595 private static final int INDEX_TOTAL_MEMTRACK_GL = 14; 1596 private static final int INDEX_LAST = 15; 1597 1598 /** 1599 * Used to notify activity lifecycle events. 1600 */ 1601 @Nullable 1602 volatile ActivityManagerInternal.VoiceInteractionManagerProvider 1603 mVoiceInteractionManagerProvider; 1604 1605 final class UiHandler extends Handler { UiHandler()1606 public UiHandler() { 1607 super(com.android.server.UiThread.get().getLooper(), null, true); 1608 } 1609 1610 @Override handleMessage(Message msg)1611 public void handleMessage(Message msg) { 1612 switch (msg.what) { 1613 case SHOW_ERROR_UI_MSG: { 1614 mAppErrors.handleShowAppErrorUi(msg); 1615 ensureBootCompleted(); 1616 } break; 1617 case SHOW_NOT_RESPONDING_UI_MSG: { 1618 mAppErrors.handleShowAnrUi(msg); 1619 ensureBootCompleted(); 1620 } break; 1621 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: { 1622 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1623 synchronized (mProcLock) { 1624 ProcessRecord proc = (ProcessRecord) data.get("app"); 1625 if (proc == null) { 1626 Slog.e(TAG, "App not found when showing strict mode dialog."); 1627 break; 1628 } 1629 if (proc.mErrorState.getDialogController().hasViolationDialogs()) { 1630 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1631 return; 1632 } 1633 AppErrorResult res = (AppErrorResult) data.get("result"); 1634 if (mAtmInternal.showStrictModeViolationDialog()) { 1635 proc.mErrorState.getDialogController().showViolationDialogs(res); 1636 } else { 1637 // The device is asleep, so just pretend that the user 1638 // saw a crash dialog and hit "force quit". 1639 res.set(0); 1640 } 1641 } 1642 ensureBootCompleted(); 1643 } break; 1644 case WAIT_FOR_DEBUGGER_UI_MSG: { 1645 synchronized (mProcLock) { 1646 ProcessRecord app = (ProcessRecord) msg.obj; 1647 if (msg.arg1 != 0) { 1648 if (!app.hasWaitedForDebugger()) { 1649 app.mErrorState.getDialogController().showDebugWaitingDialogs(); 1650 app.setWaitedForDebugger(true); 1651 } 1652 } else { 1653 app.mErrorState.getDialogController().clearWaitingDialog(); 1654 } 1655 } 1656 } break; 1657 case DISPATCH_PROCESSES_CHANGED_UI_MSG: { 1658 mProcessList.dispatchProcessesChanged(); 1659 break; 1660 } 1661 case DISPATCH_PROCESS_DIED_UI_MSG: { 1662 if (false) { // DO NOT SUBMIT WITH TRUE 1663 maybeTriggerWatchdog(); 1664 } 1665 final int pid = msg.arg1; 1666 final int uid = msg.arg2; 1667 mProcessList.dispatchProcessDied(pid, uid); 1668 break; 1669 } 1670 case DISPATCH_OOM_ADJ_OBSERVER_MSG: { 1671 dispatchOomAdjObserver((String) msg.obj); 1672 } break; 1673 case PUSH_TEMP_ALLOWLIST_UI_MSG: { 1674 pushTempAllowlist(); 1675 } break; 1676 } 1677 } 1678 } 1679 1680 final class MainHandler extends Handler { MainHandler(Looper looper)1681 public MainHandler(Looper looper) { 1682 super(looper, null, true); 1683 } 1684 1685 @Override handleMessage(Message msg)1686 public void handleMessage(Message msg) { 1687 switch (msg.what) { 1688 case GC_BACKGROUND_PROCESSES_MSG: { 1689 synchronized (ActivityManagerService.this) { 1690 mAppProfiler.performAppGcsIfAppropriateLocked(); 1691 } 1692 } break; 1693 case SERVICE_TIMEOUT_MSG: { 1694 mServices.serviceTimeout((ProcessRecord) msg.obj); 1695 } break; 1696 case SERVICE_FOREGROUND_TIMEOUT_MSG: { 1697 mServices.serviceForegroundTimeout((ServiceRecord) msg.obj); 1698 } break; 1699 case SERVICE_FOREGROUND_TIMEOUT_ANR_MSG: { 1700 SomeArgs args = (SomeArgs) msg.obj; 1701 mServices.serviceForegroundTimeoutANR((ProcessRecord) args.arg1, 1702 (String) args.arg2); 1703 args.recycle(); 1704 } break; 1705 case SERVICE_FOREGROUND_CRASH_MSG: { 1706 SomeArgs args = (SomeArgs) msg.obj; 1707 mServices.serviceForegroundCrash( 1708 (ProcessRecord) args.arg1, 1709 (String) args.arg2, 1710 (ComponentName) args.arg3); 1711 args.recycle(); 1712 } break; 1713 case UPDATE_TIME_ZONE: { 1714 synchronized (mProcLock) { 1715 mProcessList.forEachLruProcessesLOSP(false, app -> { 1716 final IApplicationThread thread = app.getThread(); 1717 if (thread != null) { 1718 try { 1719 thread.updateTimeZone(); 1720 } catch (RemoteException ex) { 1721 Slog.w(TAG, "Failed to update time zone for: " 1722 + app.info.processName); 1723 } 1724 } 1725 }); 1726 } 1727 } break; 1728 case CLEAR_DNS_CACHE_MSG: { 1729 synchronized (mProcLock) { 1730 mProcessList.clearAllDnsCacheLOSP(); 1731 } 1732 } break; 1733 case UPDATE_HTTP_PROXY_MSG: { 1734 mProcessList.setAllHttpProxy(); 1735 } break; 1736 case PROC_START_TIMEOUT_MSG: { 1737 ProcessRecord app = (ProcessRecord) msg.obj; 1738 synchronized (ActivityManagerService.this) { 1739 handleProcessStartOrKillTimeoutLocked(app, /* isKillTimeout */ false); 1740 } 1741 } break; 1742 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: { 1743 ProcessRecord app = (ProcessRecord) msg.obj; 1744 synchronized (ActivityManagerService.this) { 1745 mCpHelper.processContentProviderPublishTimedOutLocked(app); 1746 } 1747 } break; 1748 case KILL_APPLICATION_MSG: { 1749 synchronized (ActivityManagerService.this) { 1750 final int appId = msg.arg1; 1751 final int userId = msg.arg2; 1752 Bundle bundle = (Bundle) msg.obj; 1753 String pkg = bundle.getString("pkg"); 1754 String reason = bundle.getString("reason"); 1755 forceStopPackageLocked(pkg, appId, false, false, true, false, 1756 false, userId, reason); 1757 } 1758 } break; 1759 1760 case KILL_APP_ZYGOTE_MSG: { 1761 synchronized (ActivityManagerService.this) { 1762 final AppZygote appZygote = (AppZygote) msg.obj; 1763 mProcessList.killAppZygoteIfNeededLocked(appZygote, false /* force */); 1764 } 1765 } break; 1766 case CHECK_EXCESSIVE_POWER_USE_MSG: { 1767 checkExcessivePowerUsage(); 1768 removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG); 1769 Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 1770 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 1771 } break; 1772 case REPORT_MEM_USAGE_MSG: { 1773 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>) msg.obj; 1774 Thread thread = new Thread() { 1775 @Override public void run() { 1776 mAppProfiler.reportMemUsage(memInfos); 1777 } 1778 }; 1779 thread.start(); 1780 break; 1781 } 1782 case UPDATE_TIME_PREFERENCE_MSG: { 1783 // The user's time format preference might have changed. 1784 // For convenience we re-use the Intent extra values. 1785 synchronized (mProcLock) { 1786 mProcessList.updateAllTimePrefsLOSP(msg.arg1); 1787 } 1788 break; 1789 } 1790 case NOTIFY_CLEARTEXT_NETWORK_MSG: { 1791 final int uid = msg.arg1; 1792 final byte[] firstPacket = (byte[]) msg.obj; 1793 1794 synchronized (mProcLock) { 1795 synchronized (mPidsSelfLocked) { 1796 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 1797 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 1798 final IApplicationThread thread = p.getThread(); 1799 if (p.uid == uid && thread != null) { 1800 try { 1801 thread.notifyCleartextNetwork(firstPacket); 1802 } catch (RemoteException ignored) { 1803 } 1804 } 1805 } 1806 } 1807 } 1808 } break; 1809 case POST_DUMP_HEAP_NOTIFICATION_MSG: { 1810 mAppProfiler.handlePostDumpHeapNotification(); 1811 } break; 1812 case ABORT_DUMPHEAP_MSG: { 1813 mAppProfiler.handleAbortDumpHeap((String) msg.obj); 1814 } break; 1815 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: { 1816 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj; 1817 try { 1818 connection.shutdown(); 1819 } catch (RemoteException e) { 1820 Slog.w(TAG, "Error shutting down UiAutomationConnection"); 1821 } 1822 // Only a UiAutomation can set this flag and now that 1823 // it is finished we make sure it is reset to its default. 1824 mUserIsMonkey = false; 1825 } break; 1826 case IDLE_UIDS_MSG: { 1827 idleUids(); 1828 } break; 1829 case HANDLE_TRUST_STORAGE_UPDATE_MSG: { 1830 synchronized (mProcLock) { 1831 mProcessList.handleAllTrustStorageUpdateLOSP(); 1832 } 1833 } break; 1834 case BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG: { 1835 handleBinderHeavyHitterAutoSamplerTimeOut(); 1836 } break; 1837 case WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG: { 1838 synchronized (ActivityManagerService.this) { 1839 ((ContentProviderRecord) msg.obj).onProviderPublishStatusLocked(false); 1840 } 1841 } break; 1842 case DISPATCH_SENDING_BROADCAST_EVENT: { 1843 mBroadcastEventListeners.forEach(l -> 1844 l.onSendingBroadcast((String) msg.obj, msg.arg1)); 1845 } break; 1846 case DISPATCH_BINDING_SERVICE_EVENT: { 1847 mBindServiceEventListeners.forEach(l -> 1848 l.onBindingService((String) msg.obj, msg.arg1)); 1849 } break; 1850 } 1851 } 1852 } 1853 1854 setSystemProcess()1855 public void setSystemProcess() { 1856 try { 1857 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, 1858 DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); 1859 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 1860 ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false, 1861 DUMP_FLAG_PRIORITY_HIGH); 1862 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 1863 ServiceManager.addService("dbinfo", new DbBinder(this)); 1864 mAppProfiler.setCpuInfoService(); 1865 ServiceManager.addService("permission", new PermissionController(this)); 1866 ServiceManager.addService("processinfo", new ProcessInfoService(this)); 1867 ServiceManager.addService("cacheinfo", new CacheBinder(this)); 1868 1869 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 1870 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); 1871 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 1872 1873 synchronized (this) { 1874 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName, 1875 false, 1876 0, 1877 false, 1878 0, 1879 null, 1880 new HostingRecord(HostingRecord.HOSTING_TYPE_SYSTEM)); 1881 app.setPersistent(true); 1882 app.setPid(MY_PID); 1883 app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ); 1884 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 1885 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_SYSTEM); 1886 addPidLocked(app); 1887 updateLruProcessLocked(app, false, null); 1888 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 1889 } 1890 } catch (PackageManager.NameNotFoundException e) { 1891 throw new RuntimeException( 1892 "Unable to find android system package", e); 1893 } 1894 1895 // Start watching app ops after we and the package manager are up and running. 1896 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null, 1897 new IAppOpsCallback.Stub() { 1898 @Override public void opChanged(int op, int uid, String packageName) { 1899 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) { 1900 if (getAppOpsManager().checkOpNoThrow(op, uid, packageName) 1901 != AppOpsManager.MODE_ALLOWED) { 1902 runInBackgroundDisabled(uid); 1903 } 1904 } 1905 } 1906 }); 1907 1908 final int[] cameraOp = {AppOpsManager.OP_CAMERA}; 1909 mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() { 1910 @Override 1911 public void opActiveChanged(int op, int uid, String packageName, String attributionTag, 1912 boolean active, @AttributionFlags int attributionFlags, 1913 int attributionChainId) { 1914 cameraActiveChanged(uid, active); 1915 } 1916 }); 1917 } 1918 setWindowManager(WindowManagerService wm)1919 public void setWindowManager(WindowManagerService wm) { 1920 synchronized (this) { 1921 mWindowManager = wm; 1922 mWmInternal = LocalServices.getService(WindowManagerInternal.class); 1923 mActivityTaskManager.setWindowManager(wm); 1924 } 1925 } 1926 1927 /** 1928 * @param usageStatsManager shouldn't be null 1929 */ setUsageStatsManager(@onNull UsageStatsManagerInternal usageStatsManager)1930 public void setUsageStatsManager(@NonNull UsageStatsManagerInternal usageStatsManager) { 1931 mUsageStatsService = usageStatsManager; 1932 mActivityTaskManager.setUsageStatsManager(usageStatsManager); 1933 } 1934 1935 /** 1936 * Sets the internal content capture manager service. 1937 * 1938 * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock. 1939 */ setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)1940 public void setContentCaptureManager( 1941 @Nullable ContentCaptureManagerInternal contentCaptureManager) { 1942 mContentCaptureService = contentCaptureManager; 1943 } 1944 startObservingNativeCrashes()1945 public void startObservingNativeCrashes() { 1946 final NativeCrashListener ncl = new NativeCrashListener(this); 1947 ncl.start(); 1948 } 1949 1950 /** 1951 * Sets a policy for handling app ops. 1952 * 1953 * @param appOpsPolicy The policy. 1954 */ setAppOpsPolicy(@ullable CheckOpsDelegate appOpsPolicy)1955 public void setAppOpsPolicy(@Nullable CheckOpsDelegate appOpsPolicy) { 1956 mAppOpsService.setAppOpsPolicy(appOpsPolicy); 1957 } 1958 getAppOpsService()1959 public IAppOpsService getAppOpsService() { 1960 return mAppOpsService; 1961 } 1962 1963 /** 1964 * Sets the internal voice interaction manager service. 1965 */ setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)1966 private void setVoiceInteractionManagerProvider( 1967 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) { 1968 mVoiceInteractionManagerProvider = provider; 1969 } 1970 1971 static class MemBinder extends Binder { 1972 ActivityManagerService mActivityManagerService; 1973 private final PriorityDump.PriorityDumper mPriorityDumper = 1974 new PriorityDump.PriorityDumper() { 1975 @Override 1976 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, 1977 boolean asProto) { 1978 dump(fd, pw, new String[] {"-a"}, asProto); 1979 } 1980 1981 @Override 1982 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 1983 mActivityManagerService.dumpApplicationMemoryUsage( 1984 fd, pw, " ", args, false, null, asProto); 1985 } 1986 }; 1987 MemBinder(ActivityManagerService activityManagerService)1988 MemBinder(ActivityManagerService activityManagerService) { 1989 mActivityManagerService = activityManagerService; 1990 } 1991 1992 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)1993 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1994 try { 1995 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 1996 1997 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 1998 "meminfo", pw)) return; 1999 PriorityDump.dump(mPriorityDumper, fd, pw, args); 2000 } finally { 2001 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2002 } 2003 } 2004 } 2005 2006 static class GraphicsBinder extends Binder { 2007 ActivityManagerService mActivityManagerService; GraphicsBinder(ActivityManagerService activityManagerService)2008 GraphicsBinder(ActivityManagerService activityManagerService) { 2009 mActivityManagerService = activityManagerService; 2010 } 2011 2012 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2013 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2014 try { 2015 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2016 2017 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2018 "gfxinfo", pw)) return; 2019 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 2020 } finally { 2021 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2022 } 2023 } 2024 } 2025 2026 static class DbBinder extends Binder { 2027 ActivityManagerService mActivityManagerService; DbBinder(ActivityManagerService activityManagerService)2028 DbBinder(ActivityManagerService activityManagerService) { 2029 mActivityManagerService = activityManagerService; 2030 } 2031 2032 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2033 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2034 try { 2035 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2036 2037 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2038 "dbinfo", pw)) return; 2039 mActivityManagerService.dumpDbInfo(fd, pw, args); 2040 } finally { 2041 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2042 } 2043 } 2044 } 2045 2046 static class CacheBinder extends Binder { 2047 ActivityManagerService mActivityManagerService; 2048 CacheBinder(ActivityManagerService activityManagerService)2049 CacheBinder(ActivityManagerService activityManagerService) { 2050 mActivityManagerService = activityManagerService; 2051 } 2052 2053 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2054 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2055 try { 2056 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 2057 2058 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2059 "cacheinfo", pw)) { 2060 return; 2061 } 2062 2063 mActivityManagerService.dumpBinderCacheContents(fd, pw, args); 2064 } finally { 2065 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 2066 } 2067 } 2068 } 2069 2070 public static final class Lifecycle extends SystemService { 2071 private final ActivityManagerService mService; 2072 private static ActivityTaskManagerService sAtm; 2073 Lifecycle(Context context)2074 public Lifecycle(Context context) { 2075 super(context); 2076 mService = new ActivityManagerService(context, sAtm); 2077 } 2078 startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2079 public static ActivityManagerService startService( 2080 SystemServiceManager ssm, ActivityTaskManagerService atm) { 2081 sAtm = atm; 2082 return ssm.startService(ActivityManagerService.Lifecycle.class).getService(); 2083 } 2084 2085 @Override onStart()2086 public void onStart() { 2087 mService.start(); 2088 } 2089 2090 @Override onBootPhase(int phase)2091 public void onBootPhase(int phase) { 2092 mService.mBootPhase = phase; 2093 if (phase == PHASE_SYSTEM_SERVICES_READY) { 2094 mService.mBatteryStatsService.systemServicesReady(); 2095 mService.mServices.systemServicesReady(); 2096 } else if (phase == PHASE_ACTIVITY_MANAGER_READY) { 2097 mService.startBroadcastObservers(); 2098 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { 2099 mService.mPackageWatchdog.onPackagesReady(); 2100 } 2101 } 2102 2103 @Override onUserStopped(@onNull TargetUser user)2104 public void onUserStopped(@NonNull TargetUser user) { 2105 mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier()); 2106 } 2107 getService()2108 public ActivityManagerService getService() { 2109 return mService; 2110 } 2111 } 2112 maybeLogUserspaceRebootEvent()2113 private void maybeLogUserspaceRebootEvent() { 2114 if (!UserspaceRebootLogger.shouldLogUserspaceRebootEvent()) { 2115 return; 2116 } 2117 final int userId = mUserController.getCurrentUserId(); 2118 if (userId != UserHandle.USER_SYSTEM) { 2119 // Only log for user0. 2120 return; 2121 } 2122 // TODO(b/148767783): should we check all profiles under user0? 2123 UserspaceRebootLogger.logEventAsync(StorageManager.isUserKeyUnlocked(userId), 2124 BackgroundThread.getExecutor()); 2125 } 2126 2127 /** 2128 * Encapsulates global settings related to hidden API enforcement behaviour, including tracking 2129 * the latest value via a content observer. 2130 */ 2131 static class HiddenApiSettings extends ContentObserver 2132 implements DeviceConfig.OnPropertiesChangedListener { 2133 2134 private final Context mContext; 2135 private boolean mBlacklistDisabled; 2136 private String mExemptionsStr; 2137 private List<String> mExemptions = Collections.emptyList(); 2138 private int mLogSampleRate = -1; 2139 private int mStatslogSampleRate = -1; 2140 @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT; 2141 2142 /** 2143 * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in 2144 * the range 0 to 0x10000 inclusive. 2145 * 2146 * @hide 2147 */ 2148 public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE = 2149 "hidden_api_access_log_sampling_rate"; 2150 2151 /** 2152 * Sampling rate for hidden API access event logging with statslog, as an integer in the 2153 * range 0 to 0x10000 inclusive. 2154 * 2155 * @hide 2156 */ 2157 public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE = 2158 "hidden_api_access_statslog_sampling_rate"; 2159 onPropertiesChanged(DeviceConfig.Properties properties)2160 public void onPropertiesChanged(DeviceConfig.Properties properties) { 2161 int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0x0); 2162 if (logSampleRate < 0 || logSampleRate > 0x10000) { 2163 logSampleRate = -1; 2164 } 2165 if (logSampleRate != -1 && logSampleRate != mLogSampleRate) { 2166 mLogSampleRate = logSampleRate; 2167 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate); 2168 } 2169 2170 int statslogSampleRate = 2171 properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0); 2172 if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) { 2173 statslogSampleRate = -1; 2174 } 2175 if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) { 2176 mStatslogSampleRate = statslogSampleRate; 2177 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate); 2178 } 2179 } 2180 HiddenApiSettings(Handler handler, Context context)2181 public HiddenApiSettings(Handler handler, Context context) { 2182 super(handler); 2183 mContext = context; 2184 } 2185 registerObserver()2186 public void registerObserver() { 2187 mContext.getContentResolver().registerContentObserver( 2188 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS), 2189 false, 2190 this); 2191 mContext.getContentResolver().registerContentObserver( 2192 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY), 2193 false, 2194 this); 2195 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT, 2196 mContext.getMainExecutor(), this); 2197 update(); 2198 } 2199 update()2200 private void update() { 2201 String exemptions = Settings.Global.getString(mContext.getContentResolver(), 2202 Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS); 2203 if (!TextUtils.equals(exemptions, mExemptionsStr)) { 2204 mExemptionsStr = exemptions; 2205 if ("*".equals(exemptions)) { 2206 mBlacklistDisabled = true; 2207 mExemptions = Collections.emptyList(); 2208 } else { 2209 mBlacklistDisabled = false; 2210 mExemptions = TextUtils.isEmpty(exemptions) 2211 ? Collections.emptyList() 2212 : Arrays.asList(exemptions.split(",")); 2213 } 2214 if (!ZYGOTE_PROCESS.setApiDenylistExemptions(mExemptions)) { 2215 Slog.e(TAG, "Failed to set API blacklist exemptions!"); 2216 // leave mExemptionsStr as is, so we don't try to send the same list again. 2217 mExemptions = Collections.emptyList(); 2218 } 2219 } 2220 mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY); 2221 } 2222 getValidEnforcementPolicy(String settingsKey)2223 private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) { 2224 int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey, 2225 ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT); 2226 if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) { 2227 return policy; 2228 } else { 2229 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 2230 } 2231 } 2232 isDisabled()2233 boolean isDisabled() { 2234 return mBlacklistDisabled; 2235 } 2236 getPolicy()2237 @HiddenApiEnforcementPolicy int getPolicy() { 2238 return mPolicy; 2239 } 2240 onChange(boolean selfChange)2241 public void onChange(boolean selfChange) { 2242 update(); 2243 } 2244 } 2245 2246 /** 2247 * Handles settings related to the enforcement of SDK sandbox restrictions. 2248 */ 2249 static class SdkSandboxSettings implements DeviceConfig.OnPropertiesChangedListener { 2250 2251 private final Context mContext; 2252 private final Object mLock = new Object(); 2253 2254 @GuardedBy("mLock") 2255 private boolean mEnforceBroadcastReceiverRestrictions; 2256 2257 /** 2258 * Property to enforce broadcast receiver restrictions for SDK sandbox processes. If the 2259 * value of this property is {@code true}, the restrictions will be enforced. 2260 */ 2261 public static final String ENFORCE_BROADCAST_RECEIVER_RESTRICTIONS = 2262 "enforce_broadcast_receiver_restrictions"; 2263 SdkSandboxSettings(Context context)2264 SdkSandboxSettings(Context context) { 2265 mContext = context; 2266 } 2267 registerObserver()2268 void registerObserver() { 2269 synchronized (mLock) { 2270 mEnforceBroadcastReceiverRestrictions = DeviceConfig.getBoolean( 2271 DeviceConfig.NAMESPACE_SDK_SANDBOX, 2272 ENFORCE_BROADCAST_RECEIVER_RESTRICTIONS, false); 2273 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_SDK_SANDBOX, 2274 mContext.getMainExecutor(), this); 2275 } 2276 } 2277 2278 @Override onPropertiesChanged(DeviceConfig.Properties properties)2279 public void onPropertiesChanged(DeviceConfig.Properties properties) { 2280 synchronized (mLock) { 2281 mEnforceBroadcastReceiverRestrictions = properties.getBoolean( 2282 ENFORCE_BROADCAST_RECEIVER_RESTRICTIONS, false); 2283 } 2284 } 2285 isBroadcastReceiverRestrictionsEnforced()2286 boolean isBroadcastReceiverRestrictionsEnforced() { 2287 synchronized (mLock) { 2288 return mEnforceBroadcastReceiverRestrictions; 2289 } 2290 } 2291 } 2292 getAppOpsManager()2293 AppOpsManager getAppOpsManager() { 2294 if (mAppOpsManager == null) { 2295 mAppOpsManager = mContext.getSystemService(AppOpsManager.class); 2296 } 2297 return mAppOpsManager; 2298 } 2299 2300 /** Provides the basic functionality for unit tests. */ 2301 @VisibleForTesting ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread)2302 ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread) { 2303 mInjector = injector; 2304 mContext = mInjector.getContext(); 2305 mUiContext = null; 2306 mAppErrors = null; 2307 mPackageWatchdog = null; 2308 mAppOpsService = mInjector.getAppOpsService(null /* file */, null /* handler */); 2309 mBatteryStatsService = null; 2310 mHandler = new MainHandler(handlerThread.getLooper()); 2311 mHandlerThread = handlerThread; 2312 mConstants = new ActivityManagerConstants(mContext, this, mHandler); 2313 final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */); 2314 mPlatformCompat = null; 2315 mProcessList = injector.getProcessList(this); 2316 mProcessList.init(this, activeUids, mPlatformCompat); 2317 mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), null); 2318 mPhantomProcessList = new PhantomProcessList(this); 2319 mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids, handlerThread); 2320 2321 mIntentFirewall = null; 2322 mProcessStats = null; 2323 mCpHelper = new ContentProviderHelper(this, false); 2324 mServices = null; 2325 mSystemThread = null; 2326 mUiHandler = injector.getUiHandler(null /* service */); 2327 mUidObserverController = new UidObserverController(mUiHandler); 2328 mUserController = new UserController(this); 2329 mPendingIntentController = 2330 new PendingIntentController(handlerThread.getLooper(), mUserController, mConstants); 2331 mAppRestrictionController = new AppRestrictionController(mContext, this); 2332 mProcStartHandlerThread = null; 2333 mProcStartHandler = null; 2334 mHiddenApiBlacklist = null; 2335 mSdkSandboxSettings = null; 2336 mFactoryTest = FACTORY_TEST_OFF; 2337 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2338 mInternal = new LocalService(); 2339 mPendingStartActivityUids = new PendingStartActivityUids(); 2340 mUseFifoUiScheduling = false; 2341 mEnableOffloadQueue = false; 2342 mFgBroadcastQueue = mBgBroadcastQueue = mBgOffloadBroadcastQueue = 2343 mFgOffloadBroadcastQueue = null; 2344 mComponentAliasResolver = new ComponentAliasResolver(this); 2345 } 2346 2347 // Note: This method is invoked on the main thread but may need to attach various 2348 // handlers to other threads. So take care to be explicit about the looper. ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2349 public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) { 2350 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); 2351 mInjector = new Injector(systemContext); 2352 mContext = systemContext; 2353 2354 mFactoryTest = FactoryTest.getMode(); 2355 mSystemThread = ActivityThread.currentActivityThread(); 2356 mUiContext = mSystemThread.getSystemUiContext(); 2357 2358 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2359 2360 mHandlerThread = new ServiceThread(TAG, 2361 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2362 mHandlerThread.start(); 2363 mHandler = new MainHandler(mHandlerThread.getLooper()); 2364 mUiHandler = mInjector.getUiHandler(this); 2365 2366 mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", 2367 THREAD_PRIORITY_FOREGROUND, false /* allowIo */); 2368 mProcStartHandlerThread.start(); 2369 mProcStartHandler = new ProcStartHandler(this, mProcStartHandlerThread.getLooper()); 2370 2371 mConstants = new ActivityManagerConstants(mContext, this, mHandler); 2372 final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */); 2373 mPlatformCompat = (PlatformCompat) ServiceManager.getService( 2374 Context.PLATFORM_COMPAT_SERVICE); 2375 mProcessList = mInjector.getProcessList(this); 2376 mProcessList.init(this, activeUids, mPlatformCompat); 2377 mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), 2378 new LowMemDetector(this)); 2379 mPhantomProcessList = new PhantomProcessList(this); 2380 mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids); 2381 2382 // Broadcast policy parameters 2383 final BroadcastConstants foreConstants = new BroadcastConstants( 2384 Settings.Global.BROADCAST_FG_CONSTANTS); 2385 foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT; 2386 2387 final BroadcastConstants backConstants = new BroadcastConstants( 2388 Settings.Global.BROADCAST_BG_CONSTANTS); 2389 backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; 2390 2391 final BroadcastConstants offloadConstants = new BroadcastConstants( 2392 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS); 2393 offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; 2394 // by default, no "slow" policy in this queue 2395 offloadConstants.SLOW_TIME = Integer.MAX_VALUE; 2396 2397 mEnableOffloadQueue = SystemProperties.getBoolean( 2398 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", true); 2399 2400 mFgBroadcastQueue = new BroadcastQueue(this, mHandler, 2401 "foreground", foreConstants, false); 2402 mBgBroadcastQueue = new BroadcastQueue(this, mHandler, 2403 "background", backConstants, true); 2404 mBgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, 2405 "offload_bg", offloadConstants, true); 2406 mFgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, 2407 "offload_fg", foreConstants, true); 2408 mBroadcastQueues[0] = mFgBroadcastQueue; 2409 mBroadcastQueues[1] = mBgBroadcastQueue; 2410 mBroadcastQueues[2] = mBgOffloadBroadcastQueue; 2411 mBroadcastQueues[3] = mFgOffloadBroadcastQueue; 2412 2413 mServices = new ActiveServices(this); 2414 mCpHelper = new ContentProviderHelper(this, true); 2415 mPackageWatchdog = PackageWatchdog.getInstance(mUiContext); 2416 mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog); 2417 mUidObserverController = new UidObserverController(mUiHandler); 2418 2419 final File systemDir = SystemServiceManager.ensureSystemDir(); 2420 2421 // TODO: Move creation of battery stats service outside of activity manager service. 2422 mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, 2423 BackgroundThread.get().getHandler()); 2424 mBatteryStatsService.getActiveStatistics().readLocked(); 2425 mBatteryStatsService.scheduleWriteToDisk(); 2426 mOnBattery = DEBUG_POWER ? true 2427 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2428 mBatteryStatsService.getActiveStatistics().setCallback(this); 2429 mOomAdjProfiler.batteryPowerChanged(mOnBattery); 2430 2431 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2432 2433 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler); 2434 2435 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2436 2437 mUserController = new UserController(this); 2438 2439 mPendingIntentController = new PendingIntentController( 2440 mHandlerThread.getLooper(), mUserController, mConstants); 2441 2442 mAppRestrictionController = new AppRestrictionController(mContext, this); 2443 2444 mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0; 2445 2446 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations")); 2447 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2448 2449 mActivityTaskManager = atm; 2450 mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, 2451 DisplayThread.get().getLooper()); 2452 mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class); 2453 2454 mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext); 2455 mSdkSandboxSettings = new SdkSandboxSettings(mContext); 2456 2457 Watchdog.getInstance().addMonitor(this); 2458 Watchdog.getInstance().addThread(mHandler); 2459 2460 // bind background threads to little cores 2461 // this is expected to fail inside of framework tests because apps can't touch cpusets directly 2462 // make sure we've already adjusted system_server's internal view of itself first 2463 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 2464 try { 2465 Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(), 2466 Process.THREAD_GROUP_SYSTEM); 2467 Process.setThreadGroupAndCpuset( 2468 mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(), 2469 Process.THREAD_GROUP_SYSTEM); 2470 } catch (Exception e) { 2471 Slog.w(TAG, "Setting background thread cpuset failed"); 2472 } 2473 2474 mInternal = new LocalService(); 2475 mPendingStartActivityUids = new PendingStartActivityUids(); 2476 mTraceErrorLogger = new TraceErrorLogger(); 2477 mComponentAliasResolver = new ComponentAliasResolver(this); 2478 } 2479 setSystemServiceManager(SystemServiceManager mgr)2480 public void setSystemServiceManager(SystemServiceManager mgr) { 2481 mSystemServiceManager = mgr; 2482 } 2483 setInstaller(Installer installer)2484 public void setInstaller(Installer installer) { 2485 mInstaller = installer; 2486 } 2487 start()2488 private void start() { 2489 mBatteryStatsService.publish(); 2490 mAppOpsService.publish(); 2491 mProcessStats.publish(); 2492 Slog.d("AppOps", "AppOpsService published"); 2493 LocalServices.addService(ActivityManagerInternal.class, mInternal); 2494 LocalManagerRegistry.addManager(ActivityManagerLocal.class, 2495 (ActivityManagerLocal) mInternal); 2496 mActivityTaskManager.onActivityManagerInternalAdded(); 2497 mPendingIntentController.onActivityManagerInternalAdded(); 2498 mAppProfiler.onActivityManagerInternalAdded(); 2499 CriticalEventLog.init(); 2500 } 2501 initPowerManagement()2502 public void initPowerManagement() { 2503 mActivityTaskManager.onInitPowerManagement(); 2504 mBatteryStatsService.initPowerManagement(); 2505 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); 2506 } 2507 getBackgroundLaunchBroadcasts()2508 private ArraySet<String> getBackgroundLaunchBroadcasts() { 2509 if (mBackgroundLaunchBroadcasts == null) { 2510 mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts(); 2511 } 2512 return mBackgroundLaunchBroadcasts; 2513 } 2514 2515 /** 2516 * Ensures that the given package name has an explicit set of allowed associations. 2517 * If it does not, give it an empty set. 2518 */ requireAllowedAssociationsLocked(String packageName)2519 void requireAllowedAssociationsLocked(String packageName) { 2520 ensureAllowedAssociations(); 2521 if (mAllowedAssociations.get(packageName) == null) { 2522 mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName, 2523 new ArraySet<>(), /* isDebuggable = */ false)); 2524 } 2525 } 2526 2527 /** 2528 * Returns true if the package {@code pkg1} running under user handle {@code uid1} is 2529 * allowed association with the package {@code pkg2} running under user handle {@code uid2}. 2530 * <p> If either of the packages are running as part of the core system, then the 2531 * association is implicitly allowed. 2532 */ validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2533 boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) { 2534 ensureAllowedAssociations(); 2535 // Interactions with the system uid are always allowed, since that is the core system 2536 // that everyone needs to be able to interact with. Also allow reflexive associations 2537 // within the same uid. 2538 if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID 2539 || UserHandle.getAppId(uid2) == SYSTEM_UID) { 2540 return true; 2541 } 2542 2543 // Check for association on both source and target packages. 2544 PackageAssociationInfo pai = mAllowedAssociations.get(pkg1); 2545 if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) { 2546 return false; 2547 } 2548 pai = mAllowedAssociations.get(pkg2); 2549 if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) { 2550 return false; 2551 } 2552 // If no explicit associations are provided in the manifest, then assume the app is 2553 // allowed associations with any package. 2554 return true; 2555 } 2556 2557 /** Sets up allowed associations for system prebuilt packages from system config (if needed). */ ensureAllowedAssociations()2558 private void ensureAllowedAssociations() { 2559 if (mAllowedAssociations == null) { 2560 ArrayMap<String, ArraySet<String>> allowedAssociations = 2561 SystemConfig.getInstance().getAllowedAssociations(); 2562 mAllowedAssociations = new ArrayMap<>(allowedAssociations.size()); 2563 PackageManagerInternal pm = getPackageManagerInternal(); 2564 for (int i = 0; i < allowedAssociations.size(); i++) { 2565 final String pkg = allowedAssociations.keyAt(i); 2566 final ArraySet<String> asc = allowedAssociations.valueAt(i); 2567 2568 // Query latest debuggable flag from package-manager. 2569 boolean isDebuggable = false; 2570 try { 2571 ApplicationInfo ai = AppGlobals.getPackageManager() 2572 .getApplicationInfo(pkg, MATCH_ALL, 0); 2573 if (ai != null) { 2574 isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 2575 } 2576 } catch (RemoteException e) { 2577 /* ignore */ 2578 } 2579 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable)); 2580 } 2581 } 2582 } 2583 2584 /** Updates allowed associations for app info (specifically, based on debuggability). */ updateAssociationForApp(ApplicationInfo appInfo)2585 private void updateAssociationForApp(ApplicationInfo appInfo) { 2586 ensureAllowedAssociations(); 2587 PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName); 2588 if (pai != null) { 2589 pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); 2590 } 2591 } 2592 2593 @Override onTransact(int code, Parcel data, Parcel reply, int flags)2594 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2595 throws RemoteException { 2596 if (code == SYSPROPS_TRANSACTION) { 2597 // We need to tell all apps about the system property change. 2598 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2599 synchronized (mProcLock) { 2600 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 2601 mProcessList.getProcessNamesLOSP().getMap(); 2602 final int numOfNames = pmap.size(); 2603 for (int ip = 0; ip < numOfNames; ip++) { 2604 SparseArray<ProcessRecord> apps = pmap.valueAt(ip); 2605 final int numOfApps = apps.size(); 2606 for (int ia = 0; ia < numOfApps; ia++) { 2607 ProcessRecord app = apps.valueAt(ia); 2608 final IApplicationThread thread = app.getThread(); 2609 if (thread != null) { 2610 procs.add(thread.asBinder()); 2611 } 2612 } 2613 } 2614 } 2615 2616 int N = procs.size(); 2617 for (int i=0; i<N; i++) { 2618 Parcel data2 = Parcel.obtain(); 2619 try { 2620 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 2621 Binder.FLAG_ONEWAY); 2622 } catch (RemoteException e) { 2623 } 2624 data2.recycle(); 2625 } 2626 } 2627 try { 2628 return super.onTransact(code, data, reply, flags); 2629 } catch (RuntimeException e) { 2630 // The activity manager only throws certain exceptions intentionally, so let's 2631 // log all others. 2632 if (!(e instanceof SecurityException 2633 || e instanceof IllegalArgumentException 2634 || e instanceof IllegalStateException)) { 2635 Slog.wtf(TAG, "Activity Manager Crash." 2636 + " UID:" + Binder.getCallingUid() 2637 + " PID:" + Binder.getCallingPid() 2638 + " TRANS:" + code, e); 2639 } 2640 throw e; 2641 } 2642 } 2643 updateCpuStats()2644 void updateCpuStats() { 2645 mAppProfiler.updateCpuStats(); 2646 } 2647 updateCpuStatsNow()2648 void updateCpuStatsNow() { 2649 mAppProfiler.updateCpuStatsNow(); 2650 } 2651 2652 @Override batteryNeedsCpuUpdate()2653 public void batteryNeedsCpuUpdate() { 2654 updateCpuStatsNow(); 2655 } 2656 2657 @Override batteryPowerChanged(boolean onBattery)2658 public void batteryPowerChanged(boolean onBattery) { 2659 // When plugging in, update the CPU stats first before changing 2660 // the plug state. 2661 updateCpuStatsNow(); 2662 synchronized (mProcLock) { 2663 mOnBattery = DEBUG_POWER ? true : onBattery; 2664 mOomAdjProfiler.batteryPowerChanged(onBattery); 2665 } 2666 } 2667 2668 @Override batteryStatsReset()2669 public void batteryStatsReset() { 2670 mOomAdjProfiler.reset(); 2671 } 2672 2673 @Override batterySendBroadcast(Intent intent)2674 public void batterySendBroadcast(Intent intent) { 2675 synchronized (this) { 2676 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, null, 2677 null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(), 2678 Binder.getCallingPid(), UserHandle.USER_ALL); 2679 } 2680 } 2681 2682 /** 2683 * Initialize the application bind args. These are passed to each 2684 * process when the bindApplication() IPC is sent to the process. They're 2685 * lazily setup to make sure the services are running when they're asked for. 2686 */ getCommonServicesLocked(boolean isolated)2687 private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) { 2688 // Isolated processes won't get this optimization, so that we don't 2689 // violate the rules about which services they have access to. 2690 if (isolated) { 2691 if (mIsolatedAppBindArgs == null) { 2692 mIsolatedAppBindArgs = new ArrayMap<>(1); 2693 addServiceToMap(mIsolatedAppBindArgs, "package"); 2694 addServiceToMap(mIsolatedAppBindArgs, "permissionmgr"); 2695 } 2696 return mIsolatedAppBindArgs; 2697 } 2698 2699 if (mAppBindArgs == null) { 2700 mAppBindArgs = new ArrayMap<>(); 2701 2702 // Add common services. 2703 // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too. 2704 // Enable the check in ApplicationThread.bindApplication() to make sure. 2705 addServiceToMap(mAppBindArgs, "package"); 2706 addServiceToMap(mAppBindArgs, "permissionmgr"); 2707 addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE); 2708 addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE); 2709 addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE); 2710 addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE); 2711 addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE); 2712 addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE); 2713 addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE); 2714 addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE); 2715 addServiceToMap(mAppBindArgs, "graphicsstats"); 2716 addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE); 2717 addServiceToMap(mAppBindArgs, "content"); 2718 addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE); 2719 addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE); 2720 addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE); 2721 addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE); 2722 addServiceToMap(mAppBindArgs, Context.POWER_SERVICE); 2723 addServiceToMap(mAppBindArgs, Context.USER_SERVICE); 2724 addServiceToMap(mAppBindArgs, "mount"); 2725 addServiceToMap(mAppBindArgs, Context.PLATFORM_COMPAT_SERVICE); 2726 } 2727 return mAppBindArgs; 2728 } 2729 addServiceToMap(ArrayMap<String, IBinder> map, String name)2730 private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) { 2731 final IBinder service = ServiceManager.getService(name); 2732 if (service != null) { 2733 map.put(name, service); 2734 if (false) { 2735 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache."); 2736 } 2737 } 2738 } 2739 2740 @Override setFocusedRootTask(int taskId)2741 public void setFocusedRootTask(int taskId) { 2742 mActivityTaskManager.setFocusedRootTask(taskId); 2743 } 2744 2745 /** Sets the task stack listener that gets callbacks when a task stack changes. */ 2746 @Override registerTaskStackListener(ITaskStackListener listener)2747 public void registerTaskStackListener(ITaskStackListener listener) { 2748 mActivityTaskManager.registerTaskStackListener(listener); 2749 } 2750 2751 /** 2752 * Unregister a task stack listener so that it stops receiving callbacks. 2753 */ 2754 @Override unregisterTaskStackListener(ITaskStackListener listener)2755 public void unregisterTaskStackListener(ITaskStackListener listener) { 2756 mActivityTaskManager.unregisterTaskStackListener(listener); 2757 } 2758 2759 @GuardedBy("this") updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2760 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2761 ProcessRecord client) { 2762 mProcessList.updateLruProcessLocked(app, activityChange, client); 2763 } 2764 2765 @GuardedBy("this") removeLruProcessLocked(ProcessRecord app)2766 final void removeLruProcessLocked(ProcessRecord app) { 2767 mProcessList.removeLruProcessLocked(app); 2768 } 2769 2770 @GuardedBy("this") getProcessRecordLocked(String processName, int uid)2771 final ProcessRecord getProcessRecordLocked(String processName, int uid) { 2772 return mProcessList.getProcessRecordLocked(processName, uid); 2773 } 2774 2775 @GuardedBy(anyOf = {"this", "mProcLock"}) getProcessNamesLOSP()2776 final ProcessMap<ProcessRecord> getProcessNamesLOSP() { 2777 return mProcessList.getProcessNamesLOSP(); 2778 } 2779 notifyPackageUse(String packageName, int reason)2780 void notifyPackageUse(String packageName, int reason) { 2781 getPackageManagerInternal().notifyPackageUse(packageName, reason); 2782 } 2783 startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2784 boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 2785 String processName, String abiOverride, int uid, Runnable crashHandler) { 2786 synchronized(this) { 2787 ApplicationInfo info = new ApplicationInfo(); 2788 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 2789 // For isolated processes, the former contains the parent's uid and the latter the 2790 // actual uid of the isolated process. 2791 // In the special case introduced by this method (which is, starting an isolated 2792 // process directly from the SystemServer without an actual parent app process) the 2793 // closest thing to a parent's uid is SYSTEM_UID. 2794 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 2795 // the |isolated| logic in the ProcessRecord constructor. 2796 info.uid = SYSTEM_UID; 2797 info.processName = processName; 2798 info.className = entryPoint; 2799 info.packageName = "android"; 2800 info.seInfoUser = SELinuxUtil.COMPLETE_STR; 2801 info.targetSdkVersion = Build.VERSION.SDK_INT; 2802 ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */, 2803 false /* knownToBeDead */, 0 /* intentFlags */, 2804 sNullHostingRecord /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY, 2805 true /* allowWhileBooting */, true /* isolated */, 2806 uid, false /* isSdkSandbox */, 0 /* sdkSandboxUid */, 2807 null /* sdkSandboxClientAppPackage */, 2808 abiOverride, entryPoint, entryPointArgs, crashHandler); 2809 return proc != null; 2810 } 2811 } 2812 2813 @GuardedBy("this") startSdkSandboxProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid, String sdkSandboxClientAppPackage)2814 final ProcessRecord startSdkSandboxProcessLocked(String processName, 2815 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2816 HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid, 2817 String sdkSandboxClientAppPackage) { 2818 return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, 2819 hostingRecord, zygotePolicyFlags, false /* allowWhileBooting */, 2820 false /* isolated */, 0 /* isolatedUid */, 2821 true /* isSdkSandbox */, sdkSandboxUid, sdkSandboxClientAppPackage, 2822 null /* ABI override */, null /* entryPoint */, 2823 null /* entryPointArgs */, null /* crashHandler */); 2824 } 2825 2826 @GuardedBy("this") startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated)2827 final ProcessRecord startProcessLocked(String processName, 2828 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2829 HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, 2830 boolean isolated) { 2831 return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, 2832 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */, 2833 false /* isSdkSandbox */, 0 /* sdkSandboxClientAppUid */, 2834 null /* sdkSandboxClientAppPackage */, 2835 null /* ABI override */, null /* entryPoint */, 2836 null /* entryPointArgs */, null /* crashHandler */); 2837 } 2838 isAllowedWhileBooting(ApplicationInfo ai)2839 boolean isAllowedWhileBooting(ApplicationInfo ai) { 2840 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 2841 } 2842 2843 /** 2844 * Update battery stats on the activity' usage. 2845 * @param activity 2846 * @param uid 2847 * @param userId 2848 * @param resumed 2849 */ updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)2850 void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) { 2851 if (DEBUG_SWITCH) { 2852 Slog.d(TAG_SWITCH, 2853 "updateBatteryStats: comp=" + activity + "res=" + resumed); 2854 } 2855 mBatteryStatsService.updateBatteryStatsOnActivityUsage(activity.getPackageName(), 2856 activity.getShortClassName(), uid, userId, resumed); 2857 } 2858 2859 /** 2860 * Update UsageStas on the activity's usage. 2861 * @param activity 2862 * @param userId 2863 * @param event 2864 * @param appToken ActivityRecord's appToken. 2865 * @param taskRoot Task's root 2866 */ updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)2867 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 2868 IBinder appToken, ComponentName taskRoot) { 2869 if (DEBUG_SWITCH) { 2870 Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp=" 2871 + activity + " hash=" + appToken.hashCode() + " event=" + event); 2872 } 2873 if (mUsageStatsService != null) { 2874 mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(), taskRoot); 2875 if (event == Event.ACTIVITY_RESUMED) { 2876 // Report component usage as an activity is an app component 2877 mUsageStatsService.reportEvent( 2878 activity.getPackageName(), userId, Event.APP_COMPONENT_USED); 2879 } 2880 } 2881 ContentCaptureManagerInternal contentCaptureService = mContentCaptureService; 2882 if (contentCaptureService != null && (event == Event.ACTIVITY_PAUSED 2883 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED 2884 || event == Event.ACTIVITY_DESTROYED)) { 2885 contentCaptureService.notifyActivityEvent(userId, activity, event); 2886 } 2887 // Currently we have move most of logic to the client side. When the activity lifecycle 2888 // event changed, the client side will notify the VoiceInteractionManagerService. But 2889 // when the application process died, the VoiceInteractionManagerService will miss the 2890 // activity lifecycle event changed, so we still need ACTIVITY_DESTROYED event here to 2891 // know if the activity has been destroyed. 2892 if (mVoiceInteractionManagerProvider != null && event == Event.ACTIVITY_DESTROYED) { 2893 mVoiceInteractionManagerProvider.notifyActivityDestroyed(appToken); 2894 } 2895 } 2896 2897 /** 2898 * Update UsageStats on this package's usage. 2899 * @param packageName 2900 * @param userId 2901 * @param event 2902 */ updateActivityUsageStats(String packageName, int userId, int event)2903 public void updateActivityUsageStats(String packageName, int userId, int event) { 2904 if (DEBUG_SWITCH) { 2905 Slog.d(TAG_SWITCH, "updateActivityUsageStats: package=" 2906 + packageName + " event=" + event); 2907 } 2908 if (mUsageStatsService != null) { 2909 mUsageStatsService.reportEvent(packageName, userId, event); 2910 } 2911 } 2912 2913 /** 2914 * Update Usages on this foreground service's usage. 2915 * @param service 2916 * @param userId 2917 * @param started 2918 */ updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)2919 void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) { 2920 if (DEBUG_SWITCH) { 2921 Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp=" 2922 + service + " started=" + started); 2923 } 2924 if (mUsageStatsService != null) { 2925 mUsageStatsService.reportEvent(service, userId, 2926 started ? UsageEvents.Event.FOREGROUND_SERVICE_START 2927 : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null); 2928 } 2929 } 2930 compatibilityInfoForPackage(ApplicationInfo ai)2931 CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) { 2932 return mAtmInternal.compatibilityInfoForPackage(ai); 2933 } 2934 2935 /** 2936 * Enforces that the uid that calls a method is not an 2937 * {@link UserHandle#isIsolated(int) isolated} uid. 2938 * 2939 * @param caller the name of the method being called. 2940 * @throws SecurityException if the calling uid is an isolated uid. 2941 */ enforceNotIsolatedCaller(String caller)2942 /* package */ void enforceNotIsolatedCaller(String caller) { 2943 if (UserHandle.isIsolated(Binder.getCallingUid())) { 2944 throw new SecurityException("Isolated process not allowed to call " + caller); 2945 } 2946 } 2947 2948 /** 2949 * Enforces that the uid that calls a method is not an 2950 * {@link UserHandle#isIsolated(int) isolated} uid or an 2951 * {@link Process#isSdkSandboxUid(int) SDK sandbox} uid. 2952 * 2953 * @param caller the name of the method being called. 2954 * @throws SecurityException if the calling uid is an isolated uid or SDK sandbox uid. 2955 */ enforceNotIsolatedOrSdkSandboxCaller(String caller)2956 void enforceNotIsolatedOrSdkSandboxCaller(String caller) { 2957 enforceNotIsolatedCaller(caller); 2958 2959 if (Process.isSdkSandboxUid(Binder.getCallingUid())) { 2960 throw new SecurityException("SDK sandbox process not allowed to call " + caller); 2961 } 2962 } 2963 2964 /** 2965 * If the caller is an {@link Process#isSdkSandboxUid(int) SDK sandbox uid}, enforces that the 2966 * SDK sandbox has permission to start or bind to a given service. 2967 * 2968 * @param intent the intent used to start or bind to the service. 2969 * @throws IllegalStateException if {@link SdkSandboxManagerLocal} cannot be resolved. 2970 * @throws SecurityException if the SDK sandbox is not allowed to bind to this service. 2971 */ enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent)2972 private void enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent) { 2973 if (Process.isSdkSandboxUid(Binder.getCallingUid())) { 2974 SdkSandboxManagerLocal sdkSandboxManagerLocal = 2975 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 2976 if (sdkSandboxManagerLocal != null) { 2977 sdkSandboxManagerLocal.enforceAllowedToStartOrBindService(intent); 2978 } else { 2979 throw new IllegalStateException("SdkSandboxManagerLocal not found when checking" 2980 + " whether SDK sandbox uid may start or bind to a service."); 2981 } 2982 } 2983 } 2984 2985 @Override setPackageScreenCompatMode(String packageName, int mode)2986 public void setPackageScreenCompatMode(String packageName, int mode) { 2987 mActivityTaskManager.setPackageScreenCompatMode(packageName, mode); 2988 } 2989 hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid)2990 private boolean hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid) { 2991 final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS, 2992 callingUid, callingPackage, null, false, "", false).getOpMode(); 2993 if (mode == AppOpsManager.MODE_DEFAULT) { 2994 return checkPermission(Manifest.permission.PACKAGE_USAGE_STATS, callingPid, callingUid) 2995 == PackageManager.PERMISSION_GRANTED; 2996 } 2997 return mode == AppOpsManager.MODE_ALLOWED; 2998 } 2999 hasUsageStatsPermission(String callingPackage)3000 private boolean hasUsageStatsPermission(String callingPackage) { 3001 return hasUsageStatsPermission(callingPackage, 3002 Binder.getCallingUid(), Binder.getCallingPid()); 3003 } 3004 enforceUsageStatsPermission(String callingPackage, int callingUid, int callingPid, String operation)3005 private void enforceUsageStatsPermission(String callingPackage, 3006 int callingUid, int callingPid, String operation) { 3007 if (!hasUsageStatsPermission(callingPackage, callingUid, callingPid)) { 3008 final String errorMsg = "Permission denial for <" + operation + "> from pid=" 3009 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3010 + " which requires PACKAGE_USAGE_STATS permission"; 3011 throw new SecurityException(errorMsg); 3012 } 3013 } 3014 3015 @Override getPackageProcessState(String packageName, String callingPackage)3016 public int getPackageProcessState(String packageName, String callingPackage) { 3017 if (!hasUsageStatsPermission(callingPackage)) { 3018 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 3019 "getPackageProcessState"); 3020 } 3021 3022 final int[] procState = {PROCESS_STATE_NONEXISTENT}; 3023 synchronized (mProcLock) { 3024 mProcessList.forEachLruProcessesLOSP(false, proc -> { 3025 if (procState[0] > proc.mState.getSetProcState()) { 3026 if (proc.getPkgList().containsKey(packageName) || (proc.getPkgDeps() != null 3027 && proc.getPkgDeps().contains(packageName))) { 3028 procState[0] = proc.mState.getSetProcState(); 3029 } 3030 } 3031 }); 3032 } 3033 return procState[0]; 3034 } 3035 3036 @Override setProcessMemoryTrimLevel(String process, int userId, int level)3037 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) 3038 throws RemoteException { 3039 if (!isCallerShell()) { 3040 throw new SecurityException("Only shell can call it"); 3041 } 3042 synchronized (this) { 3043 final ProcessRecord app = findProcessLOSP(process, userId, "setProcessMemoryTrimLevel"); 3044 if (app == null) { 3045 throw new IllegalArgumentException("Unknown process: " + process); 3046 } 3047 final IApplicationThread thread = app.getThread(); 3048 if (thread == null) { 3049 throw new IllegalArgumentException("Process has no app thread"); 3050 } 3051 if (app.mProfile.getTrimMemoryLevel() >= level) { 3052 throw new IllegalArgumentException( 3053 "Unable to set a higher trim level than current level"); 3054 } 3055 if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || 3056 app.mState.getCurProcState() > PROCESS_STATE_IMPORTANT_FOREGROUND)) { 3057 throw new IllegalArgumentException("Unable to set a background trim level " 3058 + "on a foreground process"); 3059 } 3060 thread.scheduleTrimMemory(level); 3061 synchronized (mProcLock) { 3062 app.mProfile.setTrimMemoryLevel(level); 3063 } 3064 return true; 3065 } 3066 } 3067 dispatchOomAdjObserver(String msg)3068 void dispatchOomAdjObserver(String msg) { 3069 OomAdjObserver observer; 3070 synchronized (mOomAdjObserverLock) { 3071 observer = mCurOomAdjObserver; 3072 } 3073 3074 if (observer != null) { 3075 observer.onOomAdjMessage(msg); 3076 } 3077 } 3078 setOomAdjObserver(int uid, OomAdjObserver observer)3079 void setOomAdjObserver(int uid, OomAdjObserver observer) { 3080 synchronized (mOomAdjObserverLock) { 3081 mCurOomAdjUid = uid; 3082 mCurOomAdjObserver = observer; 3083 } 3084 } 3085 clearOomAdjObserver()3086 void clearOomAdjObserver() { 3087 synchronized (mOomAdjObserverLock) { 3088 mCurOomAdjUid = -1; 3089 mCurOomAdjObserver = null; 3090 } 3091 } 3092 reportUidInfoMessageLocked(String tag, String msg, int uid)3093 void reportUidInfoMessageLocked(String tag, String msg, int uid) { 3094 Slog.i(TAG, msg); 3095 synchronized (mOomAdjObserverLock) { 3096 if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) { 3097 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget(); 3098 } 3099 } 3100 } 3101 3102 /** 3103 * @deprecated use {@link #startActivityWithFeature} instead 3104 */ 3105 @Deprecated 3106 @Override startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3107 public int startActivity(IApplicationThread caller, String callingPackage, 3108 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3109 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { 3110 return mActivityTaskManager.startActivity(caller, callingPackage, null, intent, 3111 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 3112 } 3113 3114 @Override startActivityWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3115 public int startActivityWithFeature(IApplicationThread caller, String callingPackage, 3116 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, 3117 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, 3118 Bundle bOptions) { 3119 return mActivityTaskManager.startActivity(caller, callingPackage, callingFeatureId, intent, 3120 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 3121 } 3122 3123 /** 3124 * @deprecated use {@link #startActivityAsUserWithFeature} instead 3125 */ 3126 @Deprecated 3127 @Override startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3128 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 3129 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3130 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 3131 return startActivityAsUserWithFeature(caller, callingPackage, null, intent, resolvedType, 3132 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId); 3133 } 3134 3135 @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)3136 public final int startActivityAsUserWithFeature(IApplicationThread caller, 3137 String callingPackage, String callingFeatureId, Intent intent, String resolvedType, 3138 IBinder resultTo, String resultWho, int requestCode, int startFlags, 3139 ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 3140 return mActivityTaskManager.startActivityAsUser(caller, callingPackage, 3141 callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, 3142 startFlags, profilerInfo, bOptions, userId); 3143 } 3144 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)3145 WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 3146 @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, 3147 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, 3148 Bundle bOptions, int userId) { 3149 return mActivityTaskManager.startActivityAndWait(caller, callingPackage, 3150 callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, 3151 startFlags, profilerInfo, bOptions, userId); 3152 } 3153 3154 @Override startActivityFromRecents(int taskId, Bundle bOptions)3155 public final int startActivityFromRecents(int taskId, Bundle bOptions) { 3156 return mActivityTaskManager.startActivityFromRecents(taskId, bOptions); 3157 } 3158 3159 /** 3160 * This is the internal entry point for handling Activity.finish(). 3161 * 3162 * @param token The Binder token referencing the Activity we want to finish. 3163 * @param resultCode Result code, if any, from this Activity. 3164 * @param resultData Result data (Intent), if any, from this Activity. 3165 * @param finishTask Whether to finish the task associated with this Activity. 3166 * 3167 * @return Returns true if the activity successfully finished, or false if it is still running. 3168 */ 3169 @Override finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3170 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 3171 int finishTask) { 3172 return ActivityClient.getInstance().finishActivity(token, resultCode, resultData, 3173 finishTask); 3174 } 3175 3176 @Override setRequestedOrientation(IBinder token, int requestedOrientation)3177 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 3178 ActivityClient.getInstance().setRequestedOrientation(token, requestedOrientation); 3179 } 3180 3181 @Override finishHeavyWeightApp()3182 public final void finishHeavyWeightApp() { 3183 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3184 != PackageManager.PERMISSION_GRANTED) { 3185 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 3186 + Binder.getCallingPid() 3187 + ", uid=" + Binder.getCallingUid() 3188 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3189 Slog.w(TAG, msg); 3190 throw new SecurityException(msg); 3191 } 3192 mAtmInternal.finishHeavyWeightApp(); 3193 } 3194 3195 @Override crashApplicationWithType(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId)3196 public void crashApplicationWithType(int uid, int initialPid, String packageName, int userId, 3197 String message, boolean force, int exceptionTypeId) { 3198 crashApplicationWithTypeWithExtras(uid, initialPid, packageName, userId, message, 3199 force, exceptionTypeId, null); 3200 } 3201 3202 @Override crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId, @Nullable Bundle extras)3203 public void crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, 3204 int userId, String message, boolean force, int exceptionTypeId, 3205 @Nullable Bundle extras) { 3206 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3207 != PackageManager.PERMISSION_GRANTED) { 3208 String msg = "Permission Denial: crashApplication() from pid=" 3209 + Binder.getCallingPid() 3210 + ", uid=" + Binder.getCallingUid() 3211 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3212 Slog.w(TAG, msg); 3213 throw new SecurityException(msg); 3214 } 3215 3216 synchronized(this) { 3217 mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId, 3218 message, force, exceptionTypeId, extras); 3219 } 3220 } 3221 3222 /** 3223 * Main function for removing an existing process from the activity manager 3224 * as a result of that process going away. Clears out all connections 3225 * to the process. 3226 */ 3227 @GuardedBy("this") handleAppDiedLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, boolean fromBinderDied)3228 final void handleAppDiedLocked(ProcessRecord app, int pid, 3229 boolean restarting, boolean allowRestart, boolean fromBinderDied) { 3230 boolean kept = cleanUpApplicationRecordLocked(app, pid, restarting, allowRestart, -1, 3231 false /*replacingPid*/, fromBinderDied); 3232 if (!kept && !restarting) { 3233 removeLruProcessLocked(app); 3234 if (pid > 0) { 3235 ProcessList.remove(pid); 3236 } 3237 } 3238 3239 mAppProfiler.onAppDiedLocked(app); 3240 3241 mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> { 3242 Slog.w(TAG, "Crash of app " + app.processName 3243 + " running instrumentation " + app.getActiveInstrumentation().mClass); 3244 Bundle info = new Bundle(); 3245 info.putString("shortMsg", "Process crashed."); 3246 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 3247 }); 3248 } 3249 3250 @GuardedBy(anyOf = {"this", "mProcLock"}) getRecordForAppLOSP(IApplicationThread thread)3251 ProcessRecord getRecordForAppLOSP(IApplicationThread thread) { 3252 if (thread == null) { 3253 return null; 3254 } 3255 3256 ProcessRecord record = mProcessList.getLRURecordForAppLOSP(thread); 3257 if (record != null) return record; 3258 3259 // Validation: if it isn't in the LRU list, it shouldn't exist, but let's 3260 // double-check that. 3261 final IBinder threadBinder = thread.asBinder(); 3262 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 3263 mProcessList.getProcessNamesLOSP().getMap(); 3264 for (int i = pmap.size()-1; i >= 0; i--) { 3265 final SparseArray<ProcessRecord> procs = pmap.valueAt(i); 3266 for (int j = procs.size()-1; j >= 0; j--) { 3267 final ProcessRecord proc = procs.valueAt(j); 3268 final IApplicationThread procThread = proc.getThread(); 3269 if (procThread != null && procThread.asBinder() == threadBinder) { 3270 Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: " 3271 + proc); 3272 return proc; 3273 } 3274 } 3275 } 3276 3277 return null; 3278 } 3279 3280 @GuardedBy("this") appDiedLocked(ProcessRecord app, String reason)3281 final void appDiedLocked(ProcessRecord app, String reason) { 3282 appDiedLocked(app, app.getPid(), app.getThread(), false, reason); 3283 } 3284 3285 @GuardedBy("this") appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied, String reason)3286 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, 3287 boolean fromBinderDied, String reason) { 3288 // First check if this ProcessRecord is actually active for the pid. 3289 final ProcessRecord curProc; 3290 synchronized (mPidsSelfLocked) { 3291 curProc = mPidsSelfLocked.get(pid); 3292 } 3293 if (curProc != app) { 3294 if (!fromBinderDied || !mProcessList.handleDyingAppDeathLocked(app, pid)) { 3295 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc); 3296 } 3297 return; 3298 } 3299 3300 mBatteryStatsService.noteProcessDied(app.info.uid, pid); 3301 3302 if (!app.isKilled()) { 3303 if (!fromBinderDied) { 3304 killProcessQuiet(pid); 3305 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_OTHER, 3306 ApplicationExitInfo.SUBREASON_UNKNOWN, reason); 3307 } 3308 ProcessList.killProcessGroup(app.uid, pid); 3309 synchronized (mProcLock) { 3310 app.setKilled(true); 3311 } 3312 } 3313 3314 // Clean up already done if the process has been re-started. 3315 IApplicationThread appThread; 3316 final int setAdj = app.mState.getSetAdj(); 3317 final int setProcState = app.mState.getSetProcState(); 3318 if (app.getPid() == pid && (appThread = app.getThread()) != null 3319 && appThread.asBinder() == thread.asBinder()) { 3320 boolean doLowMem = app.getActiveInstrumentation() == null; 3321 boolean doOomAdj = doLowMem; 3322 if (!app.isKilledByAm()) { 3323 reportUidInfoMessageLocked(TAG, 3324 "Process " + app.processName + " (pid " + pid + ") has died: " 3325 + ProcessList.makeOomAdjString(setAdj, true) + " " 3326 + ProcessList.makeProcStateString(setProcState), app.info.uid); 3327 mAppProfiler.setAllowLowerMemLevelLocked(true); 3328 } else { 3329 // Note that we always want to do oom adj to update our state with the 3330 // new number of procs. 3331 mAppProfiler.setAllowLowerMemLevelLocked(false); 3332 doLowMem = false; 3333 } 3334 EventLogTags.writeAmProcDied(app.userId, pid, app.processName, setAdj, setProcState); 3335 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 3336 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder()); 3337 handleAppDiedLocked(app, pid, false, true, fromBinderDied); 3338 3339 if (doOomAdj) { 3340 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END); 3341 } 3342 if (doLowMem) { 3343 mAppProfiler.doLowMemReportIfNeededLocked(app); 3344 } 3345 } else if (app.getPid() != pid) { 3346 // A new process has already been started. 3347 reportUidInfoMessageLocked(TAG, 3348 "Process " + app.processName + " (pid " + pid 3349 + ") has died and restarted (pid " + app.getPid() + ").", app.info.uid); 3350 3351 EventLogTags.writeAmProcDied(app.userId, app.getPid(), app.processName, 3352 setAdj, setProcState); 3353 } else if (DEBUG_PROCESSES) { 3354 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread " 3355 + thread.asBinder()); 3356 } 3357 3358 // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal 3359 // for pulling memory stats of other running processes when this process died. 3360 if (!hasMemcg()) { 3361 FrameworkStatsLog.write(FrameworkStatsLog.APP_DIED, SystemClock.elapsedRealtime()); 3362 } 3363 } 3364 3365 /** 3366 * If a stack trace dump file is configured, dump process stack traces. 3367 * @param firstPids of dalvik VM processes to dump stack traces for first 3368 * @param lastPids of dalvik VM processes to dump stack traces for last 3369 * @param nativePids optional list of native pids to dump stack crawls 3370 * @param logExceptionCreatingFile optional writer to which we log errors creating the file 3371 */ dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile)3372 public static File dumpStackTraces(ArrayList<Integer> firstPids, 3373 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 3374 ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile) { 3375 return dumpStackTraces(firstPids, processCpuTracker, lastPids, nativePids, 3376 logExceptionCreatingFile, null, null, null); 3377 } 3378 3379 /** 3380 * If a stack trace dump file is configured, dump process stack traces. 3381 * @param firstPids of dalvik VM processes to dump stack traces for first 3382 * @param lastPids of dalvik VM processes to dump stack traces for last 3383 * @param nativePids optional list of native pids to dump stack crawls 3384 * @param logExceptionCreatingFile optional writer to which we log errors creating the file 3385 * @param subject optional line related to the error 3386 * @param criticalEventSection optional lines containing recent critical events. 3387 */ dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, String subject, String criticalEventSection)3388 public static File dumpStackTraces(ArrayList<Integer> firstPids, 3389 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 3390 ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, 3391 String subject, String criticalEventSection) { 3392 return dumpStackTraces(firstPids, processCpuTracker, lastPids, nativePids, 3393 logExceptionCreatingFile, null, subject, criticalEventSection); 3394 } 3395 3396 /** 3397 * @param firstPidOffsets Optional, when it's set, it receives the start/end offset 3398 * of the very first pid to be dumped. 3399 */ dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, long[] firstPidOffsets, String subject, String criticalEventSection)3400 /* package */ static File dumpStackTraces(ArrayList<Integer> firstPids, 3401 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 3402 ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, 3403 long[] firstPidOffsets, String subject, String criticalEventSection) { 3404 ArrayList<Integer> extraPids = null; 3405 3406 Slog.i(TAG, "dumpStackTraces pids=" + lastPids + " nativepids=" + nativePids); 3407 3408 // Measure CPU usage as soon as we're called in order to get a realistic sampling 3409 // of the top users at the time of the request. 3410 if (processCpuTracker != null) { 3411 processCpuTracker.init(); 3412 try { 3413 Thread.sleep(200); 3414 } catch (InterruptedException ignored) { 3415 } 3416 3417 processCpuTracker.update(); 3418 3419 // We'll take the stack crawls of just the top apps using CPU. 3420 final int N = processCpuTracker.countWorkingStats(); 3421 extraPids = new ArrayList<>(); 3422 for (int i = 0; i < N && extraPids.size() < 5; i++) { 3423 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i); 3424 if (lastPids.indexOfKey(stats.pid) >= 0) { 3425 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid); 3426 3427 extraPids.add(stats.pid); 3428 } else { 3429 Slog.i(TAG, "Skipping next CPU consuming process, not a java proc: " 3430 + stats.pid); 3431 } 3432 } 3433 } 3434 3435 final File tracesDir = new File(ANR_TRACE_DIR); 3436 // Each set of ANR traces is written to a separate file and dumpstate will process 3437 // all such files and add them to a captured bug report if they're recent enough. 3438 maybePruneOldTraces(tracesDir); 3439 3440 // NOTE: We should consider creating the file in native code atomically once we've 3441 // gotten rid of the old scheme of dumping and lot of the code that deals with paths 3442 // can be removed. 3443 File tracesFile; 3444 try { 3445 tracesFile = createAnrDumpFile(tracesDir); 3446 } catch (IOException e) { 3447 Slog.w(TAG, "Exception creating ANR dump file:", e); 3448 if (logExceptionCreatingFile != null) { 3449 logExceptionCreatingFile.append("----- Exception creating ANR dump file -----\n"); 3450 e.printStackTrace(new PrintWriter(logExceptionCreatingFile)); 3451 } 3452 return null; 3453 } 3454 3455 if (subject != null || criticalEventSection != null) { 3456 try (FileOutputStream fos = new FileOutputStream(tracesFile, true)) { 3457 if (subject != null) { 3458 String header = "Subject: " + subject + "\n\n"; 3459 fos.write(header.getBytes(StandardCharsets.UTF_8)); 3460 } 3461 if (criticalEventSection != null) { 3462 fos.write(criticalEventSection.getBytes(StandardCharsets.UTF_8)); 3463 } 3464 } catch (IOException e) { 3465 Slog.w(TAG, "Exception writing to ANR dump file:", e); 3466 } 3467 } 3468 3469 Pair<Long, Long> offsets = dumpStackTraces( 3470 tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids); 3471 if (firstPidOffsets != null) { 3472 if (offsets == null) { 3473 firstPidOffsets[0] = firstPidOffsets[1] = -1; 3474 } else { 3475 firstPidOffsets[0] = offsets.first; // Start offset to the ANR trace file 3476 firstPidOffsets[1] = offsets.second; // End offset to the ANR trace file 3477 } 3478 } 3479 return tracesFile; 3480 } 3481 3482 @GuardedBy("ActivityManagerService.class") 3483 private static SimpleDateFormat sAnrFileDateFormat; 3484 static final String ANR_FILE_PREFIX = "anr_"; 3485 createAnrDumpFile(File tracesDir)3486 private static synchronized File createAnrDumpFile(File tracesDir) throws IOException { 3487 if (sAnrFileDateFormat == null) { 3488 sAnrFileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS"); 3489 } 3490 3491 final String formattedDate = sAnrFileDateFormat.format(new Date()); 3492 final File anrFile = new File(tracesDir, ANR_FILE_PREFIX + formattedDate); 3493 3494 if (anrFile.createNewFile()) { 3495 FileUtils.setPermissions(anrFile.getAbsolutePath(), 0600, -1, -1); // -rw------- 3496 return anrFile; 3497 } else { 3498 throw new IOException("Unable to create ANR dump file: createNewFile failed"); 3499 } 3500 } 3501 3502 /** 3503 * Prune all trace files that are more than a day old. 3504 * 3505 * NOTE: It might make sense to move this functionality to tombstoned eventually, along with a 3506 * shift away from anr_XX and tombstone_XX to a more descriptive name. We do it here for now 3507 * since it's the system_server that creates trace files for most ANRs. 3508 */ maybePruneOldTraces(File tracesDir)3509 private static void maybePruneOldTraces(File tracesDir) { 3510 final File[] files = tracesDir.listFiles(); 3511 if (files == null) return; 3512 3513 final int max = SystemProperties.getInt("tombstoned.max_anr_count", 64); 3514 final long now = System.currentTimeMillis(); 3515 try { 3516 Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed()); 3517 for (int i = 0; i < files.length; ++i) { 3518 if (i > max || (now - files[i].lastModified()) > DAY_IN_MILLIS) { 3519 if (!files[i].delete()) { 3520 Slog.w(TAG, "Unable to prune stale trace file: " + files[i]); 3521 } 3522 } 3523 } 3524 } catch (IllegalArgumentException e) { 3525 // The modification times changed while we were sorting. Bail... 3526 // https://issuetracker.google.com/169836837 3527 Slog.w(TAG, "tombstone modification times changed while sorting; not pruning", e); 3528 } 3529 } 3530 3531 /** 3532 * Dump java traces for process {@code pid} to the specified file. If java trace dumping 3533 * fails, a native backtrace is attempted. Note that the timeout {@code timeoutMs} only applies 3534 * to the java section of the trace, a further {@code NATIVE_DUMP_TIMEOUT_MS} might be spent 3535 * attempting to obtain native traces in the case of a failure. Returns the total time spent 3536 * capturing traces. 3537 */ dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs)3538 private static long dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs) { 3539 final long timeStart = SystemClock.elapsedRealtime(); 3540 boolean javaSuccess = Debug.dumpJavaBacktraceToFileTimeout(pid, fileName, 3541 (int) (timeoutMs / 1000)); 3542 if (javaSuccess) { 3543 // Check that something is in the file, actually. Try-catch should not be necessary, 3544 // but better safe than sorry. 3545 try { 3546 long size = new File(fileName).length(); 3547 if (size < JAVA_DUMP_MINIMUM_SIZE) { 3548 Slog.w(TAG, "Successfully created Java ANR file is empty!"); 3549 javaSuccess = false; 3550 } 3551 } catch (Exception e) { 3552 Slog.w(TAG, "Unable to get ANR file size", e); 3553 javaSuccess = false; 3554 } 3555 } 3556 if (!javaSuccess) { 3557 Slog.w(TAG, "Dumping Java threads failed, initiating native stack dump."); 3558 if (!Debug.dumpNativeBacktraceToFileTimeout(pid, fileName, 3559 (NATIVE_DUMP_TIMEOUT_MS / 1000))) { 3560 Slog.w(TAG, "Native stack dump failed!"); 3561 } 3562 } 3563 3564 return SystemClock.elapsedRealtime() - timeStart; 3565 } 3566 3567 /** 3568 * @return The start/end offset of the trace of the very first PID 3569 */ dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, ArrayList<Integer> nativePids, ArrayList<Integer> extraPids)3570 public static Pair<Long, Long> dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, 3571 ArrayList<Integer> nativePids, ArrayList<Integer> extraPids) { 3572 3573 Slog.i(TAG, "Dumping to " + tracesFile); 3574 3575 // We don't need any sort of inotify based monitoring when we're dumping traces via 3576 // tombstoned. Data is piped to an "intercept" FD installed in tombstoned so we're in full 3577 // control of all writes to the file in question. 3578 3579 // We must complete all stack dumps within 20 seconds. 3580 long remainingTime = 20 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 3581 3582 // As applications are usually interested with the ANR stack traces, but we can't share with 3583 // them the stack traces other than their own stacks. So after the very first PID is 3584 // dumped, remember the current file size. 3585 long firstPidStart = -1; 3586 long firstPidEnd = -1; 3587 3588 // First collect all of the stacks of the most important pids. 3589 if (firstPids != null) { 3590 int num = firstPids.size(); 3591 for (int i = 0; i < num; i++) { 3592 final int pid = firstPids.get(i); 3593 // We don't copy ANR traces from the system_server intentionally. 3594 final boolean firstPid = i == 0 && MY_PID != pid; 3595 File tf = null; 3596 if (firstPid) { 3597 tf = new File(tracesFile); 3598 firstPidStart = tf.exists() ? tf.length() : 0; 3599 } 3600 3601 Slog.i(TAG, "Collecting stacks for pid " + pid); 3602 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, 3603 remainingTime); 3604 3605 remainingTime -= timeTaken; 3606 if (remainingTime <= 0) { 3607 Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + pid 3608 + "); deadline exceeded."); 3609 return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null; 3610 } 3611 3612 if (firstPid) { 3613 firstPidEnd = tf.length(); 3614 } 3615 if (DEBUG_ANR) { 3616 Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms"); 3617 } 3618 } 3619 } 3620 3621 // Next collect the stacks of the native pids 3622 if (nativePids != null) { 3623 for (int pid : nativePids) { 3624 Slog.i(TAG, "Collecting stacks for native pid " + pid); 3625 final long nativeDumpTimeoutMs = Math.min(NATIVE_DUMP_TIMEOUT_MS, remainingTime); 3626 3627 final long start = SystemClock.elapsedRealtime(); 3628 Debug.dumpNativeBacktraceToFileTimeout( 3629 pid, tracesFile, (int) (nativeDumpTimeoutMs / 1000)); 3630 final long timeTaken = SystemClock.elapsedRealtime() - start; 3631 3632 remainingTime -= timeTaken; 3633 if (remainingTime <= 0) { 3634 Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid + 3635 "); deadline exceeded."); 3636 return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null; 3637 } 3638 3639 if (DEBUG_ANR) { 3640 Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms"); 3641 } 3642 } 3643 } 3644 3645 // Lastly, dump stacks for all extra PIDs from the CPU tracker. 3646 if (extraPids != null) { 3647 for (int pid : extraPids) { 3648 Slog.i(TAG, "Collecting stacks for extra pid " + pid); 3649 3650 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, remainingTime); 3651 3652 remainingTime -= timeTaken; 3653 if (remainingTime <= 0) { 3654 Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + pid + 3655 "); deadline exceeded."); 3656 return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null; 3657 } 3658 3659 if (DEBUG_ANR) { 3660 Slog.d(TAG, "Done with extra pid " + pid + " in " + timeTaken + "ms"); 3661 } 3662 } 3663 } 3664 Slog.i(TAG, "Done dumping"); 3665 return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null; 3666 } 3667 3668 @Override clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)3669 public boolean clearApplicationUserData(final String packageName, boolean keepState, 3670 final IPackageDataObserver observer, int userId) { 3671 enforceNotIsolatedCaller("clearApplicationUserData"); 3672 int uid = Binder.getCallingUid(); 3673 int pid = Binder.getCallingPid(); 3674 final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false, 3675 ALLOW_FULL_ONLY, "clearApplicationUserData", null); 3676 3677 final ApplicationInfo appInfo; 3678 final boolean isInstantApp; 3679 3680 final long callingId = Binder.clearCallingIdentity(); 3681 try { 3682 IPackageManager pm = AppGlobals.getPackageManager(); 3683 boolean permitted = true; 3684 // Instant packages are not protected 3685 if (getPackageManagerInternal().isPackageDataProtected( 3686 resolvedUserId, packageName)) { 3687 if (ActivityManager.checkUidPermission(android.Manifest.permission.MANAGE_USERS, 3688 uid) == PERMISSION_GRANTED) { 3689 // The caller has the MANAGE_USERS permission, tell them what's going on. 3690 throw new SecurityException( 3691 "Cannot clear data for a protected package: " + packageName); 3692 } else { 3693 permitted = false; // fall through and throw the SecurityException below. 3694 } 3695 } 3696 3697 ApplicationInfo applicationInfo = null; 3698 if (permitted) { 3699 try { 3700 applicationInfo = pm.getApplicationInfo(packageName, 3701 MATCH_UNINSTALLED_PACKAGES, resolvedUserId); 3702 } catch (RemoteException e) { 3703 /* ignore */ 3704 } 3705 permitted = (applicationInfo != null && applicationInfo.uid == uid) // own uid data 3706 || (checkComponentPermission(permission.CLEAR_APP_USER_DATA, 3707 pid, uid, -1, true) == PackageManager.PERMISSION_GRANTED); 3708 } 3709 3710 if (!permitted) { 3711 throw new SecurityException("PID " + pid + " does not have permission " 3712 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 3713 + " of package " + packageName); 3714 } 3715 appInfo = applicationInfo; 3716 3717 final boolean hasInstantMetadata = getPackageManagerInternal() 3718 .hasInstantApplicationMetadata(packageName, resolvedUserId); 3719 final boolean isUninstalledAppWithoutInstantMetadata = 3720 (appInfo == null && !hasInstantMetadata); 3721 isInstantApp = (appInfo != null && appInfo.isInstantApp()) 3722 || hasInstantMetadata; 3723 final boolean canAccessInstantApps = checkComponentPermission( 3724 permission.ACCESS_INSTANT_APPS, pid, uid, -1, true) 3725 == PackageManager.PERMISSION_GRANTED; 3726 3727 if (isUninstalledAppWithoutInstantMetadata || (isInstantApp 3728 && !canAccessInstantApps)) { 3729 Slog.w(TAG, "Invalid packageName: " + packageName); 3730 if (observer != null) { 3731 try { 3732 observer.onRemoveCompleted(packageName, false); 3733 } catch (RemoteException e) { 3734 Slog.i(TAG, "Observer no longer exists."); 3735 } 3736 } 3737 return false; 3738 } 3739 3740 synchronized (this) { 3741 if (appInfo != null) { 3742 forceStopPackageLocked(packageName, appInfo.uid, "clear data"); 3743 mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId); 3744 } 3745 } 3746 3747 final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() { 3748 @Override 3749 public void onRemoveCompleted(String packageName, boolean succeeded) 3750 throws RemoteException { 3751 if (appInfo != null) { 3752 synchronized (ActivityManagerService.this) { 3753 finishForceStopPackageLocked(packageName, appInfo.uid); 3754 } 3755 } 3756 3757 if (succeeded) { 3758 final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 3759 Uri.fromParts("package", packageName, null /* fragment */)); 3760 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 3761 intent.putExtra(Intent.EXTRA_UID, 3762 (appInfo != null) ? appInfo.uid : INVALID_UID); 3763 intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId); 3764 if (isInstantApp) { 3765 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName); 3766 } 3767 final int[] visibilityAllowList = mPackageManagerInt.getVisibilityAllowList( 3768 packageName, resolvedUserId); 3769 3770 broadcastIntentInPackage("android", null /* featureId */, SYSTEM_UID, 3771 uid, pid, intent, null /* resolvedType */, null /* resultTo */, 3772 0 /* resultCode */, null /* resultData */, null /* resultExtras */, 3773 isInstantApp ? permission.ACCESS_INSTANT_APPS : null, 3774 null /* bOptions */, false /* serialized */, false /* sticky */, 3775 resolvedUserId, false /* allowBackgroundActivityStarts */, 3776 null /* backgroundActivityStartsToken */, visibilityAllowList); 3777 } 3778 3779 if (observer != null) { 3780 observer.onRemoveCompleted(packageName, succeeded); 3781 } 3782 } 3783 }; 3784 3785 try { 3786 // Clear application user data 3787 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId); 3788 3789 if (appInfo != null) { 3790 // Restore already established notification state and permission grants, 3791 // so it told us to keep those intact -- it's about to emplace app data 3792 // that is appropriate for those bits of system state. 3793 if (!keepState) { 3794 // Remove all permissions granted from/to this package 3795 mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId, 3796 true, false); 3797 3798 // Reset notification state 3799 INotificationManager inm = NotificationManager.getService(); 3800 inm.clearData(packageName, appInfo.uid, uid == appInfo.uid); 3801 } 3802 3803 // Clear its scheduled jobs 3804 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 3805 // Clearing data is a user-initiated action. 3806 js.cancelJobsForUid(appInfo.uid, JobParameters.STOP_REASON_USER, 3807 JobParameters.INTERNAL_STOP_REASON_DATA_CLEARED, "clear data"); 3808 3809 // Clear its pending alarms 3810 AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class); 3811 ami.removeAlarmsForUid(appInfo.uid); 3812 } 3813 } catch (RemoteException e) { 3814 } 3815 } finally { 3816 Binder.restoreCallingIdentity(callingId); 3817 } 3818 return true; 3819 } 3820 3821 @Override killBackgroundProcesses(final String packageName, int userId)3822 public void killBackgroundProcesses(final String packageName, int userId) { 3823 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3824 != PackageManager.PERMISSION_GRANTED && 3825 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 3826 != PackageManager.PERMISSION_GRANTED) { 3827 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 3828 + Binder.getCallingPid() 3829 + ", uid=" + Binder.getCallingUid() 3830 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3831 Slog.w(TAG, msg); 3832 throw new SecurityException(msg); 3833 } 3834 final int callingUid = Binder.getCallingUid(); 3835 final int callingPid = Binder.getCallingPid(); 3836 final int callingAppId = UserHandle.getAppId(callingUid); 3837 3838 ProcessRecord proc; 3839 synchronized (mPidsSelfLocked) { 3840 proc = mPidsSelfLocked.get(callingPid); 3841 } 3842 final boolean hasKillAllPermission = PERMISSION_GRANTED == checkPermission( 3843 android.Manifest.permission.FORCE_STOP_PACKAGES, callingPid, callingUid) 3844 || UserHandle.isCore(callingUid) 3845 || (proc != null && proc.info.isSystemApp()); 3846 3847 userId = mUserController.handleIncomingUser(callingPid, callingUid, 3848 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 3849 final int[] userIds = mUserController.expandUserId(userId); 3850 3851 final long callingId = Binder.clearCallingIdentity(); 3852 try { 3853 IPackageManager pm = AppGlobals.getPackageManager(); 3854 for (int targetUserId : userIds) { 3855 int appId = -1; 3856 try { 3857 appId = UserHandle.getAppId( 3858 pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 3859 targetUserId)); 3860 } catch (RemoteException e) { 3861 } 3862 if (appId == -1 || (!hasKillAllPermission && appId != callingAppId)) { 3863 Slog.w(TAG, "Invalid packageName: " + packageName); 3864 return; 3865 } 3866 synchronized (this) { 3867 synchronized (mProcLock) { 3868 mProcessList.killPackageProcessesLSP(packageName, appId, targetUserId, 3869 ProcessList.SERVICE_ADJ, ApplicationExitInfo.REASON_USER_REQUESTED, 3870 ApplicationExitInfo.SUBREASON_KILL_BACKGROUND, "kill background"); 3871 } 3872 } 3873 } 3874 } finally { 3875 Binder.restoreCallingIdentity(callingId); 3876 } 3877 } 3878 3879 @Override killAllBackgroundProcesses()3880 public void killAllBackgroundProcesses() { 3881 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3882 != PackageManager.PERMISSION_GRANTED) { 3883 final String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 3884 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3885 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3886 Slog.w(TAG, msg); 3887 throw new SecurityException(msg); 3888 } 3889 3890 final int callingUid = Binder.getCallingUid(); 3891 final int callingPid = Binder.getCallingPid(); 3892 3893 ProcessRecord proc; 3894 synchronized (mPidsSelfLocked) { 3895 proc = mPidsSelfLocked.get(callingPid); 3896 } 3897 if (callingUid >= FIRST_APPLICATION_UID 3898 && (proc == null || !proc.info.isSystemApp())) { 3899 final String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 3900 + callingPid + ", uid=" + callingUid + " is not allowed"; 3901 Slog.w(TAG, msg); 3902 // Silently return to avoid existing apps from crashing. 3903 return; 3904 } 3905 3906 final long callingId = Binder.clearCallingIdentity(); 3907 try { 3908 synchronized (this) { 3909 // Allow memory level to go down (the flag needs to be set before updating oom adj) 3910 // because this method is also used to simulate low memory. 3911 mAppProfiler.setAllowLowerMemLevelLocked(true); 3912 synchronized (mProcLock) { 3913 mProcessList.killPackageProcessesLSP(null /* packageName */, -1 /* appId */, 3914 UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ, 3915 ApplicationExitInfo.REASON_USER_REQUESTED, 3916 ApplicationExitInfo.SUBREASON_KILL_BACKGROUND, 3917 "kill all background"); 3918 } 3919 3920 mAppProfiler.doLowMemReportIfNeededLocked(null); 3921 } 3922 } finally { 3923 Binder.restoreCallingIdentity(callingId); 3924 } 3925 } 3926 3927 /** 3928 * Kills all background processes, except those matching any of the 3929 * specified properties. 3930 * 3931 * @param minTargetSdk the target SDK version at or above which to preserve 3932 * processes, or {@code -1} to ignore the target SDK 3933 * @param maxProcState the process state at or below which to preserve 3934 * processes, or {@code -1} to ignore the process state 3935 */ killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)3936 void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 3937 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3938 != PackageManager.PERMISSION_GRANTED) { 3939 final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid=" 3940 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3941 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3942 Slog.w(TAG, msg); 3943 throw new SecurityException(msg); 3944 } 3945 3946 final long callingId = Binder.clearCallingIdentity(); 3947 try { 3948 synchronized (this) { 3949 synchronized (mProcLock) { 3950 mProcessList.killAllBackgroundProcessesExceptLSP(minTargetSdk, maxProcState); 3951 } 3952 } 3953 } finally { 3954 Binder.restoreCallingIdentity(callingId); 3955 } 3956 } 3957 3958 @Override stopAppForUser(final String packageName, int userId)3959 public void stopAppForUser(final String packageName, int userId) { 3960 if (checkCallingPermission(MANAGE_ACTIVITY_TASKS) 3961 != PackageManager.PERMISSION_GRANTED) { 3962 String msg = "Permission Denial: stopAppForUser() from pid=" 3963 + Binder.getCallingPid() 3964 + ", uid=" + Binder.getCallingUid() 3965 + " requires " + MANAGE_ACTIVITY_TASKS; 3966 Slog.w(TAG, msg); 3967 throw new SecurityException(msg); 3968 } 3969 3970 final int callingPid = Binder.getCallingPid(); 3971 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 3972 userId, true, ALLOW_FULL_ONLY, "stopAppForUser", null); 3973 final long callingId = Binder.clearCallingIdentity(); 3974 try { 3975 stopAppForUserInternal(packageName, userId); 3976 } finally { 3977 Binder.restoreCallingIdentity(callingId); 3978 } 3979 } 3980 3981 @Override registerForegroundServiceObserver(IForegroundServiceObserver callback)3982 public boolean registerForegroundServiceObserver(IForegroundServiceObserver callback) { 3983 final int callingUid = Binder.getCallingUid(); 3984 final int permActivityTasks = checkCallingPermission(MANAGE_ACTIVITY_TASKS); 3985 final int permAcrossUsersFull = checkCallingPermission(INTERACT_ACROSS_USERS_FULL); 3986 if (permActivityTasks != PackageManager.PERMISSION_GRANTED 3987 || permAcrossUsersFull != PERMISSION_GRANTED) { 3988 String msg = "Permission Denial: registerForegroundServiceObserver() from pid=" 3989 + Binder.getCallingPid() 3990 + ", uid=" + callingUid 3991 + " requires " + MANAGE_ACTIVITY_TASKS 3992 + " and " + INTERACT_ACROSS_USERS_FULL; 3993 Slog.w(TAG, msg); 3994 throw new SecurityException(msg); 3995 } 3996 3997 synchronized (this) { 3998 return mServices.registerForegroundServiceObserverLocked(callingUid, callback); 3999 } 4000 } 4001 4002 @Override forceStopPackage(final String packageName, int userId)4003 public void forceStopPackage(final String packageName, int userId) { 4004 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4005 != PackageManager.PERMISSION_GRANTED) { 4006 String msg = "Permission Denial: forceStopPackage() from pid=" 4007 + Binder.getCallingPid() 4008 + ", uid=" + Binder.getCallingUid() 4009 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 4010 Slog.w(TAG, msg); 4011 throw new SecurityException(msg); 4012 } 4013 final int callingPid = Binder.getCallingPid(); 4014 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 4015 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 4016 final long callingId = Binder.clearCallingIdentity(); 4017 try { 4018 IPackageManager pm = AppGlobals.getPackageManager(); 4019 synchronized(this) { 4020 int[] users = userId == UserHandle.USER_ALL 4021 ? mUserController.getUsers() : new int[] { userId }; 4022 for (int user : users) { 4023 if (getPackageManagerInternal().isPackageStateProtected( 4024 packageName, user)) { 4025 Slog.w(TAG, "Ignoring request to force stop protected package " 4026 + packageName + " u" + user); 4027 return; 4028 } 4029 4030 int pkgUid = -1; 4031 try { 4032 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 4033 user); 4034 } catch (RemoteException e) { 4035 } 4036 if (pkgUid == -1) { 4037 Slog.w(TAG, "Invalid packageName: " + packageName); 4038 continue; 4039 } 4040 try { 4041 pm.setPackageStoppedState(packageName, true, user); 4042 } catch (RemoteException e) { 4043 } catch (IllegalArgumentException e) { 4044 Slog.w(TAG, "Failed trying to unstop package " 4045 + packageName + ": " + e); 4046 } 4047 if (mUserController.isUserRunning(user, 0)) { 4048 forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid); 4049 finishForceStopPackageLocked(packageName, pkgUid); 4050 } 4051 } 4052 } 4053 } finally { 4054 Binder.restoreCallingIdentity(callingId); 4055 } 4056 } 4057 4058 @Override addPackageDependency(String packageName)4059 public void addPackageDependency(String packageName) { 4060 int callingPid = Binder.getCallingPid(); 4061 if (callingPid == myPid()) { 4062 // Yeah, um, no. 4063 return; 4064 } 4065 ProcessRecord proc; 4066 synchronized (mPidsSelfLocked) { 4067 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 4068 } 4069 if (proc != null) { 4070 ArraySet<String> pkgDeps = proc.getPkgDeps(); 4071 synchronized (this) { 4072 synchronized (mProcLock) { 4073 if (pkgDeps == null) { 4074 proc.setPkgDeps(pkgDeps = new ArraySet<String>(1)); 4075 } 4076 pkgDeps.add(packageName); 4077 } 4078 } 4079 } 4080 } 4081 4082 /* 4083 * The pkg name and app id have to be specified. 4084 */ 4085 @Override killApplication(String pkg, int appId, int userId, String reason)4086 public void killApplication(String pkg, int appId, int userId, String reason) { 4087 if (pkg == null) { 4088 return; 4089 } 4090 // Make sure the uid is valid. 4091 if (appId < 0) { 4092 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 4093 return; 4094 } 4095 int callerUid = Binder.getCallingUid(); 4096 // Only the system server can kill an application 4097 if (UserHandle.getAppId(callerUid) == SYSTEM_UID) { 4098 // Post an aysnc message to kill the application 4099 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 4100 msg.arg1 = appId; 4101 msg.arg2 = userId; 4102 Bundle bundle = new Bundle(); 4103 bundle.putString("pkg", pkg); 4104 bundle.putString("reason", reason); 4105 msg.obj = bundle; 4106 mHandler.sendMessage(msg); 4107 } else { 4108 throw new SecurityException(callerUid + " cannot kill pkg: " + 4109 pkg); 4110 } 4111 } 4112 4113 @Override closeSystemDialogs(String reason)4114 public void closeSystemDialogs(String reason) { 4115 mAtmInternal.closeSystemDialogs(reason); 4116 } 4117 4118 @Override getProcessMemoryInfo(int[] pids)4119 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 4120 enforceNotIsolatedCaller("getProcessMemoryInfo"); 4121 4122 final long now = SystemClock.uptimeMillis(); 4123 final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME; 4124 4125 final int callingPid = Binder.getCallingPid(); 4126 final int callingUid = Binder.getCallingUid(); 4127 final int callingUserId = UserHandle.getUserId(callingUid); 4128 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 4129 callingUid) == PackageManager.PERMISSION_GRANTED; 4130 // Check REAL_GET_TASKS to see if they are allowed to access other uids 4131 final boolean allUids = mAtmInternal.isGetTasksAllowed( 4132 "getProcessMemoryInfo", callingPid, callingUid); 4133 4134 // Check if the caller is actually instrumented and from shell, if it's true, we may lift 4135 // the throttle of PSS info sampling. 4136 boolean isCallerInstrumentedFromShell = false; 4137 synchronized (mProcLock) { 4138 synchronized (mPidsSelfLocked) { 4139 ProcessRecord caller = mPidsSelfLocked.get(callingPid); 4140 if (caller != null) { 4141 final ActiveInstrumentation instr = caller.getActiveInstrumentation(); 4142 isCallerInstrumentedFromShell = instr != null 4143 && (instr.mSourceUid == SHELL_UID || instr.mSourceUid == ROOT_UID); 4144 } 4145 } 4146 } 4147 4148 final Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 4149 for (int i=pids.length-1; i>=0; i--) { 4150 final Debug.MemoryInfo mi = infos[i] = new Debug.MemoryInfo(); 4151 final ProcessRecord proc; 4152 final int oomAdj; 4153 final ProcessProfileRecord profile; 4154 synchronized (mAppProfiler.mProfilerLock) { 4155 synchronized (mPidsSelfLocked) { 4156 proc = mPidsSelfLocked.get(pids[i]); 4157 if (proc != null) { 4158 profile = proc.mProfile; 4159 oomAdj = profile.getSetAdj(); 4160 } else { 4161 profile = null; 4162 oomAdj = 0; 4163 } 4164 } 4165 } 4166 final int targetUid = (proc != null) ? proc.uid : -1; 4167 final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1; 4168 4169 if (callingUid != targetUid) { 4170 if (!allUids) { 4171 continue; // Not allowed to see other UIDs. 4172 } 4173 4174 if (!allUsers && (targetUserId != callingUserId)) { 4175 continue; // Not allowed to see other users. 4176 } 4177 } 4178 if (proc != null) { 4179 synchronized (mAppProfiler.mProfilerLock) { 4180 if (profile.getLastMemInfoTime() >= lastNow && profile.getLastMemInfo() != null 4181 && !isCallerInstrumentedFromShell) { 4182 // It hasn't been long enough that we want to take another sample; return 4183 // the last one. 4184 mi.set(profile.getLastMemInfo()); 4185 continue; 4186 } 4187 } 4188 } 4189 final long startTime = SystemClock.currentThreadTimeMillis(); 4190 final Debug.MemoryInfo memInfo = new Debug.MemoryInfo(); 4191 Debug.getMemoryInfo(pids[i], memInfo); 4192 final long duration = SystemClock.currentThreadTimeMillis() - startTime; 4193 mi.set(memInfo); 4194 if (proc != null) { 4195 synchronized (mAppProfiler.mProfilerLock) { 4196 profile.setLastMemInfo(memInfo); 4197 profile.setLastMemInfoTime(SystemClock.uptimeMillis()); 4198 if (profile.getThread() != null && profile.getSetAdj() == oomAdj) { 4199 // Record this for posterity if the process has been stable. 4200 profile.addPss(mi.getTotalPss(), 4201 mi.getTotalUss(), mi.getTotalRss(), false, 4202 ProcessStats.ADD_PSS_EXTERNAL_SLOW, duration); 4203 proc.getPkgList().forEachPackageProcessStats(holder -> { 4204 final ProcessState state = holder.state; 4205 FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED, 4206 proc.info.uid, 4207 state != null ? state.getName() : proc.processName, 4208 state != null ? state.getPackage() : proc.info.packageName, 4209 mi.getTotalPss(), 4210 mi.getTotalUss(), 4211 mi.getTotalRss(), 4212 ProcessStats.ADD_PSS_EXTERNAL_SLOW, 4213 duration, 4214 holder.appVersion, 4215 profile.getCurrentHostingComponentTypes(), 4216 profile.getHistoricalHostingComponentTypes()); 4217 }); 4218 } 4219 } 4220 } 4221 } 4222 return infos; 4223 } 4224 4225 @Override getProcessPss(int[] pids)4226 public long[] getProcessPss(int[] pids) { 4227 enforceNotIsolatedCaller("getProcessPss"); 4228 4229 final int callingPid = Binder.getCallingPid(); 4230 final int callingUid = Binder.getCallingUid(); 4231 final int userId = UserHandle.getUserId(callingUid); 4232 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 4233 callingUid) == PackageManager.PERMISSION_GRANTED; 4234 // Check REAL_GET_TASKS to see if they are allowed to access other uids 4235 final boolean allUids = mAtmInternal.isGetTasksAllowed( 4236 "getProcessPss", callingPid, callingUid); 4237 4238 final long[] pss = new long[pids.length]; 4239 for (int i=pids.length-1; i>=0; i--) { 4240 ProcessRecord proc; 4241 int oomAdj; 4242 synchronized (mProcLock) { 4243 synchronized (mPidsSelfLocked) { 4244 proc = mPidsSelfLocked.get(pids[i]); 4245 oomAdj = proc != null ? proc.mState.getSetAdj() : 0; 4246 } 4247 } 4248 if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) { 4249 // The caller is not allow to get information about this other process... 4250 // just leave it empty. 4251 continue; 4252 } 4253 final long[] tmpUss = new long[3]; 4254 final long startTime = SystemClock.currentThreadTimeMillis(); 4255 final long pi = pss[i] = Debug.getPss(pids[i], tmpUss, null); 4256 final long duration = SystemClock.currentThreadTimeMillis() - startTime; 4257 if (proc != null) { 4258 final ProcessProfileRecord profile = proc.mProfile; 4259 synchronized (mAppProfiler.mProfilerLock) { 4260 if (profile.getThread() != null && profile.getSetAdj() == oomAdj) { 4261 // Record this for posterity if the process has been stable. 4262 profile.addPss(pi, tmpUss[0], tmpUss[2], false, 4263 ProcessStats.ADD_PSS_EXTERNAL, duration); 4264 proc.getPkgList().forEachPackageProcessStats(holder -> { 4265 FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED, 4266 proc.info.uid, 4267 holder.state.getName(), 4268 holder.state.getPackage(), 4269 pi, 4270 tmpUss[0], 4271 tmpUss[2], 4272 ProcessStats.ADD_PSS_EXTERNAL, 4273 duration, 4274 holder.appVersion, 4275 profile.getCurrentHostingComponentTypes(), 4276 profile.getHistoricalHostingComponentTypes()); 4277 }); 4278 } 4279 } 4280 } 4281 } 4282 return pss; 4283 } 4284 4285 @Override killApplicationProcess(String processName, int uid)4286 public void killApplicationProcess(String processName, int uid) { 4287 if (processName == null) { 4288 return; 4289 } 4290 4291 int callerUid = Binder.getCallingUid(); 4292 // Only the system server can kill an application 4293 if (callerUid == SYSTEM_UID) { 4294 synchronized (this) { 4295 ProcessRecord app = getProcessRecordLocked(processName, uid); 4296 IApplicationThread thread; 4297 if (app != null && (thread = app.getThread()) != null) { 4298 try { 4299 thread.scheduleSuicide(); 4300 } catch (RemoteException e) { 4301 // If the other end already died, then our work here is done. 4302 } 4303 } else { 4304 Slog.w(TAG, "Process/uid not found attempting kill of " 4305 + processName + " / " + uid); 4306 } 4307 } 4308 } else { 4309 throw new SecurityException(callerUid + " cannot kill app process: " + 4310 processName); 4311 } 4312 } 4313 4314 @GuardedBy("this") forceStopPackageLocked(final String packageName, int uid, String reason)4315 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 4316 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 4317 false, true, false, false, UserHandle.getUserId(uid), reason); 4318 } 4319 4320 @GuardedBy("this") finishForceStopPackageLocked(final String packageName, int uid)4321 private void finishForceStopPackageLocked(final String packageName, int uid) { 4322 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 4323 Uri.fromParts("package", packageName, null)); 4324 if (!mProcessesReady) { 4325 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 4326 | Intent.FLAG_RECEIVER_FOREGROUND); 4327 } 4328 intent.putExtra(Intent.EXTRA_UID, uid); 4329 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 4330 broadcastIntentLocked(null, null, null, intent, 4331 null, null, 0, null, null, null, null, null, OP_NONE, 4332 null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(), 4333 Binder.getCallingPid(), UserHandle.getUserId(uid)); 4334 } 4335 cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4336 private void cleanupDisabledPackageComponentsLocked( 4337 String packageName, int userId, String[] changedClasses) { 4338 4339 Set<String> disabledClasses = null; 4340 boolean packageDisabled = false; 4341 IPackageManager pm = AppGlobals.getPackageManager(); 4342 4343 if (changedClasses == null) { 4344 // Nothing changed... 4345 return; 4346 } 4347 4348 // Determine enable/disable state of the package and its components. 4349 int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4350 for (int i = changedClasses.length - 1; i >= 0; i--) { 4351 final String changedClass = changedClasses[i]; 4352 4353 if (changedClass.equals(packageName)) { 4354 try { 4355 // Entire package setting changed 4356 enabled = pm.getApplicationEnabledSetting(packageName, 4357 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4358 } catch (Exception e) { 4359 // No such package/component; probably racing with uninstall. In any 4360 // event it means we have nothing further to do here. 4361 return; 4362 } 4363 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4364 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4365 if (packageDisabled) { 4366 // Entire package is disabled. 4367 // No need to continue to check component states. 4368 disabledClasses = null; 4369 break; 4370 } 4371 } else { 4372 try { 4373 enabled = pm.getComponentEnabledSetting( 4374 new ComponentName(packageName, changedClass), 4375 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4376 } catch (Exception e) { 4377 // As above, probably racing with uninstall. 4378 return; 4379 } 4380 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4381 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) { 4382 if (disabledClasses == null) { 4383 disabledClasses = new ArraySet<>(changedClasses.length); 4384 } 4385 disabledClasses.add(changedClass); 4386 } 4387 } 4388 } 4389 4390 if (!packageDisabled && disabledClasses == null) { 4391 // Nothing to do here... 4392 return; 4393 } 4394 4395 mAtmInternal.cleanupDisabledPackageComponents( 4396 packageName, disabledClasses, userId, mBooted); 4397 4398 // Clean-up disabled services. 4399 mServices.bringDownDisabledPackageServicesLocked( 4400 packageName, disabledClasses, userId, false /* evenPersistent */, 4401 false /* fullStop */, true /* doIt */); 4402 4403 // Clean-up disabled providers. 4404 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4405 mCpHelper.getProviderMap().collectPackageProvidersLocked( 4406 packageName, disabledClasses, true, false, userId, providers); 4407 for (int i = providers.size() - 1; i >= 0; i--) { 4408 mCpHelper.removeDyingProviderLocked(null, providers.get(i), true); 4409 } 4410 4411 // Clean-up disabled broadcast receivers. 4412 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 4413 mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4414 packageName, disabledClasses, userId, true); 4415 } 4416 4417 } 4418 clearBroadcastQueueForUserLocked(int userId)4419 final boolean clearBroadcastQueueForUserLocked(int userId) { 4420 boolean didSomething = false; 4421 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 4422 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4423 null, null, userId, true); 4424 } 4425 return didSomething; 4426 } 4427 4428 @GuardedBy("this") forceStopAppZygoteLocked(String packageName, int appId, int userId)4429 final void forceStopAppZygoteLocked(String packageName, int appId, int userId) { 4430 if (packageName == null) { 4431 return; 4432 } 4433 if (appId < 0) { 4434 appId = UserHandle.getAppId(getPackageManagerInternal().getPackageUid(packageName, 4435 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM)); 4436 } 4437 4438 mProcessList.killAppZygotesLocked(packageName, appId, userId, true /* force */); 4439 } 4440 stopAppForUserInternal(final String packageName, @UserIdInt final int userId)4441 void stopAppForUserInternal(final String packageName, @UserIdInt final int userId) { 4442 final int uid = getPackageManagerInternal().getPackageUid(packageName, 4443 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, userId); 4444 if (uid < 0) { 4445 Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId 4446 + " but does not exist in that user"); 4447 return; 4448 } 4449 4450 // Policy: certain classes of app are not subject to user-invoked stop 4451 if (getPackageManagerInternal().isPackageStateProtected(packageName, userId)) { 4452 Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId 4453 + " but it is protected"); 4454 return; 4455 } 4456 4457 Slog.i(TAG, "Stopping app for user: " + packageName + "/" + userId); 4458 4459 // A specific subset of the work done in forceStopPackageLocked(), because we are 4460 // intentionally not rendering the app nonfunctional; we're just halting its current 4461 // execution. 4462 final int appId = UserHandle.getAppId(uid); 4463 synchronized (this) { 4464 synchronized (mProcLock) { 4465 mAtmInternal.onForceStopPackage(packageName, true, false, userId); 4466 4467 mProcessList.killPackageProcessesLSP(packageName, appId, userId, 4468 ProcessList.INVALID_ADJ, true, false, true, 4469 false, true /* setRemoved */, false, 4470 ApplicationExitInfo.REASON_USER_REQUESTED, 4471 ApplicationExitInfo.SUBREASON_STOP_APP, 4472 "fully stop " + packageName + "/" + userId + " by user request"); 4473 } 4474 4475 mServices.bringDownDisabledPackageServicesLocked( 4476 packageName, null, userId, false, true, true); 4477 4478 if (mBooted) { 4479 mAtmInternal.resumeTopActivities(true); 4480 } 4481 } 4482 } 4483 4484 @GuardedBy("this") forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reason)4485 final boolean forceStopPackageLocked(String packageName, int appId, 4486 boolean callerWillRestart, boolean purgeCache, boolean doit, 4487 boolean evenPersistent, boolean uninstalling, int userId, String reason) { 4488 int i; 4489 4490 if (userId == UserHandle.USER_ALL && packageName == null) { 4491 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 4492 } 4493 4494 if (appId < 0 && packageName != null) { 4495 appId = UserHandle.getAppId(getPackageManagerInternal().getPackageUid(packageName, 4496 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM)); 4497 } 4498 4499 boolean didSomething; 4500 if (doit) { 4501 if (packageName != null) { 4502 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId 4503 + " user=" + userId + ": " + reason); 4504 } else { 4505 Slog.i(TAG, "Force stopping u" + userId + ": " + reason); 4506 } 4507 4508 mAppErrors.resetProcessCrashTime(packageName == null, appId, userId); 4509 } 4510 4511 synchronized (mProcLock) { 4512 // Notify first that the package is stopped, so its process won't be restarted 4513 // unexpectedly if there is an activity of the package without attached process 4514 // becomes visible when killing its other processes with visible activities. 4515 didSomething = mAtmInternal.onForceStopPackage( 4516 packageName, doit, evenPersistent, userId); 4517 4518 didSomething |= mProcessList.killPackageProcessesLSP(packageName, appId, userId, 4519 ProcessList.INVALID_ADJ, callerWillRestart, false /* allowRestart */, doit, 4520 evenPersistent, true /* setRemoved */, uninstalling, 4521 packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED 4522 : ApplicationExitInfo.REASON_USER_REQUESTED, 4523 ApplicationExitInfo.SUBREASON_FORCE_STOP, 4524 (packageName == null ? ("stop user " + userId) : ("stop " + packageName)) 4525 + " due to " + reason); 4526 } 4527 4528 if (mServices.bringDownDisabledPackageServicesLocked( 4529 packageName, null /* filterByClasses */, userId, evenPersistent, true, doit)) { 4530 if (!doit) { 4531 return true; 4532 } 4533 didSomething = true; 4534 } 4535 4536 if (packageName == null) { 4537 // Remove all sticky broadcasts from this user. 4538 mStickyBroadcasts.remove(userId); 4539 } 4540 4541 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4542 if (mCpHelper.getProviderMap().collectPackageProvidersLocked(packageName, null, doit, 4543 evenPersistent, userId, providers)) { 4544 if (!doit) { 4545 return true; 4546 } 4547 didSomething = true; 4548 } 4549 for (i = providers.size() - 1; i >= 0; i--) { 4550 mCpHelper.removeDyingProviderLocked(null, providers.get(i), true); 4551 } 4552 4553 // Remove transient permissions granted from/to this package/user 4554 mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false); 4555 4556 if (doit) { 4557 for (i = mBroadcastQueues.length - 1; i >= 0; i--) { 4558 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4559 packageName, null, userId, doit); 4560 } 4561 } 4562 4563 if (packageName == null || uninstalling) { 4564 didSomething |= mPendingIntentController.removePendingIntentsForPackage( 4565 packageName, userId, appId, doit); 4566 } 4567 4568 if (doit) { 4569 if (purgeCache && packageName != null) { 4570 AttributeCache ac = AttributeCache.instance(); 4571 if (ac != null) { 4572 ac.removePackage(packageName); 4573 } 4574 } 4575 if (mBooted) { 4576 mAtmInternal.resumeTopActivities(true /* scheduleIdle */); 4577 } 4578 } 4579 4580 return didSomething; 4581 } 4582 4583 @GuardedBy("this") handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout)4584 void handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout) { 4585 final int pid = app.getPid(); 4586 boolean gone = isKillTimeout || removePidIfNoThreadLocked(app); 4587 4588 if (gone) { 4589 if (isKillTimeout) { 4590 // It's still alive... maybe blocked at uninterruptible sleep ? 4591 final ProcessRecord successor = app.mSuccessor; 4592 if (successor == null) { 4593 // There might be a race, nothing to do here. 4594 return; 4595 } 4596 Slog.wtf(TAG, app.toString() + " " + app.getDyingPid() 4597 + " refused to die while trying to launch " + successor 4598 + ", cancelling the process start"); 4599 4600 // It doesn't make sense to proceed with launching the new instance while the old 4601 // instance is still alive, abort the launch. 4602 app.mSuccessorStartRunnable = null; 4603 app.mSuccessor = null; 4604 successor.mPredecessor = null; 4605 4606 // We're going to cleanup the successor process record, which wasn't started at all. 4607 app = successor; 4608 } else { 4609 final String msg = "Process " + app + " failed to attach"; 4610 Slog.w(TAG, msg); 4611 EventLogTags.writeAmProcessStartTimeout(app.userId, pid, app.uid, app.processName); 4612 if (app.getActiveInstrumentation() != null) { 4613 final Bundle info = new Bundle(); 4614 info.putString("shortMsg", "failed to attach"); 4615 info.putString("longMsg", msg); 4616 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 4617 } 4618 } 4619 synchronized (mProcLock) { 4620 mProcessList.removeProcessNameLocked(app.processName, app.uid); 4621 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 4622 // Take care of any launching providers waiting for this process. 4623 mCpHelper.cleanupAppInLaunchingProvidersLocked(app, true); 4624 // Take care of any services that are waiting for the process. 4625 mServices.processStartTimedOutLocked(app); 4626 if (!isKillTimeout) { 4627 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 4628 app.killLocked("start timeout", 4629 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true); 4630 removeLruProcessLocked(app); 4631 } 4632 if (app.isolated) { 4633 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 4634 mProcessList.mAppExitInfoTracker.mIsolatedUidRecords.removeIsolatedUid( 4635 app.uid, app.info.uid); 4636 getPackageManagerInternal().removeIsolatedUid(app.uid); 4637 } 4638 } 4639 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4640 if (!isKillTimeout && backupTarget != null && backupTarget.app.getPid() == pid) { 4641 Slog.w(TAG, "Unattached app died before backup, skipping"); 4642 final int userId = app.userId; 4643 final String packageName = app.info.packageName; 4644 mHandler.post(new Runnable() { 4645 @Override 4646 public void run(){ 4647 try { 4648 IBackupManager bm = IBackupManager.Stub.asInterface( 4649 ServiceManager.getService(Context.BACKUP_SERVICE)); 4650 bm.agentDisconnectedForUser(userId, packageName); 4651 } catch (RemoteException e) { 4652 // Can't happen; the backup manager is local 4653 } 4654 } 4655 }); 4656 } 4657 if (!isKillTimeout) { 4658 if (isPendingBroadcastProcessLocked(pid)) { 4659 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 4660 skipPendingBroadcastLocked(pid); 4661 } 4662 } else { 4663 if (isPendingBroadcastProcessLocked(app)) { 4664 skipCurrentReceiverLocked(app); 4665 } 4666 } 4667 } else { 4668 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 4669 } 4670 } 4671 4672 @GuardedBy("this") attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4673 private boolean attachApplicationLocked(@NonNull IApplicationThread thread, 4674 int pid, int callingUid, long startSeq) { 4675 4676 // Find the application record that is being attached... either via 4677 // the pid if we are running in multiple processes, or just pull the 4678 // next app record if we are emulating process with anonymous threads. 4679 ProcessRecord app; 4680 long startTime = SystemClock.uptimeMillis(); 4681 long bindApplicationTimeMillis; 4682 if (pid != MY_PID && pid >= 0) { 4683 synchronized (mPidsSelfLocked) { 4684 app = mPidsSelfLocked.get(pid); 4685 } 4686 if (app != null && (app.getStartUid() != callingUid || app.getStartSeq() != startSeq)) { 4687 String processName = null; 4688 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4689 if (pending != null) { 4690 processName = pending.processName; 4691 } 4692 final String msg = "attachApplicationLocked process:" + processName 4693 + " startSeq:" + startSeq 4694 + " pid:" + pid 4695 + " belongs to another existing app:" + app.processName 4696 + " startSeq:" + app.getStartSeq(); 4697 Slog.wtf(TAG, msg); 4698 // SafetyNet logging for b/131105245. 4699 EventLog.writeEvent(0x534e4554, "131105245", app.getStartUid(), msg); 4700 // If there is already an app occupying that pid that hasn't been cleaned up 4701 cleanUpApplicationRecordLocked(app, pid, false, false, -1, 4702 true /*replacingPid*/, false /* fromBinderDied */); 4703 removePidLocked(pid, app); 4704 app = null; 4705 } 4706 } else { 4707 app = null; 4708 } 4709 4710 // It's possible that process called attachApplication before we got a chance to 4711 // update the internal state. 4712 if (app == null && startSeq > 0) { 4713 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4714 if (pending != null && pending.getStartUid() == callingUid 4715 && pending.getStartSeq() == startSeq 4716 && mProcessList.handleProcessStartedLocked(pending, pid, 4717 pending.isUsingWrapper(), startSeq, true)) { 4718 app = pending; 4719 } 4720 } 4721 4722 if (app == null) { 4723 Slog.w(TAG, "No pending application record for pid " + pid 4724 + " (IApplicationThread " + thread + "); dropping process"); 4725 EventLogTags.writeAmDropProcess(pid); 4726 if (pid > 0 && pid != MY_PID) { 4727 killProcessQuiet(pid); 4728 //TODO: killProcessGroup(app.info.uid, pid); 4729 // We can't log the app kill info for this process since we don't 4730 // know who it is, so just skip the logging. 4731 } else { 4732 try { 4733 thread.scheduleExit(); 4734 } catch (Exception e) { 4735 // Ignore exceptions. 4736 } 4737 } 4738 return false; 4739 } 4740 4741 // If this application record is still attached to a previous 4742 // process, clean it up now. 4743 if (app.getThread() != null) { 4744 handleAppDiedLocked(app, pid, true, true, false /* fromBinderDied */); 4745 } 4746 4747 // Tell the process all about itself. 4748 4749 if (DEBUG_ALL) Slog.v( 4750 TAG, "Binding process pid " + pid + " to record " + app); 4751 4752 final String processName = app.processName; 4753 try { 4754 AppDeathRecipient adr = new AppDeathRecipient( 4755 app, pid, thread); 4756 thread.asBinder().linkToDeath(adr, 0); 4757 app.setDeathRecipient(adr); 4758 } catch (RemoteException e) { 4759 app.resetPackageList(mProcessStats); 4760 mProcessList.startProcessLocked(app, 4761 new HostingRecord(HostingRecord.HOSTING_TYPE_LINK_FAIL, processName), 4762 ZYGOTE_POLICY_FLAG_EMPTY); 4763 return false; 4764 } 4765 4766 EventLogTags.writeAmProcBound(app.userId, pid, app.processName); 4767 4768 synchronized (mProcLock) { 4769 app.mState.setCurAdj(ProcessList.INVALID_ADJ); 4770 app.mState.setSetAdj(ProcessList.INVALID_ADJ); 4771 app.mState.setVerifiedAdj(ProcessList.INVALID_ADJ); 4772 mOomAdjuster.setAttachingSchedGroupLSP(app); 4773 app.mState.setForcingToImportant(null); 4774 updateProcessForegroundLocked(app, false, 0, false); 4775 app.mState.setHasShownUi(false); 4776 app.mState.setCached(false); 4777 app.setDebugging(false); 4778 app.setKilledByAm(false); 4779 app.setKilled(false); 4780 // We carefully use the same state that PackageManager uses for 4781 // filtering, since we use this flag to decide if we need to install 4782 // providers when user is unlocked later 4783 app.setUnlocked(StorageManager.isUserKeyUnlocked(app.userId)); 4784 } 4785 4786 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4787 4788 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4789 List<ProviderInfo> providers = normalMode 4790 ? mCpHelper.generateApplicationProvidersLocked(app) 4791 : null; 4792 4793 if (providers != null && mCpHelper.checkAppInLaunchingProvidersLocked(app)) { 4794 Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG); 4795 msg.obj = app; 4796 mHandler.sendMessageDelayed(msg, 4797 ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS); 4798 } 4799 4800 checkTime(startTime, "attachApplicationLocked: before bindApplication"); 4801 4802 if (!normalMode) { 4803 Slog.i(TAG, "Launching preboot mode app: " + app); 4804 } 4805 4806 if (DEBUG_ALL) Slog.v( 4807 TAG, "New app record " + app 4808 + " thread=" + thread.asBinder() + " pid=" + pid); 4809 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4810 try { 4811 int testMode = ApplicationThreadConstants.DEBUG_OFF; 4812 if (mDebugApp != null && mDebugApp.equals(processName)) { 4813 testMode = mWaitForDebugger 4814 ? ApplicationThreadConstants.DEBUG_WAIT 4815 : ApplicationThreadConstants.DEBUG_ON; 4816 app.setDebugging(true); 4817 if (mDebugTransient) { 4818 mDebugApp = mOrigDebugApp; 4819 mWaitForDebugger = mOrigWaitForDebugger; 4820 } 4821 } 4822 4823 boolean enableTrackAllocation = false; 4824 synchronized (mProcLock) { 4825 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) { 4826 enableTrackAllocation = true; 4827 mTrackAllocationApp = null; 4828 } 4829 } 4830 4831 // If the app is being launched for restore or full backup, set it up specially 4832 boolean isRestrictedBackupMode = false; 4833 if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) { 4834 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID 4835 && ((backupTarget.backupMode == BackupRecord.RESTORE) 4836 || (backupTarget.backupMode == BackupRecord.RESTORE_FULL) 4837 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL)); 4838 } 4839 4840 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 4841 4842 if (instr != null) { 4843 notifyPackageUse(instr.mClass.getPackageName(), 4844 PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION); 4845 } 4846 ProtoLog.v(WM_DEBUG_CONFIGURATION, "Binding proc %s with config %s", 4847 processName, app.getWindowProcessController().getConfiguration()); 4848 ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info; 4849 app.setCompat(compatibilityInfoForPackage(appInfo)); 4850 4851 ProfilerInfo profilerInfo = mAppProfiler.setupProfilerInfoLocked(thread, app, instr); 4852 4853 // We deprecated Build.SERIAL and it is not accessible to 4854 // Instant Apps and target APIs higher than O MR1. Since access to the serial 4855 // is now behind a permission we push down the value. 4856 final String buildSerial = (!appInfo.isInstantApp() 4857 && appInfo.targetSdkVersion < Build.VERSION_CODES.P) 4858 ? sTheRealBuildSerial : Build.UNKNOWN; 4859 4860 // Figure out whether the app needs to run in autofill compat mode. 4861 AutofillOptions autofillOptions = null; 4862 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 4863 final AutofillManagerInternal afm = LocalServices.getService( 4864 AutofillManagerInternal.class); 4865 if (afm != null) { 4866 autofillOptions = afm.getAutofillOptions( 4867 app.info.packageName, app.info.longVersionCode, app.userId); 4868 } 4869 } 4870 ContentCaptureOptions contentCaptureOptions = null; 4871 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 4872 final ContentCaptureManagerInternal ccm = 4873 LocalServices.getService(ContentCaptureManagerInternal.class); 4874 if (ccm != null) { 4875 contentCaptureOptions = ccm.getOptionsForPackage(app.userId, 4876 app.info.packageName); 4877 } 4878 } 4879 SharedMemory serializedSystemFontMap = null; 4880 final FontManagerInternal fm = LocalServices.getService(FontManagerInternal.class); 4881 if (fm != null) { 4882 serializedSystemFontMap = fm.getSerializedSystemFontMap(); 4883 } 4884 4885 checkTime(startTime, "attachApplicationLocked: immediately before bindApplication"); 4886 bindApplicationTimeMillis = SystemClock.uptimeMillis(); 4887 mAtmInternal.preBindApplication(app.getWindowProcessController()); 4888 final ActiveInstrumentation instr2 = app.getActiveInstrumentation(); 4889 if (mPlatformCompat != null) { 4890 mPlatformCompat.resetReporting(app.info); 4891 } 4892 final ProviderInfoList providerList = ProviderInfoList.fromList(providers); 4893 if (app.getIsolatedEntryPoint() != null) { 4894 // This is an isolated process which should just call an entry point instead of 4895 // being bound to an application. 4896 thread.runIsolatedEntryPoint( 4897 app.getIsolatedEntryPoint(), app.getIsolatedEntryPointArgs()); 4898 } else if (instr2 != null) { 4899 thread.bindApplication(processName, appInfo, 4900 app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage, 4901 providerList, 4902 instr2.mClass, 4903 profilerInfo, instr2.mArguments, 4904 instr2.mWatcher, 4905 instr2.mUiAutomationConnection, testMode, 4906 mBinderTransactionTrackingEnabled, enableTrackAllocation, 4907 isRestrictedBackupMode || !normalMode, app.isPersistent(), 4908 new Configuration(app.getWindowProcessController().getConfiguration()), 4909 app.getCompat(), getCommonServicesLocked(app.isolated), 4910 mCoreSettingsObserver.getCoreSettingsLocked(), 4911 buildSerial, autofillOptions, contentCaptureOptions, 4912 app.getDisabledCompatChanges(), serializedSystemFontMap, 4913 app.getStartElapsedTime(), app.getStartUptime()); 4914 } else { 4915 thread.bindApplication(processName, appInfo, 4916 app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage, 4917 providerList, null, profilerInfo, null, null, null, testMode, 4918 mBinderTransactionTrackingEnabled, enableTrackAllocation, 4919 isRestrictedBackupMode || !normalMode, app.isPersistent(), 4920 new Configuration(app.getWindowProcessController().getConfiguration()), 4921 app.getCompat(), getCommonServicesLocked(app.isolated), 4922 mCoreSettingsObserver.getCoreSettingsLocked(), 4923 buildSerial, autofillOptions, contentCaptureOptions, 4924 app.getDisabledCompatChanges(), serializedSystemFontMap, 4925 app.getStartElapsedTime(), app.getStartUptime()); 4926 } 4927 if (profilerInfo != null) { 4928 profilerInfo.closeFd(); 4929 profilerInfo = null; 4930 } 4931 4932 // Make app active after binding application or client may be running requests (e.g 4933 // starting activities) before it is ready. 4934 synchronized (mProcLock) { 4935 app.makeActive(thread, mProcessStats); 4936 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication"); 4937 } 4938 updateLruProcessLocked(app, false, null); 4939 checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked"); 4940 final long now = SystemClock.uptimeMillis(); 4941 synchronized (mAppProfiler.mProfilerLock) { 4942 app.mProfile.setLastRequestedGc(now); 4943 app.mProfile.setLastLowMemory(now); 4944 } 4945 } catch (Exception e) { 4946 // We need kill the process group here. (b/148588589) 4947 Slog.wtf(TAG, "Exception thrown during bind of " + app, e); 4948 app.resetPackageList(mProcessStats); 4949 app.unlinkDeathRecipient(); 4950 app.killLocked("error during bind", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 4951 true); 4952 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */); 4953 return false; 4954 } 4955 4956 // Remove this record from the list of starting applications. 4957 mPersistentStartingProcesses.remove(app); 4958 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, 4959 "Attach application locked removing on hold: " + app); 4960 mProcessesOnHold.remove(app); 4961 4962 boolean badApp = false; 4963 boolean didSomething = false; 4964 4965 // See if the top visible activity is waiting to run in this process... 4966 if (normalMode) { 4967 try { 4968 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); 4969 } catch (Exception e) { 4970 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); 4971 badApp = true; 4972 } 4973 } 4974 4975 // Find any services that should be running in this process... 4976 if (!badApp) { 4977 try { 4978 didSomething |= mServices.attachApplicationLocked(app, processName); 4979 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked"); 4980 } catch (Exception e) { 4981 Slog.wtf(TAG, "Exception thrown starting services in " + app, e); 4982 badApp = true; 4983 } 4984 } 4985 4986 if (!badApp) { 4987 updateUidReadyForBootCompletedBroadcastLocked(app.uid); 4988 } 4989 4990 // Check if a next-broadcast receiver is in this process... 4991 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 4992 try { 4993 didSomething |= sendPendingBroadcastsLocked(app); 4994 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked"); 4995 } catch (Exception e) { 4996 // If the app died trying to launch the receiver we declare it 'bad' 4997 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e); 4998 badApp = true; 4999 } 5000 } 5001 5002 // Check whether the next backup agent is in this process... 5003 if (!badApp && backupTarget != null && backupTarget.app == app) { 5004 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, 5005 "New app is backup target, launching agent for " + app); 5006 notifyPackageUse(backupTarget.appInfo.packageName, 5007 PackageManager.NOTIFY_PACKAGE_USE_BACKUP); 5008 try { 5009 thread.scheduleCreateBackupAgent(backupTarget.appInfo, 5010 compatibilityInfoForPackage(backupTarget.appInfo), 5011 backupTarget.backupMode, backupTarget.userId, backupTarget.operationType); 5012 } catch (Exception e) { 5013 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e); 5014 badApp = true; 5015 } 5016 } 5017 5018 if (badApp) { 5019 app.killLocked("error during init", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 5020 true); 5021 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */); 5022 return false; 5023 } 5024 5025 if (!didSomething) { 5026 updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN); 5027 checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked"); 5028 } 5029 5030 5031 final HostingRecord hostingRecord = app.getHostingRecord(); 5032 String shortAction = getShortAction(hostingRecord.getAction()); 5033 FrameworkStatsLog.write( 5034 FrameworkStatsLog.PROCESS_START_TIME, 5035 app.info.uid, 5036 pid, 5037 app.info.packageName, 5038 FrameworkStatsLog.PROCESS_START_TIME__TYPE__COLD, 5039 app.getStartElapsedTime(), 5040 (int) (bindApplicationTimeMillis - app.getStartUptime()), 5041 (int) (SystemClock.uptimeMillis() - app.getStartUptime()), 5042 hostingRecord.getType(), 5043 hostingRecord.getName(), 5044 shortAction, 5045 HostingRecord.getHostingTypeIdStatsd(hostingRecord.getType()), 5046 HostingRecord.getTriggerTypeForStatsd(hostingRecord.getTriggerType())); 5047 return true; 5048 } 5049 5050 @Override attachApplication(IApplicationThread thread, long startSeq)5051 public final void attachApplication(IApplicationThread thread, long startSeq) { 5052 if (thread == null) { 5053 throw new SecurityException("Invalid application interface"); 5054 } 5055 synchronized (this) { 5056 int callingPid = Binder.getCallingPid(); 5057 final int callingUid = Binder.getCallingUid(); 5058 final long origId = Binder.clearCallingIdentity(); 5059 attachApplicationLocked(thread, callingPid, callingUid, startSeq); 5060 Binder.restoreCallingIdentity(origId); 5061 } 5062 } 5063 5064 /** 5065 * @return The last part of the string of an intent's action. 5066 */ getShortAction(@ullable String action)5067 static @Nullable String getShortAction(@Nullable String action) { 5068 String shortAction = action; 5069 if (action != null) { 5070 int index = action.lastIndexOf('.'); 5071 if (index != -1 && index != action.length() - 1) { 5072 shortAction = action.substring(index + 1); 5073 } 5074 } 5075 return shortAction; 5076 } 5077 checkTime(long startTime, String where)5078 void checkTime(long startTime, String where) { 5079 long now = SystemClock.uptimeMillis(); 5080 if ((now - startTime) > 50) { 5081 // If we are taking more than 50ms, log about it. 5082 Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where); 5083 } 5084 } 5085 5086 @Override showBootMessage(final CharSequence msg, final boolean always)5087 public void showBootMessage(final CharSequence msg, final boolean always) { 5088 if (Binder.getCallingUid() != myUid()) { 5089 throw new SecurityException(); 5090 } 5091 mWindowManager.showBootMessage(msg, always); 5092 } 5093 finishBooting()5094 final void finishBooting() { 5095 TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing", 5096 Trace.TRACE_TAG_ACTIVITY_MANAGER); 5097 t.traceBegin("FinishBooting"); 5098 5099 synchronized (this) { 5100 if (!mBootAnimationComplete) { 5101 mCallFinishBooting = true; 5102 return; 5103 } 5104 mCallFinishBooting = false; 5105 } 5106 5107 // Let the ART runtime in zygote and system_server know that the boot completed. 5108 ZYGOTE_PROCESS.bootCompleted(); 5109 VMRuntime.bootCompleted(); 5110 5111 IntentFilter pkgFilter = new IntentFilter(); 5112 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 5113 pkgFilter.addDataScheme("package"); 5114 mContext.registerReceiver(new BroadcastReceiver() { 5115 @Override 5116 public void onReceive(Context context, Intent intent) { 5117 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 5118 if (pkgs != null) { 5119 for (String pkg : pkgs) { 5120 synchronized (ActivityManagerService.this) { 5121 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 5122 0, "query restart")) { 5123 setResultCode(Activity.RESULT_OK); 5124 return; 5125 } 5126 } 5127 } 5128 } 5129 } 5130 }, pkgFilter); 5131 5132 // Inform checkpointing systems of success 5133 try { 5134 // This line is needed to CTS test for the correct exception handling 5135 // See b/138952436#comment36 for context 5136 Slog.i(TAG, "About to commit checkpoint"); 5137 IStorageManager storageManager = InstallLocationUtils.getStorageManager(); 5138 storageManager.commitChanges(); 5139 } catch (Exception e) { 5140 PowerManager pm = (PowerManager) 5141 mInjector.getContext().getSystemService(Context.POWER_SERVICE); 5142 pm.reboot("Checkpoint commit failed"); 5143 } 5144 5145 // Let system services know. 5146 mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED); 5147 5148 synchronized (this) { 5149 // Ensure that any processes we had put on hold are now started 5150 // up. 5151 final int NP = mProcessesOnHold.size(); 5152 if (NP > 0) { 5153 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mProcessesOnHold); 5154 for (int ip = 0; ip < NP; ip++) { 5155 if (DEBUG_PROCESSES) { 5156 Slog.v(TAG_PROCESSES, "Starting process on hold: " + procs.get(ip)); 5157 } 5158 mProcessList.startProcessLocked(procs.get(ip), 5159 new HostingRecord(HostingRecord.HOSTING_TYPE_ON_HOLD), 5160 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 5161 } 5162 } 5163 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 5164 return; 5165 } 5166 // Start looking for apps that are abusing wake locks. 5167 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 5168 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 5169 // Check if we are performing userspace reboot before setting sys.boot_completed to 5170 // avoid race with init reseting sys.init.userspace_reboot.in_progress once sys 5171 // .boot_completed is 1. 5172 if (InitProperties.userspace_reboot_in_progress().orElse(false)) { 5173 UserspaceRebootLogger.noteUserspaceRebootSuccess(); 5174 } 5175 // Tell anyone interested that we are done booting! 5176 SystemProperties.set("sys.boot_completed", "1"); 5177 5178 // And trigger dev.bootcomplete if we are not showing encryption progress 5179 if (!"trigger_restart_min_framework".equals(VoldProperties.decrypt().orElse("")) 5180 || "".equals(VoldProperties.encrypt_progress().orElse(""))) { 5181 SystemProperties.set("dev.bootcomplete", "1"); 5182 } 5183 mUserController.sendBootCompleted( 5184 new IIntentReceiver.Stub() { 5185 @Override 5186 public void performReceive(Intent intent, int resultCode, 5187 String data, Bundle extras, boolean ordered, 5188 boolean sticky, int sendingUser) { 5189 synchronized (mProcLock) { 5190 mAppProfiler.requestPssAllProcsLPr( 5191 SystemClock.uptimeMillis(), true, false); 5192 } 5193 } 5194 }); 5195 maybeLogUserspaceRebootEvent(); 5196 mUserController.scheduleStartProfiles(); 5197 } 5198 // UART is on if init's console service is running, send a warning notification. 5199 showConsoleNotificationIfActive(); 5200 showMteOverrideNotificationIfActive(); 5201 5202 t.traceEnd(); 5203 } 5204 showConsoleNotificationIfActive()5205 private void showConsoleNotificationIfActive() { 5206 if (!SystemProperties.get("init.svc.console").equals("running")) { 5207 return; 5208 } 5209 String title = mContext 5210 .getString(com.android.internal.R.string.console_running_notification_title); 5211 String message = mContext 5212 .getString(com.android.internal.R.string.console_running_notification_message); 5213 Notification notification = 5214 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 5215 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 5216 .setWhen(0) 5217 .setOngoing(true) 5218 .setTicker(title) 5219 .setDefaults(0) // please be quiet 5220 .setColor(mContext.getColor( 5221 com.android.internal.R.color 5222 .system_notification_accent_color)) 5223 .setContentTitle(title) 5224 .setContentText(message) 5225 .setVisibility(Notification.VISIBILITY_PUBLIC) 5226 .build(); 5227 5228 NotificationManager notificationManager = 5229 mContext.getSystemService(NotificationManager.class); 5230 notificationManager.notifyAsUser( 5231 null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL); 5232 5233 } 5234 showMteOverrideNotificationIfActive()5235 private void showMteOverrideNotificationIfActive() { 5236 if (!SystemProperties.getBoolean("ro.arm64.memtag.bootctl_supported", false) 5237 || !com.android.internal.os.Zygote.nativeSupportsMemoryTagging()) { 5238 return; 5239 } 5240 String title = mContext 5241 .getString(com.android.internal.R.string.mte_override_notification_title); 5242 String message = mContext 5243 .getString(com.android.internal.R.string.mte_override_notification_message); 5244 Notification notification = 5245 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 5246 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 5247 .setOngoing(true) 5248 .setTicker(title) 5249 .setDefaults(0) // please be quiet 5250 .setColor(mContext.getColor( 5251 com.android.internal.R.color 5252 .system_notification_accent_color)) 5253 .setContentTitle(title) 5254 .setContentText(message) 5255 .setVisibility(Notification.VISIBILITY_PUBLIC) 5256 .build(); 5257 5258 NotificationManager notificationManager = 5259 mContext.getSystemService(NotificationManager.class); 5260 notificationManager.notifyAsUser( 5261 null, SystemMessage.NOTE_MTE_OVERRIDE_ENABLED, notification, UserHandle.ALL); 5262 } 5263 5264 @Override bootAnimationComplete()5265 public void bootAnimationComplete() { 5266 if (DEBUG_ALL) Slog.d(TAG, "bootAnimationComplete: Callers=" + Debug.getCallers(4)); 5267 5268 final boolean callFinishBooting; 5269 synchronized (this) { 5270 callFinishBooting = mCallFinishBooting; 5271 mBootAnimationComplete = true; 5272 } 5273 if (callFinishBooting) { 5274 finishBooting(); 5275 } 5276 } 5277 ensureBootCompleted()5278 final void ensureBootCompleted() { 5279 boolean booting; 5280 boolean enableScreen; 5281 synchronized (this) { 5282 booting = mBooting; 5283 mBooting = false; 5284 enableScreen = !mBooted; 5285 mBooted = true; 5286 } 5287 5288 if (booting) { 5289 finishBooting(); 5290 } 5291 5292 if (enableScreen) { 5293 mAtmInternal.enableScreenAfterBoot(mBooted); 5294 } 5295 } 5296 5297 /** 5298 * @deprecated Use {@link #getIntentSenderWithFeature} instead 5299 */ 5300 @Deprecated 5301 @Override getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5302 public IIntentSender getIntentSender(int type, 5303 String packageName, IBinder token, String resultWho, 5304 int requestCode, Intent[] intents, String[] resolvedTypes, 5305 int flags, Bundle bOptions, int userId) { 5306 return getIntentSenderWithFeature(type, packageName, null, token, resultWho, requestCode, 5307 intents, resolvedTypes, flags, bOptions, userId); 5308 } 5309 5310 @Override getIntentSenderWithFeature(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5311 public IIntentSender getIntentSenderWithFeature(int type, String packageName, String featureId, 5312 IBinder token, String resultWho, int requestCode, Intent[] intents, 5313 String[] resolvedTypes, int flags, Bundle bOptions, int userId) { 5314 enforceNotIsolatedCaller("getIntentSender"); 5315 5316 return getIntentSenderWithFeatureAsApp(type, packageName, featureId, token, resultWho, 5317 requestCode, intents, resolvedTypes, flags, bOptions, userId, 5318 Binder.getCallingUid()); 5319 } 5320 5321 /** 5322 * System-internal callers can invoke this with owningUid being the app's own identity 5323 * rather than the public API's behavior of always assigning ownership to the actual 5324 * caller identity. This will create an IntentSender as though the package/userid/uid app 5325 * were the caller, so that the ultimate PendingIntent is triggered with only the app's 5326 * capabilities and not the system's. Used in cases like notification groups where 5327 * the OS must synthesize a PendingIntent on an app's behalf. 5328 */ 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)5329 public IIntentSender getIntentSenderWithFeatureAsApp(int type, String packageName, 5330 String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, 5331 String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid) { 5332 // NOTE: The service lock isn't held in this method because nothing in the method requires 5333 // the service lock to be held. 5334 5335 // Refuse possible leaked file descriptors 5336 if (intents != null) { 5337 if (intents.length < 1) { 5338 throw new IllegalArgumentException("Intents array length must be >= 1"); 5339 } 5340 for (int i=0; i<intents.length; i++) { 5341 Intent intent = intents[i]; 5342 if (intent != null) { 5343 if (intent.hasFileDescriptors()) { 5344 throw new IllegalArgumentException("File descriptors passed in Intent"); 5345 } 5346 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 5347 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 5348 throw new IllegalArgumentException( 5349 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 5350 } 5351 intents[i] = new Intent(intent); 5352 } 5353 } 5354 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 5355 throw new IllegalArgumentException( 5356 "Intent array length does not match resolvedTypes length"); 5357 } 5358 } 5359 if (bOptions != null) { 5360 if (bOptions.hasFileDescriptors()) { 5361 throw new IllegalArgumentException("File descriptors passed in options"); 5362 } 5363 } 5364 5365 int origUserId = userId; 5366 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), owningUid, userId, 5367 type == ActivityManager.INTENT_SENDER_BROADCAST, 5368 ALLOW_NON_FULL, "getIntentSender", null); 5369 if (origUserId == UserHandle.USER_CURRENT) { 5370 // We don't want to evaluate this until the pending intent is 5371 // actually executed. However, we do want to always do the 5372 // security checking for it above. 5373 userId = UserHandle.USER_CURRENT; 5374 } 5375 try { 5376 if (owningUid != 0 && owningUid != SYSTEM_UID) { 5377 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName, 5378 MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(owningUid)); 5379 if (!UserHandle.isSameApp(owningUid, uid)) { 5380 String msg = "Permission Denial: getIntentSender() from pid=" 5381 + Binder.getCallingPid() 5382 + ", uid=" + owningUid 5383 + ", (need uid=" + uid + ")" 5384 + " is not allowed to send as package " + packageName; 5385 Slog.w(TAG, msg); 5386 throw new SecurityException(msg); 5387 } 5388 } 5389 5390 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 5391 return mAtmInternal.getIntentSender(type, packageName, featureId, owningUid, 5392 userId, token, resultWho, requestCode, intents, resolvedTypes, flags, 5393 bOptions); 5394 } 5395 return mPendingIntentController.getIntentSender(type, packageName, featureId, 5396 owningUid, userId, token, resultWho, requestCode, intents, resolvedTypes, 5397 flags, bOptions); 5398 } catch (RemoteException e) { 5399 throw new SecurityException(e); 5400 } 5401 } 5402 5403 @Override sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5404 public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, 5405 Intent intent, String resolvedType, 5406 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 5407 if (target instanceof PendingIntentRecord) { 5408 return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType, 5409 allowlistToken, finishedReceiver, requiredPermission, options); 5410 } else { 5411 if (intent == null) { 5412 // Weird case: someone has given us their own custom IIntentSender, and now 5413 // they have someone else trying to send to it but of course this isn't 5414 // really a PendingIntent, so there is no base Intent, and the caller isn't 5415 // supplying an Intent... but we never want to dispatch a null Intent to 5416 // a receiver, so um... let's make something up. 5417 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call"); 5418 intent = new Intent(Intent.ACTION_MAIN); 5419 } 5420 try { 5421 target.send(code, intent, resolvedType, allowlistToken, null, 5422 requiredPermission, options); 5423 } catch (RemoteException e) { 5424 } 5425 // Platform code can rely on getting a result back when the send is done, but if 5426 // this intent sender is from outside of the system we can't rely on it doing that. 5427 // So instead we don't give it the result receiver, and instead just directly 5428 // report the finish immediately. 5429 if (finishedReceiver != null) { 5430 try { 5431 finishedReceiver.performReceive(intent, 0, 5432 null, null, false, false, UserHandle.getCallingUserId()); 5433 } catch (RemoteException e) { 5434 } 5435 } 5436 return 0; 5437 } 5438 } 5439 5440 @Override cancelIntentSender(IIntentSender sender)5441 public void cancelIntentSender(IIntentSender sender) { 5442 mPendingIntentController.cancelIntentSender(sender); 5443 } 5444 5445 @Override registerIntentSenderCancelListenerEx( IIntentSender sender, IResultReceiver receiver)5446 public boolean registerIntentSenderCancelListenerEx( 5447 IIntentSender sender, IResultReceiver receiver) { 5448 return mPendingIntentController.registerIntentSenderCancelListener(sender, receiver); 5449 } 5450 5451 @Override unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5452 public void unregisterIntentSenderCancelListener(IIntentSender sender, 5453 IResultReceiver receiver) { 5454 mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver); 5455 } 5456 5457 @Override getInfoForIntentSender(IIntentSender sender)5458 public PendingIntentInfo getInfoForIntentSender(IIntentSender sender) { 5459 if (sender instanceof PendingIntentRecord) { 5460 final PendingIntentRecord res = (PendingIntentRecord) sender; 5461 final String packageName = res.key.packageName; 5462 final int uid = res.uid; 5463 final boolean shouldFilter = getPackageManagerInternal().filterAppAccess( 5464 packageName, Binder.getCallingUid(), UserHandle.getUserId(uid)); 5465 return new PendingIntentInfo( 5466 shouldFilter ? null : packageName, 5467 shouldFilter ? INVALID_UID : uid, 5468 (res.key.flags & PendingIntent.FLAG_IMMUTABLE) != 0, 5469 res.key.type); 5470 } else { 5471 return new PendingIntentInfo(null, INVALID_UID, false, 5472 ActivityManager.INTENT_SENDER_UNKNOWN); 5473 } 5474 } 5475 5476 @Override isIntentSenderTargetedToPackage(IIntentSender pendingResult)5477 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 5478 if (!(pendingResult instanceof PendingIntentRecord)) { 5479 return false; 5480 } 5481 try { 5482 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5483 if (res.key.allIntents == null) { 5484 return false; 5485 } 5486 for (int i=0; i<res.key.allIntents.length; i++) { 5487 Intent intent = res.key.allIntents[i]; 5488 if (intent.getPackage() != null && intent.getComponent() != null) { 5489 return false; 5490 } 5491 } 5492 return true; 5493 } catch (ClassCastException e) { 5494 } 5495 return false; 5496 } 5497 5498 @Override isIntentSenderAnActivity(IIntentSender pendingResult)5499 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 5500 if (!(pendingResult instanceof PendingIntentRecord)) { 5501 return false; 5502 } 5503 try { 5504 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5505 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 5506 return true; 5507 } 5508 return false; 5509 } catch (ClassCastException e) { 5510 } 5511 return false; 5512 } 5513 5514 @Override getIntentForIntentSender(IIntentSender pendingResult)5515 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 5516 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5517 "getIntentForIntentSender()"); 5518 if (!(pendingResult instanceof PendingIntentRecord)) { 5519 return null; 5520 } 5521 try { 5522 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5523 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 5524 } catch (ClassCastException e) { 5525 } 5526 return null; 5527 } 5528 5529 @Override queryIntentComponentsForIntentSender( IIntentSender pendingResult, int matchFlags)5530 public ParceledListSlice<ResolveInfo> queryIntentComponentsForIntentSender( 5531 IIntentSender pendingResult, int matchFlags) { 5532 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5533 "queryIntentComponentsForIntentSender()"); 5534 Objects.requireNonNull(pendingResult); 5535 final PendingIntentRecord res; 5536 try { 5537 res = (PendingIntentRecord) pendingResult; 5538 } catch (ClassCastException e) { 5539 return null; 5540 } 5541 final Intent intent = res.key.requestIntent; 5542 if (intent == null) { 5543 return null; 5544 } 5545 final int userId = res.key.userId; 5546 final int uid = res.uid; 5547 final String resolvedType = res.key.requestResolvedType; 5548 switch (res.key.type) { 5549 case ActivityManager.INTENT_SENDER_ACTIVITY: 5550 return new ParceledListSlice<>(mPackageManagerInt.queryIntentActivities( 5551 intent, resolvedType, matchFlags, uid, userId)); 5552 case ActivityManager.INTENT_SENDER_SERVICE: 5553 case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE: 5554 return new ParceledListSlice<>(mPackageManagerInt.queryIntentServices( 5555 intent, matchFlags, uid, userId)); 5556 case ActivityManager.INTENT_SENDER_BROADCAST: 5557 return new ParceledListSlice<>(mPackageManagerInt.queryIntentReceivers( 5558 intent, resolvedType, matchFlags, uid, userId, false)); 5559 default: // ActivityManager.INTENT_SENDER_ACTIVITY_RESULT 5560 throw new IllegalStateException("Unsupported intent sender type: " + res.key.type); 5561 } 5562 } 5563 5564 @Override getTagForIntentSender(IIntentSender pendingResult, String prefix)5565 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) { 5566 if (!(pendingResult instanceof PendingIntentRecord)) { 5567 return null; 5568 } 5569 try { 5570 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5571 synchronized (this) { 5572 return getTagForIntentSenderLocked(res, prefix); 5573 } 5574 } catch (ClassCastException e) { 5575 } 5576 return null; 5577 } 5578 getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5579 String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) { 5580 final Intent intent = res.key.requestIntent; 5581 if (intent != null) { 5582 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null 5583 || res.lastTagPrefix.equals(prefix))) { 5584 return res.lastTag; 5585 } 5586 res.lastTagPrefix = prefix; 5587 final StringBuilder sb = new StringBuilder(128); 5588 if (prefix != null) { 5589 sb.append(prefix); 5590 } 5591 if (intent.getAction() != null) { 5592 sb.append(intent.getAction()); 5593 } else if (intent.getComponent() != null) { 5594 intent.getComponent().appendShortString(sb); 5595 } else { 5596 sb.append("?"); 5597 } 5598 return res.lastTag = sb.toString(); 5599 } 5600 return null; 5601 } 5602 5603 @Override setProcessLimit(int max)5604 public void setProcessLimit(int max) { 5605 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5606 "setProcessLimit()"); 5607 synchronized (this) { 5608 mConstants.setOverrideMaxCachedProcesses(max); 5609 trimApplicationsLocked(true, OomAdjuster.OOM_ADJ_REASON_PROCESS_END); 5610 } 5611 } 5612 5613 @Override getProcessLimit()5614 public int getProcessLimit() { 5615 synchronized (this) { 5616 return mConstants.getOverrideMaxCachedProcesses(); 5617 } 5618 } 5619 importanceTokenDied(ImportanceToken token)5620 void importanceTokenDied(ImportanceToken token) { 5621 synchronized (ActivityManagerService.this) { 5622 ProcessRecord pr = null; 5623 synchronized (mPidsSelfLocked) { 5624 ImportanceToken cur 5625 = mImportantProcesses.get(token.pid); 5626 if (cur != token) { 5627 return; 5628 } 5629 mImportantProcesses.remove(token.pid); 5630 pr = mPidsSelfLocked.get(token.pid); 5631 if (pr == null) { 5632 return; 5633 } 5634 pr.mState.setForcingToImportant(null); 5635 updateProcessForegroundLocked(pr, false, 0, false); 5636 } 5637 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 5638 } 5639 } 5640 5641 @Override setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5642 public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) { 5643 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5644 "setProcessImportant()"); 5645 synchronized(this) { 5646 boolean changed = false; 5647 5648 ProcessRecord pr = null; 5649 synchronized (mPidsSelfLocked) { 5650 pr = mPidsSelfLocked.get(pid); 5651 if (pr == null && isForeground) { 5652 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 5653 return; 5654 } 5655 ImportanceToken oldToken = mImportantProcesses.get(pid); 5656 if (oldToken != null) { 5657 oldToken.token.unlinkToDeath(oldToken, 0); 5658 mImportantProcesses.remove(pid); 5659 if (pr != null) { 5660 pr.mState.setForcingToImportant(null); 5661 } 5662 changed = true; 5663 } 5664 if (isForeground && token != null) { 5665 ImportanceToken newToken = new ImportanceToken(pid, token, reason) { 5666 @Override 5667 public void binderDied() { 5668 importanceTokenDied(this); 5669 } 5670 }; 5671 try { 5672 token.linkToDeath(newToken, 0); 5673 mImportantProcesses.put(pid, newToken); 5674 pr.mState.setForcingToImportant(newToken); 5675 changed = true; 5676 } catch (RemoteException e) { 5677 // If the process died while doing this, we will later 5678 // do the cleanup with the process death link. 5679 } 5680 } 5681 } 5682 5683 if (changed) { 5684 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 5685 } 5686 } 5687 } 5688 isAppForeground(int uid)5689 private boolean isAppForeground(int uid) { 5690 synchronized (mProcLock) { 5691 UidRecord uidRec = mProcessList.mActiveUids.get(uid); 5692 if (uidRec == null || uidRec.isIdle()) { 5693 return false; 5694 } 5695 return uidRec.getCurProcState() <= PROCESS_STATE_IMPORTANT_FOREGROUND; 5696 } 5697 } 5698 isAppBad(final String processName, final int uid)5699 private boolean isAppBad(final String processName, final int uid) { 5700 return mAppErrors.isBadProcess(processName, uid); 5701 } 5702 5703 // NOTE: this is an internal method used by the OnShellCommand implementation only and should 5704 // be guarded by permission checking. getUidState(int uid)5705 int getUidState(int uid) { 5706 synchronized (mProcLock) { 5707 return mProcessList.getUidProcStateLOSP(uid); 5708 } 5709 } 5710 5711 @GuardedBy("this") getUidStateLocked(int uid)5712 int getUidStateLocked(int uid) { 5713 return mProcessList.getUidProcStateLOSP(uid); 5714 } 5715 5716 // ========================================================= 5717 // PROCESS INFO 5718 // ========================================================= 5719 5720 static class ProcessInfoService extends IProcessInfoService.Stub { 5721 final ActivityManagerService mActivityManagerService; ProcessInfoService(ActivityManagerService activityManagerService)5722 ProcessInfoService(ActivityManagerService activityManagerService) { 5723 mActivityManagerService = activityManagerService; 5724 } 5725 5726 @Override getProcessStatesFromPids( int[] pids, int[] states)5727 public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) { 5728 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 5729 /*in*/ pids, /*out*/ states, null); 5730 } 5731 5732 @Override getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5733 public void getProcessStatesAndOomScoresFromPids( 5734 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 5735 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 5736 /*in*/ pids, /*out*/ states, /*out*/ scores); 5737 } 5738 } 5739 5740 /** 5741 * For each PID in the given input array, write the current process state 5742 * for that process into the states array, or -1 to indicate that no 5743 * process with the given PID exists. If scores array is provided, write 5744 * the oom score for the process into the scores array, with INVALID_ADJ 5745 * indicating the PID doesn't exist. 5746 */ getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5747 public void getProcessStatesAndOomScoresForPIDs( 5748 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 5749 if (scores != null) { 5750 enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE, 5751 "getProcessStatesAndOomScoresForPIDs()"); 5752 } 5753 5754 if (pids == null) { 5755 throw new NullPointerException("pids"); 5756 } else if (states == null) { 5757 throw new NullPointerException("states"); 5758 } else if (pids.length != states.length) { 5759 throw new IllegalArgumentException("pids and states arrays have different lengths!"); 5760 } else if (scores != null && pids.length != scores.length) { 5761 throw new IllegalArgumentException("pids and scores arrays have different lengths!"); 5762 } 5763 5764 synchronized (mProcLock) { 5765 synchronized (mPidsSelfLocked) { 5766 int newestTimeIndex = -1; 5767 long newestTime = Long.MIN_VALUE; 5768 for (int i = 0; i < pids.length; i++) { 5769 ProcessRecord pr = mPidsSelfLocked.get(pids[i]); 5770 if (pr != null) { 5771 final long pendingTopTime = 5772 mPendingStartActivityUids.getPendingTopPidTime(pr.uid, pids[i]); 5773 if (pendingTopTime != PendingStartActivityUids.INVALID_TIME) { 5774 // The uid in mPendingStartActivityUids gets the TOP process state. 5775 states[i] = PROCESS_STATE_TOP; 5776 if (scores != null) { 5777 // The uid in mPendingStartActivityUids gets a better score. 5778 scores[i] = ProcessList.FOREGROUND_APP_ADJ - 1; 5779 } 5780 if (pendingTopTime > newestTime) { 5781 newestTimeIndex = i; 5782 newestTime = pendingTopTime; 5783 } 5784 } else { 5785 states[i] = pr.mState.getCurProcState(); 5786 if (scores != null) { 5787 scores[i] = pr.mState.getCurAdj(); 5788 } 5789 } 5790 } else { 5791 states[i] = PROCESS_STATE_NONEXISTENT; 5792 if (scores != null) { 5793 scores[i] = ProcessList.INVALID_ADJ; 5794 } 5795 } 5796 } 5797 // The uid with the newest timestamp in mPendingStartActivityUids gets the best 5798 // score. 5799 if (newestTimeIndex != -1) { 5800 if (scores != null) { 5801 scores[newestTimeIndex] = ProcessList.FOREGROUND_APP_ADJ - 2; 5802 } 5803 } 5804 } 5805 } 5806 } 5807 5808 // ========================================================= 5809 // PERMISSIONS 5810 // ========================================================= 5811 5812 static class PermissionController extends IPermissionController.Stub { 5813 ActivityManagerService mActivityManagerService; PermissionController(ActivityManagerService activityManagerService)5814 PermissionController(ActivityManagerService activityManagerService) { 5815 mActivityManagerService = activityManagerService; 5816 } 5817 5818 @Override checkPermission(String permission, int pid, int uid)5819 public boolean checkPermission(String permission, int pid, int uid) { 5820 return mActivityManagerService.checkPermission(permission, pid, 5821 uid) == PackageManager.PERMISSION_GRANTED; 5822 } 5823 5824 @Override noteOp(String op, int uid, String packageName)5825 public int noteOp(String op, int uid, String packageName) { 5826 // TODO moltmann: Allow to specify featureId 5827 return mActivityManagerService.mAppOpsService 5828 .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName, null, 5829 false, "", false).getOpMode(); 5830 } 5831 5832 @Override getPackagesForUid(int uid)5833 public String[] getPackagesForUid(int uid) { 5834 return mActivityManagerService.mContext.getPackageManager() 5835 .getPackagesForUid(uid); 5836 } 5837 5838 @Override isRuntimePermission(String permission)5839 public boolean isRuntimePermission(String permission) { 5840 try { 5841 PermissionInfo info = mActivityManagerService.mContext.getPackageManager() 5842 .getPermissionInfo(permission, 0); 5843 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 5844 == PermissionInfo.PROTECTION_DANGEROUS; 5845 } catch (NameNotFoundException nnfe) { 5846 Slog.e(TAG, "No such permission: "+ permission, nnfe); 5847 } 5848 return false; 5849 } 5850 5851 @Override getPackageUid(String packageName, int flags)5852 public int getPackageUid(String packageName, int flags) { 5853 try { 5854 return mActivityManagerService.mContext.getPackageManager() 5855 .getPackageUid(packageName, flags); 5856 } catch (NameNotFoundException nnfe) { 5857 return -1; 5858 } 5859 } 5860 } 5861 5862 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 5863 @Override checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5864 public int checkComponentPermission(String permission, int pid, int uid, 5865 int owningUid, boolean exported) { 5866 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 5867 owningUid, exported); 5868 } 5869 5870 @Override getAMSLock()5871 public Object getAMSLock() { 5872 return ActivityManagerService.this; 5873 } 5874 } 5875 checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5876 public static int checkComponentPermission(String permission, int pid, int uid, 5877 int owningUid, boolean exported) { 5878 if (pid == MY_PID) { 5879 return PackageManager.PERMISSION_GRANTED; 5880 } 5881 // If there is an explicit permission being checked, and this is coming from a process 5882 // that has been denied access to that permission, then just deny. Ultimately this may 5883 // not be quite right -- it means that even if the caller would have access for another 5884 // reason (such as being the owner of the component it is trying to access), it would still 5885 // fail. This also means the system and root uids would be able to deny themselves 5886 // access to permissions, which... well okay. ¯\_(ツ)_/¯ 5887 if (permission != null) { 5888 synchronized (sActiveProcessInfoSelfLocked) { 5889 ProcessInfo procInfo = sActiveProcessInfoSelfLocked.get(pid); 5890 if (procInfo != null && procInfo.deniedPermissions != null 5891 && procInfo.deniedPermissions.contains(permission)) { 5892 return PackageManager.PERMISSION_DENIED; 5893 } 5894 } 5895 } 5896 return ActivityManager.checkComponentPermission(permission, uid, 5897 owningUid, exported); 5898 } 5899 enforceDebuggable(ProcessRecord proc)5900 private void enforceDebuggable(ProcessRecord proc) { 5901 if (!Build.IS_DEBUGGABLE && !proc.isDebuggable()) { 5902 throw new SecurityException("Process not debuggable: " + proc.info.packageName); 5903 } 5904 } 5905 enforceDebuggable(ApplicationInfo info)5906 private void enforceDebuggable(ApplicationInfo info) { 5907 if (!Build.IS_DEBUGGABLE && (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 5908 throw new SecurityException("Process not debuggable: " + info.packageName); 5909 } 5910 } 5911 5912 /** 5913 * As the only public entry point for permissions checking, this method 5914 * can enforce the semantic that requesting a check on a null global 5915 * permission is automatically denied. (Internally a null permission 5916 * string is used when calling {@link #checkComponentPermission} in cases 5917 * when only uid-based security is needed.) 5918 * 5919 * This can be called with or without the global lock held. 5920 */ 5921 @Override checkPermission(String permission, int pid, int uid)5922 public int checkPermission(String permission, int pid, int uid) { 5923 if (permission == null) { 5924 return PackageManager.PERMISSION_DENIED; 5925 } 5926 return checkComponentPermission(permission, pid, uid, -1, true); 5927 } 5928 5929 /** 5930 * Binder IPC calls go through the public entry point. 5931 * This can be called with or without the global lock held. 5932 */ checkCallingPermission(String permission)5933 int checkCallingPermission(String permission) { 5934 return checkPermission(permission, 5935 Binder.getCallingPid(), 5936 Binder.getCallingUid()); 5937 } 5938 5939 /** 5940 * This can be called with or without the global lock held. 5941 */ enforceCallingPermission(String permission, String func)5942 void enforceCallingPermission(String permission, String func) { 5943 if (checkCallingPermission(permission) 5944 == PackageManager.PERMISSION_GRANTED) { 5945 return; 5946 } 5947 5948 String msg = "Permission Denial: " + func + " from pid=" 5949 + Binder.getCallingPid() 5950 + ", uid=" + Binder.getCallingUid() 5951 + " requires " + permission; 5952 Slog.w(TAG, msg); 5953 throw new SecurityException(msg); 5954 } 5955 5956 /** 5957 * This can be called with or without the global lock held. 5958 */ enforcePermission(String permission, int pid, int uid, String func)5959 void enforcePermission(String permission, int pid, int uid, String func) { 5960 if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) { 5961 return; 5962 } 5963 5964 String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid 5965 + " requires " + permission; 5966 Slog.w(TAG, msg); 5967 throw new SecurityException(msg); 5968 } 5969 isAppStartModeDisabled(int uid, String packageName)5970 public boolean isAppStartModeDisabled(int uid, String packageName) { 5971 synchronized (mProcLock) { 5972 return getAppStartModeLOSP(uid, packageName, 0, -1, false, true, false) 5973 == ActivityManager.APP_START_MODE_DISABLED; 5974 } 5975 } 5976 isInRestrictedBucket(int userId, String packageName, long nowElapsed)5977 private boolean isInRestrictedBucket(int userId, String packageName, long nowElapsed) { 5978 return UsageStatsManager.STANDBY_BUCKET_RESTRICTED 5979 <= mUsageStatsService.getAppStandbyBucket(packageName, userId, nowElapsed); 5980 } 5981 5982 // Unified app-op and target sdk check 5983 @GuardedBy(anyOf = {"this", "mProcLock"}) appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)5984 int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) { 5985 // Apps that target O+ are always subject to background check 5986 if (packageTargetSdk >= Build.VERSION_CODES.O) { 5987 if (DEBUG_BACKGROUND_CHECK) { 5988 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted"); 5989 } 5990 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 5991 } 5992 // It's a legacy app. If it's in the RESTRICTED bucket, always restrict on battery. 5993 if (mOnBattery // Short-circuit in common case. 5994 && mConstants.FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS 5995 && isInRestrictedBucket( 5996 UserHandle.getUserId(uid), packageName, SystemClock.elapsedRealtime())) { 5997 if (DEBUG_BACKGROUND_CHECK) { 5998 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " in RESTRICTED bucket"); 5999 } 6000 return ActivityManager.APP_START_MODE_DELAYED; 6001 } 6002 // Not in the RESTRICTED bucket so policy is based on AppOp check. 6003 int appop = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_RUN_IN_BACKGROUND, 6004 uid, packageName, null, ""); 6005 if (DEBUG_BACKGROUND_CHECK) { 6006 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop); 6007 } 6008 switch (appop) { 6009 case AppOpsManager.MODE_ALLOWED: 6010 // If force-background-check is enabled, restrict all apps that aren't allowlisted. 6011 if (mForceBackgroundCheck && 6012 !UserHandle.isCore(uid) && 6013 !isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ true)) { 6014 if (DEBUG_BACKGROUND_CHECK) { 6015 Slog.i(TAG, "Force background check: " + 6016 uid + "/" + packageName + " restricted"); 6017 } 6018 return ActivityManager.APP_START_MODE_DELAYED; 6019 } 6020 return ActivityManager.APP_START_MODE_NORMAL; 6021 case AppOpsManager.MODE_IGNORED: 6022 return ActivityManager.APP_START_MODE_DELAYED; 6023 default: 6024 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 6025 } 6026 } 6027 6028 // Service launch is available to apps with run-in-background exemptions but 6029 // some other background operations are not. If we're doing a check 6030 // of service-launch policy, allow those callers to proceed unrestricted. 6031 @GuardedBy(anyOf = {"this", "mProcLock"}) appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6032 int appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) { 6033 // Persistent app? 6034 if (mPackageManagerInt.isPackagePersistent(packageName)) { 6035 if (DEBUG_BACKGROUND_CHECK) { 6036 Slog.i(TAG, "App " + uid + "/" + packageName 6037 + " is persistent; not restricted in background"); 6038 } 6039 return ActivityManager.APP_START_MODE_NORMAL; 6040 } 6041 6042 // Non-persistent but background whitelisted? 6043 if (uidOnBackgroundAllowlistLOSP(uid)) { 6044 if (DEBUG_BACKGROUND_CHECK) { 6045 Slog.i(TAG, "App " + uid + "/" + packageName 6046 + " on background allowlist; not restricted in background"); 6047 } 6048 return ActivityManager.APP_START_MODE_NORMAL; 6049 } 6050 6051 // Is this app on the battery whitelist? 6052 if (isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ false)) { 6053 if (DEBUG_BACKGROUND_CHECK) { 6054 Slog.i(TAG, "App " + uid + "/" + packageName 6055 + " on idle allowlist; not restricted in background"); 6056 } 6057 return ActivityManager.APP_START_MODE_NORMAL; 6058 } 6059 6060 // None of the service-policy criteria apply, so we apply the common criteria 6061 return appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk); 6062 } 6063 6064 @GuardedBy(anyOf = {"this", "mProcLock"}) getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6065 int getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, 6066 int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) { 6067 if (mInternal.isPendingTopUid(uid)) { 6068 return ActivityManager.APP_START_MODE_NORMAL; 6069 } 6070 UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 6071 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg=" 6072 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle=" 6073 + (uidRec != null ? uidRec.isIdle() : false)); 6074 if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.isIdle()) { 6075 boolean ephemeral; 6076 if (uidRec == null) { 6077 ephemeral = getPackageManagerInternal().isPackageEphemeral( 6078 UserHandle.getUserId(uid), packageName); 6079 } else { 6080 ephemeral = uidRec.isEphemeral(); 6081 } 6082 6083 if (ephemeral) { 6084 // We are hard-core about ephemeral apps not running in the background. 6085 return ActivityManager.APP_START_MODE_DISABLED; 6086 } else { 6087 if (disabledOnly) { 6088 // The caller is only interested in whether app starts are completely 6089 // disabled for the given package (that is, it is an instant app). So 6090 // we don't need to go further, which is all just seeing if we should 6091 // apply a "delayed" mode for a regular app. 6092 return ActivityManager.APP_START_MODE_NORMAL; 6093 } 6094 final int startMode = (alwaysRestrict) 6095 ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk) 6096 : appServicesRestrictedInBackgroundLOSP(uid, packageName, 6097 packageTargetSdk); 6098 if (DEBUG_BACKGROUND_CHECK) { 6099 Slog.d(TAG, "checkAllowBackground: uid=" + uid 6100 + " pkg=" + packageName + " startMode=" + startMode 6101 + " onallowlist=" + isOnDeviceIdleAllowlistLOSP(uid, false) 6102 + " onallowlist(ei)=" + isOnDeviceIdleAllowlistLOSP(uid, true)); 6103 } 6104 if (startMode == ActivityManager.APP_START_MODE_DELAYED) { 6105 // This is an old app that has been forced into a "compatible as possible" 6106 // mode of background check. To increase compatibility, we will allow other 6107 // foreground apps to cause its services to start. 6108 if (callingPid >= 0) { 6109 ProcessRecord proc; 6110 synchronized (mPidsSelfLocked) { 6111 proc = mPidsSelfLocked.get(callingPid); 6112 } 6113 if (proc != null && !ActivityManager.isProcStateBackground( 6114 proc.mState.getCurProcState())) { 6115 // Whoever is instigating this is in the foreground, so we will allow it 6116 // to go through. 6117 return ActivityManager.APP_START_MODE_NORMAL; 6118 } 6119 } 6120 } 6121 return startMode; 6122 } 6123 } 6124 return ActivityManager.APP_START_MODE_NORMAL; 6125 } 6126 6127 /** 6128 * @return whether a UID is in the system, user or temp doze allowlist. 6129 */ 6130 @GuardedBy(anyOf = {"this", "mProcLock"}) isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo)6131 boolean isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo) { 6132 final int appId = UserHandle.getAppId(uid); 6133 6134 final int[] allowlist = allowExceptIdleToo 6135 ? mDeviceIdleExceptIdleAllowlist 6136 : mDeviceIdleAllowlist; 6137 6138 return Arrays.binarySearch(allowlist, appId) >= 0 6139 || Arrays.binarySearch(mDeviceIdleTempAllowlist, appId) >= 0 6140 || mPendingTempAllowlist.get(uid) != null; 6141 } 6142 6143 /** 6144 * Is the uid allowlisted to start FGS? 6145 * @param uid 6146 * @return a TempAllowListEntry if the uid is allowed. 6147 * null if the uid is not allowed. 6148 */ 6149 @Nullable 6150 @GuardedBy(anyOf = {"this", "mProcLock"}) isAllowlistedForFgsStartLOSP(int uid)6151 FgsTempAllowListItem isAllowlistedForFgsStartLOSP(int uid) { 6152 if (Arrays.binarySearch(mDeviceIdleExceptIdleAllowlist, UserHandle.getAppId(uid)) >= 0) { 6153 return FAKE_TEMP_ALLOW_LIST_ITEM; 6154 } 6155 final Pair<Long, FgsTempAllowListItem> entry = mFgsStartTempAllowList.get(uid); 6156 return entry == null ? null : entry.second; 6157 } 6158 6159 /** 6160 * @return allowlist tag for a uid from mPendingTempAllowlist, null if not currently on 6161 * the allowlist 6162 */ 6163 @GuardedBy(anyOf = {"this", "mProcLock"}) getPendingTempAllowlistTagForUidLOSP(int uid)6164 String getPendingTempAllowlistTagForUidLOSP(int uid) { 6165 final PendingTempAllowlist ptw = mPendingTempAllowlist.get(uid); 6166 return ptw != null ? ptw.tag : null; 6167 } 6168 6169 @VisibleForTesting grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId)6170 public void grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId) { 6171 getPackageManagerInternal() 6172 .grantImplicitAccess(userId, intent, recipientAppId, visibleUid, true /*direct*/); 6173 } 6174 6175 /** 6176 * @param uri This uri must NOT contain an embedded userId. 6177 * @param userId The userId in which the uri is to be resolved. 6178 */ 6179 @Override checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6180 public int checkUriPermission(Uri uri, int pid, int uid, 6181 final int modeFlags, int userId, IBinder callerToken) { 6182 enforceNotIsolatedCaller("checkUriPermission"); 6183 6184 // Our own process gets to do everything. 6185 if (pid == MY_PID) { 6186 return PackageManager.PERMISSION_GRANTED; 6187 } 6188 if (uid != ROOT_UID) { // bypass the root 6189 if (mPackageManagerInt.filterAppAccess(uid, Binder.getCallingUid())) { 6190 return PackageManager.PERMISSION_DENIED; 6191 } 6192 } 6193 return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, modeFlags), uid, modeFlags) 6194 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED; 6195 } 6196 6197 @Override checkUriPermissions(@onNull List<Uri> uris, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6198 public int[] checkUriPermissions(@NonNull List<Uri> uris, int pid, int uid, 6199 final int modeFlags, int userId, IBinder callerToken) { 6200 final int size = uris.size(); 6201 int[] res = new int[size]; 6202 // Default value DENIED. 6203 Arrays.fill(res, PackageManager.PERMISSION_DENIED); 6204 6205 for (int i = 0; i < size; i++) { 6206 final Uri uri = uris.get(i); 6207 final int userIdFromUri = ContentProvider.getUserIdFromUri(uri, userId); 6208 res[i] = checkUriPermission(ContentProvider.getUriWithoutUserId(uri), pid, uid, 6209 modeFlags, userIdFromUri, callerToken); 6210 } 6211 return res; 6212 } 6213 6214 /** 6215 * @param uri This uri must NOT contain an embedded userId. 6216 * @param userId The userId in which the uri is to be resolved. 6217 */ 6218 @Override grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6219 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 6220 final int modeFlags, int userId) { 6221 enforceNotIsolatedCaller("grantUriPermission"); 6222 GrantUri grantUri = new GrantUri(userId, uri, modeFlags); 6223 synchronized (this) { 6224 final ProcessRecord r = getRecordForAppLOSP(caller); 6225 if (r == null) { 6226 throw new SecurityException("Unable to find app for caller " 6227 + caller 6228 + " when granting permission to uri " + grantUri); 6229 } 6230 if (targetPkg == null) { 6231 throw new IllegalArgumentException("null target"); 6232 } 6233 final int callingUserId = UserHandle.getUserId(r.uid); 6234 if (mPackageManagerInt.filterAppAccess(targetPkg, r.uid, callingUserId)) { 6235 return; 6236 } 6237 6238 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 6239 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 6240 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 6241 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 6242 6243 final Intent intent = new Intent(); 6244 intent.setData(uri); 6245 intent.setFlags(modeFlags); 6246 6247 final NeededUriGrants needed = mUgmInternal.checkGrantUriPermissionFromIntent(intent, 6248 r.uid, targetPkg, callingUserId); 6249 mUgmInternal.grantUriPermissionUncheckedFromIntent(needed, null); 6250 } 6251 } 6252 6253 /** 6254 * @param uri This uri must NOT contain an embedded userId. 6255 * @param userId The userId in which the uri is to be resolved. 6256 */ 6257 @Override revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6258 public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, 6259 final int modeFlags, int userId) { 6260 enforceNotIsolatedCaller("revokeUriPermission"); 6261 synchronized (this) { 6262 final ProcessRecord r = getRecordForAppLOSP(caller); 6263 if (r == null) { 6264 throw new SecurityException("Unable to find app for caller " 6265 + caller 6266 + " when revoking permission to uri " + uri); 6267 } 6268 if (uri == null) { 6269 Slog.w(TAG, "revokeUriPermission: null uri"); 6270 return; 6271 } 6272 6273 if (!Intent.isAccessUriMode(modeFlags)) { 6274 return; 6275 } 6276 6277 final String authority = uri.getAuthority(); 6278 final ProviderInfo pi = mCpHelper.getProviderInfoLocked(authority, userId, 6279 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 6280 if (pi == null) { 6281 Slog.w(TAG, "No content provider found for permission revoke: " 6282 + uri.toSafeString()); 6283 return; 6284 } 6285 6286 mUgmInternal.revokeUriPermission(targetPackage, r.uid, 6287 new GrantUri(userId, uri, modeFlags), modeFlags); 6288 } 6289 } 6290 6291 @Override showWaitingForDebugger(IApplicationThread who, boolean waiting)6292 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 6293 synchronized (mProcLock) { 6294 final ProcessRecord app = who != null ? getRecordForAppLOSP(who) : null; 6295 if (app == null) return; 6296 6297 Message msg = Message.obtain(); 6298 msg.what = WAIT_FOR_DEBUGGER_UI_MSG; 6299 msg.obj = app; 6300 msg.arg1 = waiting ? 1 : 0; 6301 mUiHandler.sendMessage(msg); 6302 } 6303 } 6304 6305 @Override getMemoryInfo(ActivityManager.MemoryInfo outInfo)6306 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 6307 mProcessList.getMemoryInfo(outInfo); 6308 } 6309 6310 // ========================================================= 6311 // TASK MANAGEMENT 6312 // ========================================================= 6313 6314 @Override getTasks(int maxNum)6315 public List<RunningTaskInfo> getTasks(int maxNum) { 6316 return mActivityTaskManager.getTasks(maxNum); 6317 } 6318 6319 @Override cancelTaskWindowTransition(int taskId)6320 public void cancelTaskWindowTransition(int taskId) { 6321 mActivityTaskManager.cancelTaskWindowTransition(taskId); 6322 } 6323 6324 @Override setTaskResizeable(int taskId, int resizeableMode)6325 public void setTaskResizeable(int taskId, int resizeableMode) { 6326 mActivityTaskManager.setTaskResizeable(taskId, resizeableMode); 6327 } 6328 6329 @Override resizeTask(int taskId, Rect bounds, int resizeMode)6330 public void resizeTask(int taskId, Rect bounds, int resizeMode) { 6331 mActivityTaskManager.resizeTask(taskId, bounds, resizeMode); 6332 } 6333 6334 @Override getTaskBounds(int taskId)6335 public Rect getTaskBounds(int taskId) { 6336 return mActivityTaskManager.getTaskBounds(taskId); 6337 } 6338 6339 @Override removeTask(int taskId)6340 public boolean removeTask(int taskId) { 6341 return mActivityTaskManager.removeTask(taskId); 6342 } 6343 6344 @Override moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6345 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, 6346 int flags, Bundle bOptions) { 6347 mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions); 6348 } 6349 6350 /** 6351 * Attempts to move a task backwards in z-order (the order of activities within the task is 6352 * unchanged). 6353 * 6354 * There are several possible results of this call: 6355 * - if the task is locked, then we will show the lock toast 6356 * - if there is a task behind the provided task, then that task is made visible and resumed as 6357 * this task is moved to the back 6358 * - otherwise, if there are no other tasks in the stack: 6359 * - if this task is in the pinned stack, then we remove the stack completely, which will 6360 * have the effect of moving the task to the top or bottom of the fullscreen stack 6361 * (depending on whether it is visible) 6362 * - otherwise, we simply return home and hide this task 6363 * 6364 * @param token A reference to the activity we wish to move 6365 * @param nonRoot If false then this only works if the activity is the root 6366 * of a task; if true it will work for any activity in a task. 6367 * @return Returns true if the move completed, false if not. 6368 */ 6369 @Override moveActivityTaskToBack(IBinder token, boolean nonRoot)6370 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 6371 return ActivityClient.getInstance().moveActivityTaskToBack(token, nonRoot); 6372 } 6373 6374 @Override moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)6375 public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) { 6376 mActivityTaskManager.moveTaskToRootTask(taskId, rootTaskId, toTop); 6377 } 6378 6379 @Override getRecentTasks(int maxNum, int flags, int userId)6380 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, 6381 int userId) { 6382 return mActivityTaskManager.getRecentTasks(maxNum, flags, userId); 6383 } 6384 6385 @Override getAllRootTaskInfos()6386 public List<RootTaskInfo> getAllRootTaskInfos() { 6387 return mActivityTaskManager.getAllRootTaskInfos(); 6388 } 6389 6390 @Override getTaskForActivity(IBinder token, boolean onlyRoot)6391 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 6392 return ActivityClient.getInstance().getTaskForActivity(token, onlyRoot); 6393 } 6394 6395 @Override updateLockTaskPackages(int userId, String[] packages)6396 public void updateLockTaskPackages(int userId, String[] packages) { 6397 mActivityTaskManager.updateLockTaskPackages(userId, packages); 6398 } 6399 6400 @Override isInLockTaskMode()6401 public boolean isInLockTaskMode() { 6402 return mActivityTaskManager.isInLockTaskMode(); 6403 } 6404 6405 @Override getLockTaskModeState()6406 public int getLockTaskModeState() { 6407 return mActivityTaskManager.getLockTaskModeState(); 6408 } 6409 6410 @Override startSystemLockTaskMode(int taskId)6411 public void startSystemLockTaskMode(int taskId) throws RemoteException { 6412 mActivityTaskManager.startSystemLockTaskMode(taskId); 6413 } 6414 6415 /** 6416 * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The 6417 * PackageManager could be unavailable at construction time and therefore needs to be accessed 6418 * on demand. 6419 */ 6420 @VisibleForTesting getPackageManager()6421 public IPackageManager getPackageManager() { 6422 return AppGlobals.getPackageManager(); 6423 } 6424 6425 @VisibleForTesting getPackageManagerInternal()6426 public PackageManagerInternal getPackageManagerInternal() { 6427 // Intentionally hold no locks: in case of race conditions, the mPackageManagerInt will 6428 // be set to the same value anyway. 6429 if (mPackageManagerInt == null) { 6430 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class); 6431 } 6432 return mPackageManagerInt; 6433 } 6434 getPermissionManagerInternal()6435 private PermissionManagerServiceInternal getPermissionManagerInternal() { 6436 // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will 6437 // be set to the same value anyway. 6438 if (mPermissionManagerInt == null) { 6439 mPermissionManagerInt = 6440 LocalServices.getService(PermissionManagerServiceInternal.class); 6441 } 6442 return mPermissionManagerInt; 6443 } 6444 getTestUtilityServiceLocked()6445 private TestUtilityService getTestUtilityServiceLocked() { 6446 if (mTestUtilityService == null) { 6447 mTestUtilityService = 6448 LocalServices.getService(TestUtilityService.class); 6449 } 6450 return mTestUtilityService; 6451 } 6452 6453 @Override appNotResponding(final String reason)6454 public void appNotResponding(final String reason) { 6455 final int callingPid = Binder.getCallingPid(); 6456 6457 synchronized (mPidsSelfLocked) { 6458 final ProcessRecord app = mPidsSelfLocked.get(callingPid); 6459 if (app == null) { 6460 throw new SecurityException("Unknown process: " + callingPid); 6461 } 6462 6463 mAnrHelper.appNotResponding(app, null, app.info, null, null, false, 6464 "App requested: " + reason); 6465 } 6466 } 6467 startPersistentApps(int matchFlags)6468 void startPersistentApps(int matchFlags) { 6469 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return; 6470 6471 synchronized (this) { 6472 try { 6473 final List<ApplicationInfo> apps = AppGlobals.getPackageManager() 6474 .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList(); 6475 for (ApplicationInfo app : apps) { 6476 if (!"android".equals(app.packageName)) { 6477 final ProcessRecord proc = addAppLocked( 6478 app, null, false, null /* ABI override */, 6479 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 6480 if (proc != null) { 6481 proc.mProfile.addHostingComponentType( 6482 HOSTING_COMPONENT_TYPE_PERSISTENT); 6483 } 6484 } 6485 } 6486 } catch (RemoteException ex) { 6487 } 6488 } 6489 } 6490 6491 // ========================================================= 6492 // CONTENT PROVIDERS 6493 // ========================================================= 6494 getContentProviderHelper()6495 public ContentProviderHelper getContentProviderHelper() { 6496 return mCpHelper; 6497 } 6498 6499 @Override getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)6500 public final ContentProviderHolder getContentProvider( 6501 IApplicationThread caller, String callingPackage, String name, int userId, 6502 boolean stable) { 6503 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProvider: ", name); 6504 try { 6505 return mCpHelper.getContentProvider(caller, callingPackage, name, userId, stable); 6506 } finally { 6507 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6508 } 6509 } 6510 6511 @Override getContentProviderExternal( String name, int userId, IBinder token, String tag)6512 public ContentProviderHolder getContentProviderExternal( 6513 String name, int userId, IBinder token, String tag) { 6514 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProviderExternal: ", name); 6515 try { 6516 return mCpHelper.getContentProviderExternal(name, userId, token, tag); 6517 } finally { 6518 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6519 } 6520 } 6521 6522 /** 6523 * Drop a content provider from a ProcessRecord's bookkeeping 6524 */ 6525 @Override removeContentProvider(IBinder connection, boolean stable)6526 public void removeContentProvider(IBinder connection, boolean stable) { 6527 mCpHelper.removeContentProvider(connection, stable); 6528 } 6529 6530 /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */ 6531 @Deprecated 6532 @Override removeContentProviderExternal(String name, IBinder token)6533 public void removeContentProviderExternal(String name, IBinder token) { 6534 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternal: ", name); 6535 try { 6536 removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId()); 6537 } finally { 6538 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6539 } 6540 } 6541 6542 @Override removeContentProviderExternalAsUser(String name, IBinder token, int userId)6543 public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) { 6544 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternalAsUser: ", name); 6545 try { 6546 mCpHelper.removeContentProviderExternalAsUser(name, token, userId); 6547 } finally { 6548 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6549 } 6550 } 6551 6552 @Override publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)6553 public final void publishContentProviders(IApplicationThread caller, 6554 List<ContentProviderHolder> providers) { 6555 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 6556 final int maxLength = 256; 6557 final StringBuilder sb = new StringBuilder(maxLength); 6558 sb.append("publishContentProviders: "); 6559 if (providers != null) { 6560 boolean first = true; 6561 for (int i = 0, size = providers.size(); i < size; i++) { 6562 final ContentProviderHolder holder = providers.get(i); 6563 if (holder != null && holder.info != null && holder.info.authority != null) { 6564 final int len = holder.info.authority.length(); 6565 if (sb.length() + len > maxLength) { 6566 sb.append("[[TRUNCATED]]"); 6567 break; 6568 } 6569 if (!first) { 6570 sb.append(';'); 6571 } else { 6572 first = false; 6573 } 6574 sb.append(holder.info.authority); 6575 } 6576 } 6577 } 6578 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString()); 6579 } 6580 try { 6581 mCpHelper.publishContentProviders(caller, providers); 6582 } finally { 6583 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6584 } 6585 } 6586 6587 @Override refContentProvider(IBinder connection, int stable, int unstable)6588 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 6589 return mCpHelper.refContentProvider(connection, stable, unstable); 6590 } 6591 6592 @Override unstableProviderDied(IBinder connection)6593 public void unstableProviderDied(IBinder connection) { 6594 mCpHelper.unstableProviderDied(connection); 6595 } 6596 6597 @Override appNotRespondingViaProvider(IBinder connection)6598 public void appNotRespondingViaProvider(IBinder connection) { 6599 mCpHelper.appNotRespondingViaProvider(connection); 6600 } 6601 6602 /** 6603 * Allows apps to retrieve the MIME type of a URI. 6604 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 6605 * users, then it does not need permission to access the ContentProvider. 6606 * Either, it needs cross-user uri grants. 6607 * 6608 * CTS tests for this functionality can be run with "runtest cts-appsecurity". 6609 * 6610 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/ 6611 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java 6612 * 6613 * @deprecated -- use getProviderMimeTypeAsync. 6614 */ 6615 @Deprecated 6616 @Override getProviderMimeType(Uri uri, int userId)6617 public String getProviderMimeType(Uri uri, int userId) { 6618 return mCpHelper.getProviderMimeType(uri, userId); 6619 } 6620 6621 /** 6622 * Allows apps to retrieve the MIME type of a URI. 6623 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 6624 * users, then it does not need permission to access the ContentProvider. 6625 * Either way, it needs cross-user uri grants. 6626 */ 6627 @Override getProviderMimeTypeAsync(Uri uri, int userId, RemoteCallback resultCallback)6628 public void getProviderMimeTypeAsync(Uri uri, int userId, RemoteCallback resultCallback) { 6629 mCpHelper.getProviderMimeTypeAsync(uri, userId, resultCallback); 6630 } 6631 6632 // ========================================================= 6633 // GLOBAL MANAGEMENT 6634 // ========================================================= 6635 6636 @GuardedBy(anyOf = {"this", "mProcLock"}) uidOnBackgroundAllowlistLOSP(final int uid)6637 private boolean uidOnBackgroundAllowlistLOSP(final int uid) { 6638 final int appId = UserHandle.getAppId(uid); 6639 final int[] allowlist = mBackgroundAppIdAllowlist; 6640 for (int i = 0, len = allowlist.length; i < len; i++) { 6641 if (appId == allowlist[i]) { 6642 return true; 6643 } 6644 } 6645 return false; 6646 } 6647 6648 @Override isBackgroundRestricted(String packageName)6649 public boolean isBackgroundRestricted(String packageName) { 6650 final int callingUid = Binder.getCallingUid(); 6651 final IPackageManager pm = AppGlobals.getPackageManager(); 6652 try { 6653 final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 6654 UserHandle.getUserId(callingUid)); 6655 if (packageUid != callingUid) { 6656 throw new IllegalArgumentException("Uid " + callingUid 6657 + " cannot query restriction state for package " + packageName); 6658 } 6659 } catch (RemoteException exc) { 6660 // Ignore. 6661 } 6662 return isBackgroundRestrictedNoCheck(callingUid, packageName); 6663 } 6664 6665 @VisibleForTesting isBackgroundRestrictedNoCheck(final int uid, final String packageName)6666 public boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) { 6667 final int mode = getAppOpsManager().checkOpNoThrow(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, 6668 uid, packageName); 6669 return mode != AppOpsManager.MODE_ALLOWED; 6670 } 6671 6672 @Override backgroundAllowlistUid(final int uid)6673 public void backgroundAllowlistUid(final int uid) { 6674 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 6675 throw new SecurityException("Only the OS may call backgroundAllowlistUid()"); 6676 } 6677 6678 if (DEBUG_BACKGROUND_CHECK) { 6679 Slog.i(TAG, "Adding uid " + uid + " to bg uid allowlist"); 6680 } 6681 synchronized (this) { 6682 synchronized (mProcLock) { 6683 final int num = mBackgroundAppIdAllowlist.length; 6684 int[] newList = new int[num + 1]; 6685 System.arraycopy(mBackgroundAppIdAllowlist, 0, newList, 0, num); 6686 newList[num] = UserHandle.getAppId(uid); 6687 mBackgroundAppIdAllowlist = newList; 6688 } 6689 } 6690 } 6691 6692 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)6693 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 6694 String abiOverride, int zygotePolicyFlags) { 6695 return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */, 6696 abiOverride, zygotePolicyFlags); 6697 } 6698 6699 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags)6700 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 6701 boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags) { 6702 return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks, 6703 false /* disableTestApiChecks */, abiOverride, zygotePolicyFlags); 6704 } 6705 6706 // TODO: Move to ProcessList? 6707 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)6708 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 6709 boolean disableHiddenApiChecks, boolean disableTestApiChecks, 6710 String abiOverride, int zygotePolicyFlags) { 6711 return addAppLocked( 6712 info, 6713 customProcess, 6714 isolated, 6715 /* isSdkSandbox= */ false, 6716 /* sdkSandboxUid= */ 0, 6717 /* sdkSandboxClientAppPackage= */ null, 6718 disableHiddenApiChecks, 6719 disableTestApiChecks, 6720 abiOverride, 6721 zygotePolicyFlags); 6722 } 6723 addAppLocked( ApplicationInfo info, String customProcess, boolean isolated, boolean isSdkSandbox, int sdkSandboxUid, @Nullable String sdkSandboxClientAppPackage, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)6724 final ProcessRecord addAppLocked( 6725 ApplicationInfo info, 6726 String customProcess, 6727 boolean isolated, 6728 boolean isSdkSandbox, 6729 int sdkSandboxUid, 6730 @Nullable String sdkSandboxClientAppPackage, 6731 boolean disableHiddenApiChecks, 6732 boolean disableTestApiChecks, 6733 String abiOverride, 6734 int zygotePolicyFlags) { 6735 ProcessRecord app; 6736 if (!isolated) { 6737 app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName, 6738 info.uid); 6739 } else { 6740 app = null; 6741 } 6742 6743 if (app == null) { 6744 app = mProcessList.newProcessRecordLocked( 6745 info, 6746 customProcess, 6747 isolated, 6748 /* isolatedUid= */0, 6749 isSdkSandbox, 6750 sdkSandboxUid, 6751 sdkSandboxClientAppPackage, 6752 new HostingRecord(HostingRecord.HOSTING_TYPE_ADDED_APPLICATION, 6753 customProcess != null ? customProcess : info.processName)); 6754 updateLruProcessLocked(app, false, null); 6755 updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN); 6756 } 6757 6758 // Report usage as process is persistent and being started. 6759 mUsageStatsService.reportEvent(info.packageName, UserHandle.getUserId(app.uid), 6760 Event.APP_COMPONENT_USED); 6761 6762 // This package really, really can not be stopped. 6763 // TODO: how set package stopped state should work for sdk sandboxes? 6764 if (!isSdkSandbox) { 6765 try { 6766 AppGlobals.getPackageManager().setPackageStoppedState( 6767 info.packageName, false, UserHandle.getUserId(app.uid)); 6768 } catch (RemoteException e) { 6769 } catch (IllegalArgumentException e) { 6770 Slog.w(TAG, "Failed trying to unstop package " 6771 + info.packageName + ": " + e); 6772 } 6773 } 6774 6775 if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 6776 app.setPersistent(true); 6777 app.mState.setMaxAdj(ProcessList.PERSISTENT_PROC_ADJ); 6778 } 6779 if (app.getThread() == null && mPersistentStartingProcesses.indexOf(app) < 0) { 6780 mPersistentStartingProcesses.add(app); 6781 mProcessList.startProcessLocked(app, new HostingRecord( 6782 HostingRecord.HOSTING_TYPE_ADDED_APPLICATION, 6783 customProcess != null ? customProcess : app.processName), 6784 zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks, 6785 abiOverride); 6786 } 6787 6788 return app; 6789 } 6790 unhandledBack()6791 public void unhandledBack() { 6792 mActivityTaskManager.unhandledBack(); 6793 } 6794 6795 // TODO: Replace this method with one that returns a bound IContentProvider. openContentUri(String uriString)6796 public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException { 6797 enforceNotIsolatedCaller("openContentUri"); 6798 final int userId = UserHandle.getCallingUserId(); 6799 final Uri uri = Uri.parse(uriString); 6800 String name = uri.getAuthority(); 6801 ContentProviderHolder cph = mCpHelper.getContentProviderExternalUnchecked(name, null, 6802 Binder.getCallingUid(), "*opencontent*", userId); 6803 ParcelFileDescriptor pfd = null; 6804 if (cph != null) { 6805 try { 6806 // This method is exposed to the VNDK and to avoid changing its 6807 // signature we just use the first package in the UID. For shared 6808 // UIDs we may blame the wrong app but that is Okay as they are 6809 // in the same security/privacy sandbox. 6810 final int uid = Binder.getCallingUid(); 6811 // Here we handle some of the special UIDs (mediaserver, systemserver, etc) 6812 final String packageName = AppOpsManager.resolvePackageName(uid, 6813 /*packageName*/ null); 6814 final AndroidPackage androidPackage; 6815 if (packageName != null) { 6816 androidPackage = mPackageManagerInt.getPackage(packageName); 6817 } else { 6818 androidPackage = mPackageManagerInt.getPackage(uid); 6819 } 6820 if (androidPackage == null) { 6821 Log.e(TAG, "Cannot find package for uid: " + uid); 6822 return null; 6823 } 6824 6825 final ApplicationInfo appInfo = mPackageManagerInt.getApplicationInfo( 6826 androidPackage.getPackageName(), /*flags*/0, Process.SYSTEM_UID, 6827 UserHandle.USER_SYSTEM); 6828 if (!appInfo.isVendor() && !appInfo.isSystemApp() && !appInfo.isSystemExt() 6829 && !appInfo.isProduct()) { 6830 Log.e(TAG, "openContentUri may only be used by vendor/system/product."); 6831 return null; 6832 } 6833 6834 final AttributionSource attributionSource = new AttributionSource( 6835 Binder.getCallingUid(), androidPackage.getPackageName(), null); 6836 pfd = cph.provider.openFile(attributionSource, uri, "r", null); 6837 } catch (FileNotFoundException e) { 6838 // do nothing; pfd will be returned null 6839 } finally { 6840 // Ensure we're done with the provider. 6841 mCpHelper.removeContentProviderExternalUnchecked(name, null, userId); 6842 } 6843 } else { 6844 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 6845 } 6846 return pfd; 6847 } 6848 reportGlobalUsageEvent(int event)6849 void reportGlobalUsageEvent(int event) { 6850 final int currentUserId = mUserController.getCurrentUserId(); 6851 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, currentUserId, event); 6852 int[] profiles = mUserController.getCurrentProfileIds(); 6853 if (profiles != null) { 6854 for (int i = profiles.length - 1; i >= 0; i--) { 6855 if (profiles[i] == currentUserId) { 6856 continue; 6857 } 6858 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, profiles[i], event); 6859 } 6860 } 6861 } 6862 reportCurWakefulnessUsageEvent()6863 void reportCurWakefulnessUsageEvent() { 6864 reportGlobalUsageEvent(mWakefulness.get() == PowerManagerInternal.WAKEFULNESS_AWAKE 6865 ? UsageEvents.Event.SCREEN_INTERACTIVE 6866 : UsageEvents.Event.SCREEN_NON_INTERACTIVE); 6867 } 6868 onWakefulnessChanged(int wakefulness)6869 void onWakefulnessChanged(int wakefulness) { 6870 synchronized (this) { 6871 boolean wasAwake = mWakefulness.getAndSet(wakefulness) 6872 == PowerManagerInternal.WAKEFULNESS_AWAKE; 6873 boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE; 6874 6875 if (wasAwake != isAwake) { 6876 // Also update state in a special way for running foreground services UI. 6877 mServices.updateScreenStateLocked(isAwake); 6878 reportCurWakefulnessUsageEvent(); 6879 mActivityTaskManager.onScreenAwakeChanged(isAwake); 6880 mOomAdjProfiler.onWakefulnessChanged(wakefulness); 6881 mOomAdjuster.onWakefulnessChanged(wakefulness); 6882 } 6883 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 6884 } 6885 } 6886 6887 @Override notifyCleartextNetwork(int uid, byte[] firstPacket)6888 public void notifyCleartextNetwork(int uid, byte[] firstPacket) { 6889 mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget(); 6890 } 6891 6892 @Override shutdown(int timeout)6893 public boolean shutdown(int timeout) { 6894 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 6895 != PackageManager.PERMISSION_GRANTED) { 6896 throw new SecurityException("Requires permission " 6897 + android.Manifest.permission.SHUTDOWN); 6898 } 6899 6900 final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout); 6901 6902 mAppOpsService.shutdown(); 6903 if (mUsageStatsService != null) { 6904 mUsageStatsService.prepareShutdown(); 6905 } 6906 mBatteryStatsService.shutdown(); 6907 mProcessStats.shutdown(); 6908 6909 return timedout; 6910 } 6911 6912 @Override notifyLockedProfile(@serIdInt int userId)6913 public void notifyLockedProfile(@UserIdInt int userId) { 6914 mAtmInternal.notifyLockedProfile(userId, mUserController.getCurrentUserId()); 6915 } 6916 6917 @Override startConfirmDeviceCredentialIntent(Intent intent, Bundle options)6918 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) { 6919 mAtmInternal.startConfirmDeviceCredentialIntent(intent, options); 6920 } 6921 6922 @Override stopAppSwitches()6923 public void stopAppSwitches() { 6924 mActivityTaskManager.stopAppSwitches(); 6925 } 6926 6927 @Override resumeAppSwitches()6928 public void resumeAppSwitches() { 6929 mActivityTaskManager.resumeAppSwitches(); 6930 } 6931 setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)6932 public void setDebugApp(String packageName, boolean waitForDebugger, 6933 boolean persistent) { 6934 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 6935 "setDebugApp()"); 6936 6937 final long ident = Binder.clearCallingIdentity(); 6938 try { 6939 // Note that this is not really thread safe if there are multiple 6940 // callers into it at the same time, but that's not a situation we 6941 // care about. 6942 if (persistent) { 6943 final ContentResolver resolver = mContext.getContentResolver(); 6944 Settings.Global.putString( 6945 resolver, Settings.Global.DEBUG_APP, 6946 packageName); 6947 Settings.Global.putInt( 6948 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 6949 waitForDebugger ? 1 : 0); 6950 } 6951 6952 synchronized (this) { 6953 if (!persistent) { 6954 mOrigDebugApp = mDebugApp; 6955 mOrigWaitForDebugger = mWaitForDebugger; 6956 } 6957 mDebugApp = packageName; 6958 mWaitForDebugger = waitForDebugger; 6959 mDebugTransient = !persistent; 6960 if (packageName != null) { 6961 forceStopPackageLocked(packageName, -1, false, false, true, true, 6962 false, UserHandle.USER_ALL, "set debug app"); 6963 } 6964 } 6965 } finally { 6966 Binder.restoreCallingIdentity(ident); 6967 } 6968 } 6969 6970 /** 6971 * Set or remove an agent to be run whenever an app with the given process name starts. 6972 * 6973 * This method will not check whether the given process name matches a debuggable app. That 6974 * would require scanning all current packages, and a rescan when new packages are installed 6975 * or updated. 6976 * 6977 * Instead, do the check when an application is started and matched to a stored agent. 6978 * 6979 * @param packageName the process name of the app. 6980 * @param agent the agent string to be used, or null to remove any previously set agent. 6981 */ 6982 @Override setAgentApp(@onNull String packageName, @Nullable String agent)6983 public void setAgentApp(@NonNull String packageName, @Nullable String agent) { 6984 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 6985 // its own permission. 6986 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 6987 != PackageManager.PERMISSION_GRANTED) { 6988 throw new SecurityException( 6989 "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER); 6990 } 6991 6992 synchronized (mAppProfiler.mProfilerLock) { 6993 mAppProfiler.setAgentAppLPf(packageName, agent); 6994 } 6995 } 6996 setTrackAllocationApp(ApplicationInfo app, String processName)6997 void setTrackAllocationApp(ApplicationInfo app, String processName) { 6998 enforceDebuggable(app); 6999 7000 synchronized (mProcLock) { 7001 mTrackAllocationApp = processName; 7002 } 7003 } 7004 setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo, ApplicationInfo sdkSandboxClientApp)7005 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo, 7006 ApplicationInfo sdkSandboxClientApp) { 7007 synchronized (mAppProfiler.mProfilerLock) { 7008 if (!Build.IS_DEBUGGABLE) { 7009 boolean isAppDebuggable = (app.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 7010 boolean isAppProfileable = app.isProfileableByShell(); 7011 7012 if (sdkSandboxClientApp != null) { 7013 isAppDebuggable |= 7014 (sdkSandboxClientApp.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 7015 isAppProfileable |= sdkSandboxClientApp.isProfileableByShell(); 7016 } 7017 if (!isAppDebuggable && !isAppProfileable) { 7018 throw new SecurityException("Process not debuggable, " 7019 + "and not profileable by shell: " + app.packageName); 7020 } 7021 } 7022 mAppProfiler.setProfileAppLPf(processName, profilerInfo); 7023 } 7024 } 7025 setNativeDebuggingAppLocked(ApplicationInfo app, String processName)7026 void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) { 7027 enforceDebuggable(app); 7028 mNativeDebuggingApp = processName; 7029 } 7030 7031 @Override setAlwaysFinish(boolean enabled)7032 public void setAlwaysFinish(boolean enabled) { 7033 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 7034 "setAlwaysFinish()"); 7035 7036 final long ident = Binder.clearCallingIdentity(); 7037 try { 7038 Settings.Global.putInt( 7039 mContext.getContentResolver(), 7040 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 7041 7042 synchronized (this) { 7043 mAlwaysFinishActivities = enabled; 7044 } 7045 } finally { 7046 Binder.restoreCallingIdentity(ident); 7047 } 7048 } 7049 7050 @Override setActivityController(IActivityController controller, boolean imAMonkey)7051 public void setActivityController(IActivityController controller, boolean imAMonkey) { 7052 if (controller != null) { 7053 Binder.allowBlocking(controller.asBinder()); 7054 } 7055 mActivityTaskManager.setActivityController(controller, imAMonkey); 7056 } 7057 7058 @Override setUserIsMonkey(boolean userIsMonkey)7059 public void setUserIsMonkey(boolean userIsMonkey) { 7060 synchronized (mProcLock) { 7061 synchronized (mPidsSelfLocked) { 7062 final int callingPid = Binder.getCallingPid(); 7063 ProcessRecord proc = mPidsSelfLocked.get(callingPid); 7064 if (proc == null) { 7065 throw new SecurityException("Unknown process: " + callingPid); 7066 } 7067 if (proc.getActiveInstrumentation() == null 7068 || proc.getActiveInstrumentation().mUiAutomationConnection == null) { 7069 throw new SecurityException("Only an instrumentation process " 7070 + "with a UiAutomation can call setUserIsMonkey"); 7071 } 7072 } 7073 mUserIsMonkey = userIsMonkey; 7074 } 7075 } 7076 7077 @Override isUserAMonkey()7078 public boolean isUserAMonkey() { 7079 synchronized (mProcLock) { 7080 // If there is a controller also implies the user is a monkey. 7081 return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey(); 7082 } 7083 } 7084 7085 @Override requestSystemServerHeapDump()7086 public void requestSystemServerHeapDump() { 7087 if (!Build.IS_DEBUGGABLE) { 7088 Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build"); 7089 return; 7090 } 7091 if (Binder.getCallingUid() != SYSTEM_UID) { 7092 // This also intentionally excludes secondary profiles from calling this. 7093 throw new SecurityException( 7094 "Only the system process is allowed to request a system heap dump"); 7095 } 7096 ProcessRecord pr; 7097 synchronized (mPidsSelfLocked) { 7098 pr = mPidsSelfLocked.get(myPid()); 7099 } 7100 if (pr == null) { 7101 Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid()); 7102 return; 7103 } 7104 synchronized (mAppProfiler.mProfilerLock) { 7105 mAppProfiler.startHeapDumpLPf(pr.mProfile, true); 7106 } 7107 } 7108 7109 /** 7110 * Takes a bugreport using bug report API ({@code BugreportManager}) with no pre-set 7111 * title and description 7112 */ 7113 @Override requestBugReport(@ugreportParams.BugreportMode int bugreportType)7114 public void requestBugReport(@BugreportParams.BugreportMode int bugreportType) { 7115 requestBugReportWithDescription(null, null, bugreportType, 0L); 7116 } 7117 7118 /** 7119 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 7120 * triggered by sending a broadcast to Shell. 7121 */ 7122 @Override requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType)7123 public void requestBugReportWithDescription(@Nullable String shareTitle, 7124 @Nullable String shareDescription, int bugreportType) { 7125 requestBugReportWithDescription(shareTitle, shareDescription, bugreportType, /*nonce*/ 0L); 7126 } 7127 7128 /** 7129 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 7130 * triggered by sending a broadcast to Shell. 7131 */ requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType, long nonce)7132 public void requestBugReportWithDescription(@Nullable String shareTitle, 7133 @Nullable String shareDescription, int bugreportType, long nonce) { 7134 String type = null; 7135 switch (bugreportType) { 7136 case BugreportParams.BUGREPORT_MODE_FULL: 7137 type = "bugreportfull"; 7138 break; 7139 case BugreportParams.BUGREPORT_MODE_INTERACTIVE: 7140 type = "bugreportplus"; 7141 break; 7142 case BugreportParams.BUGREPORT_MODE_REMOTE: 7143 type = "bugreportremote"; 7144 break; 7145 case BugreportParams.BUGREPORT_MODE_WEAR: 7146 type = "bugreportwear"; 7147 break; 7148 case BugreportParams.BUGREPORT_MODE_TELEPHONY: 7149 type = "bugreporttelephony"; 7150 break; 7151 case BugreportParams.BUGREPORT_MODE_WIFI: 7152 type = "bugreportwifi"; 7153 break; 7154 default: 7155 throw new IllegalArgumentException( 7156 "Provided bugreport type is not correct, value: " 7157 + bugreportType); 7158 } 7159 // Always log caller, even if it does not have permission to dump. 7160 Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid()); 7161 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 7162 7163 if (!TextUtils.isEmpty(shareTitle)) { 7164 if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) { 7165 String errorStr = "shareTitle should be less than " 7166 + MAX_BUGREPORT_TITLE_SIZE + " characters"; 7167 throw new IllegalArgumentException(errorStr); 7168 } 7169 if (!TextUtils.isEmpty(shareDescription)) { 7170 if (shareDescription.length() > MAX_BUGREPORT_DESCRIPTION_SIZE) { 7171 String errorStr = "shareDescription should be less than " 7172 + MAX_BUGREPORT_DESCRIPTION_SIZE + " characters"; 7173 throw new IllegalArgumentException(errorStr); 7174 } 7175 } 7176 Slog.d(TAG, "Bugreport notification title " + shareTitle 7177 + " description " + shareDescription); 7178 } 7179 // Create intent to trigger Bugreport API via Shell 7180 Intent triggerShellBugreport = new Intent(); 7181 triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED); 7182 triggerShellBugreport.setPackage(SHELL_APP_PACKAGE); 7183 triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType); 7184 triggerShellBugreport.putExtra(EXTRA_BUGREPORT_NONCE, nonce); 7185 triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 7186 triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 7187 if (shareTitle != null) { 7188 triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle); 7189 } 7190 if (shareDescription != null) { 7191 triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription); 7192 } 7193 final long identity = Binder.clearCallingIdentity(); 7194 try { 7195 // Send broadcast to shell to trigger bugreport using Bugreport API 7196 mContext.sendBroadcastAsUser(triggerShellBugreport, UserHandle.SYSTEM); 7197 } finally { 7198 Binder.restoreCallingIdentity(identity); 7199 } 7200 } 7201 7202 /** 7203 * Takes a telephony bugreport with title and description 7204 */ 7205 @Override requestTelephonyBugReport(String shareTitle, String shareDescription)7206 public void requestTelephonyBugReport(String shareTitle, String shareDescription) { 7207 requestBugReportWithDescription(shareTitle, shareDescription, 7208 BugreportParams.BUGREPORT_MODE_TELEPHONY); 7209 } 7210 7211 /** 7212 * Takes a minimal bugreport of Wifi-related state with pre-set title and description 7213 */ 7214 @Override requestWifiBugReport(String shareTitle, String shareDescription)7215 public void requestWifiBugReport(String shareTitle, String shareDescription) { 7216 requestBugReportWithDescription(shareTitle, shareDescription, 7217 BugreportParams.BUGREPORT_MODE_WIFI); 7218 } 7219 7220 /** 7221 * Takes an interactive bugreport with a progress notification 7222 */ 7223 @Override requestInteractiveBugReport()7224 public void requestInteractiveBugReport() { 7225 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE); 7226 } 7227 7228 /** 7229 * Takes an interactive bugreport with a progress notification. Also, shows the given title and 7230 * description on the final share notification 7231 */ 7232 @Override requestInteractiveBugReportWithDescription(String shareTitle, String shareDescription)7233 public void requestInteractiveBugReportWithDescription(String shareTitle, 7234 String shareDescription) { 7235 requestBugReportWithDescription(shareTitle, shareDescription, 7236 BugreportParams.BUGREPORT_MODE_INTERACTIVE); 7237 } 7238 7239 /** 7240 * Takes a bugreport with minimal user interference 7241 */ 7242 @Override requestFullBugReport()7243 public void requestFullBugReport() { 7244 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_FULL); 7245 } 7246 7247 /** 7248 * Takes a bugreport remotely 7249 */ 7250 @Override requestRemoteBugReport(long nonce)7251 public void requestRemoteBugReport(long nonce) { 7252 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE, nonce); 7253 } 7254 7255 /** 7256 * Launches a bugreport-whitelisted app to handle a bugreport. 7257 * 7258 * <p>Allows a bug report handler app to take bugreports on the user's behalf. The handler can 7259 * be predefined in the config, meant to be launched with the primary user. The user can 7260 * override this with a different (or same) handler app on possibly a different user. This is 7261 * useful for capturing bug reports from work profile, for instance. 7262 * 7263 * @return true if there is a bugreport-whitelisted app to handle a bugreport, or false 7264 * otherwise. 7265 */ 7266 @Override launchBugReportHandlerApp()7267 public boolean launchBugReportHandlerApp() { 7268 if (!BugReportHandlerUtil.isBugReportHandlerEnabled(mContext)) { 7269 return false; 7270 } 7271 7272 // Always log caller, even if it does not have permission to dump. 7273 Slog.i(TAG, "launchBugReportHandlerApp requested by UID " + Binder.getCallingUid()); 7274 enforceCallingPermission(android.Manifest.permission.DUMP, 7275 "launchBugReportHandlerApp"); 7276 7277 return BugReportHandlerUtil.launchBugReportHandlerApp(mContext); 7278 } 7279 7280 /** 7281 * Get packages of bugreport-whitelisted apps to handle a bug report. 7282 * 7283 * @return packages of bugreport-whitelisted apps to handle a bug report. 7284 */ 7285 @Override getBugreportWhitelistedPackages()7286 public List<String> getBugreportWhitelistedPackages() { 7287 enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING, 7288 "getBugreportWhitelistedPackages"); 7289 return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages()); 7290 } 7291 registerProcessObserver(IProcessObserver observer)7292 public void registerProcessObserver(IProcessObserver observer) { 7293 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 7294 "registerProcessObserver()"); 7295 mProcessList.registerProcessObserver(observer); 7296 } 7297 7298 @Override unregisterProcessObserver(IProcessObserver observer)7299 public void unregisterProcessObserver(IProcessObserver observer) { 7300 mProcessList.unregisterProcessObserver(observer); 7301 } 7302 7303 @Override getUidProcessState(int uid, String callingPackage)7304 public int getUidProcessState(int uid, String callingPackage) { 7305 if (!hasUsageStatsPermission(callingPackage)) { 7306 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 7307 "getUidProcessState"); 7308 } 7309 // In case the caller is requesting processState of an app in a different user, 7310 // then verify the caller has INTERACT_ACROSS_USERS_FULL permission 7311 mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 7312 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY, 7313 "getUidProcessState", callingPackage); // Ignore return value 7314 7315 synchronized (mProcLock) { 7316 if (mPendingStartActivityUids.isPendingTopUid(uid)) { 7317 return PROCESS_STATE_TOP; 7318 } 7319 return mProcessList.getUidProcStateLOSP(uid); 7320 } 7321 } 7322 7323 @Override getUidProcessCapabilities(int uid, String callingPackage)7324 public @ProcessCapability int getUidProcessCapabilities(int uid, String callingPackage) { 7325 if (!hasUsageStatsPermission(callingPackage)) { 7326 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 7327 "getUidProcessState"); 7328 } 7329 // In case the caller is requesting processCapabilities of an app in a different user, 7330 // then verify the caller has INTERACT_ACROSS_USERS_FULL permission 7331 mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 7332 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY, 7333 "getUidProcessCapabilities", callingPackage); // Ignore return value 7334 7335 synchronized (mProcLock) { 7336 return mProcessList.getUidProcessCapabilityLOSP(uid); 7337 } 7338 } 7339 7340 @Override registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)7341 public void registerUidObserver(IUidObserver observer, int which, int cutpoint, 7342 String callingPackage) { 7343 if (!hasUsageStatsPermission(callingPackage)) { 7344 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 7345 "registerUidObserver"); 7346 } 7347 mUidObserverController.register(observer, which, cutpoint, callingPackage, 7348 Binder.getCallingUid()); 7349 } 7350 7351 @Override unregisterUidObserver(IUidObserver observer)7352 public void unregisterUidObserver(IUidObserver observer) { 7353 mUidObserverController.unregister(observer); 7354 } 7355 7356 @Override isUidActive(int uid, String callingPackage)7357 public boolean isUidActive(int uid, String callingPackage) { 7358 if (!hasUsageStatsPermission(callingPackage)) { 7359 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 7360 "isUidActive"); 7361 } 7362 synchronized (mProcLock) { 7363 if (isUidActiveLOSP(uid)) { 7364 return true; 7365 } 7366 } 7367 return mInternal.isPendingTopUid(uid); 7368 } 7369 7370 @GuardedBy(anyOf = {"this", "mProcLock"}) isUidActiveLOSP(int uid)7371 boolean isUidActiveLOSP(int uid) { 7372 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 7373 return uidRecord != null && !uidRecord.isSetIdle(); 7374 } 7375 7376 @Override setPersistentVrThread(int tid)7377 public void setPersistentVrThread(int tid) { 7378 mActivityTaskManager.setPersistentVrThread(tid); 7379 } 7380 7381 /** 7382 * Schedule the given thread a normal scheduling priority. 7383 * 7384 * @param tid the tid of the thread to adjust the scheduling of. 7385 * @param suppressLogs {@code true} if any error logging should be disabled. 7386 * 7387 * @return {@code true} if this succeeded. 7388 */ scheduleAsRegularPriority(int tid, boolean suppressLogs)7389 public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) { 7390 try { 7391 Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0); 7392 return true; 7393 } catch (IllegalArgumentException e) { 7394 if (!suppressLogs) { 7395 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 7396 } 7397 } catch (SecurityException e) { 7398 if (!suppressLogs) { 7399 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 7400 } 7401 } 7402 return false; 7403 } 7404 7405 /** 7406 * Schedule the given thread an FIFO scheduling priority. 7407 * 7408 * @param tid the tid of the thread to adjust the scheduling of. 7409 * @param suppressLogs {@code true} if any error logging should be disabled. 7410 * 7411 * @return {@code true} if this succeeded. 7412 */ scheduleAsFifoPriority(int tid, boolean suppressLogs)7413 public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) { 7414 try { 7415 Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1); 7416 return true; 7417 } catch (IllegalArgumentException e) { 7418 if (!suppressLogs) { 7419 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 7420 } 7421 } catch (SecurityException e) { 7422 if (!suppressLogs) { 7423 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 7424 } 7425 } 7426 return false; 7427 } 7428 7429 @Override setRenderThread(int tid)7430 public void setRenderThread(int tid) { 7431 synchronized (mProcLock) { 7432 ProcessRecord proc; 7433 int pid = Binder.getCallingPid(); 7434 if (pid == Process.myPid()) { 7435 demoteSystemServerRenderThread(tid); 7436 return; 7437 } 7438 synchronized (mPidsSelfLocked) { 7439 proc = mPidsSelfLocked.get(pid); 7440 } 7441 if (proc != null && proc.getRenderThreadTid() == 0 && tid > 0) { 7442 // ensure the tid belongs to the process 7443 if (!isThreadInProcess(pid, tid)) { 7444 throw new IllegalArgumentException( 7445 "Render thread does not belong to process"); 7446 } 7447 proc.setRenderThreadTid(tid); 7448 if (DEBUG_OOM_ADJ) { 7449 Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid); 7450 } 7451 // promote to FIFO now 7452 if (proc.mState.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) { 7453 if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band"); 7454 if (mUseFifoUiScheduling) { 7455 setThreadScheduler(proc.getRenderThreadTid(), 7456 SCHED_FIFO | SCHED_RESET_ON_FORK, 1); 7457 } else { 7458 setThreadPriority(proc.getRenderThreadTid(), THREAD_PRIORITY_TOP_APP_BOOST); 7459 } 7460 } 7461 } else { 7462 if (DEBUG_OOM_ADJ) { 7463 Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " 7464 + "PID: " + pid + ", TID: " + tid + " FIFO: " + mUseFifoUiScheduling); 7465 } 7466 } 7467 } 7468 } 7469 7470 /** 7471 * We only use RenderThread in system_server to store task snapshots to the disk, which should 7472 * happen in the background. Thus, demote render thread from system_server to a lower priority. 7473 * 7474 * @param tid the tid of the RenderThread 7475 */ demoteSystemServerRenderThread(int tid)7476 private void demoteSystemServerRenderThread(int tid) { 7477 setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND); 7478 } 7479 7480 @Override isVrModePackageEnabled(ComponentName packageName)7481 public boolean isVrModePackageEnabled(ComponentName packageName) { 7482 mActivityTaskManager.enforceSystemHasVrFeature(); 7483 7484 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); 7485 7486 return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) == 7487 VrManagerInternal.NO_ERROR; 7488 } 7489 isTopActivityImmersive()7490 public boolean isTopActivityImmersive() { 7491 return mActivityTaskManager.isTopActivityImmersive(); 7492 } 7493 7494 @Override isTopOfTask(IBinder token)7495 public boolean isTopOfTask(IBinder token) { 7496 return ActivityClient.getInstance().isTopOfTask(token); 7497 } 7498 7499 @Override setHasTopUi(boolean hasTopUi)7500 public void setHasTopUi(boolean hasTopUi) throws RemoteException { 7501 if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) { 7502 String msg = "Permission Denial: setHasTopUi() from pid=" 7503 + Binder.getCallingPid() 7504 + ", uid=" + Binder.getCallingUid() 7505 + " requires " + permission.INTERNAL_SYSTEM_WINDOW; 7506 Slog.w(TAG, msg); 7507 throw new SecurityException(msg); 7508 } 7509 final int pid = Binder.getCallingPid(); 7510 final long origId = Binder.clearCallingIdentity(); 7511 try { 7512 synchronized (this) { 7513 boolean changed = false; 7514 ProcessRecord pr; 7515 synchronized (mPidsSelfLocked) { 7516 pr = mPidsSelfLocked.get(pid); 7517 if (pr == null) { 7518 Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid); 7519 return; 7520 } 7521 if (pr.mState.hasTopUi() != hasTopUi) { 7522 if (DEBUG_OOM_ADJ) { 7523 Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid); 7524 } 7525 pr.mState.setHasTopUi(hasTopUi); 7526 changed = true; 7527 } 7528 } 7529 if (changed) { 7530 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 7531 } 7532 } 7533 } finally { 7534 Binder.restoreCallingIdentity(origId); 7535 } 7536 } 7537 enterSafeMode()7538 public final void enterSafeMode() { 7539 synchronized(this) { 7540 // It only makes sense to do this before the system is ready 7541 // and started launching other packages. 7542 if (!mSystemReady) { 7543 try { 7544 AppGlobals.getPackageManager().enterSafeMode(); 7545 } catch (RemoteException e) { 7546 } 7547 } 7548 7549 mSafeMode = true; 7550 } 7551 } 7552 showSafeModeOverlay()7553 public final void showSafeModeOverlay() { 7554 View v = LayoutInflater.from(mContext).inflate( 7555 com.android.internal.R.layout.safe_mode, null); 7556 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 7557 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 7558 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 7559 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 7560 lp.gravity = Gravity.BOTTOM | Gravity.START; 7561 lp.format = v.getBackground().getOpacity(); 7562 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 7563 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 7564 lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS; 7565 ((WindowManager)mContext.getSystemService( 7566 Context.WINDOW_SERVICE)).addView(v, lp); 7567 } 7568 7569 @Override noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)7570 public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, 7571 String sourcePkg, String tag) { 7572 if (workSource != null && workSource.isEmpty()) { 7573 workSource = null; 7574 } 7575 7576 if (sourceUid <= 0 && workSource == null) { 7577 // Try and derive a UID to attribute things to based on the caller. 7578 if (sender != null) { 7579 if (!(sender instanceof PendingIntentRecord)) { 7580 return; 7581 } 7582 7583 final PendingIntentRecord rec = (PendingIntentRecord) sender; 7584 final int callerUid = Binder.getCallingUid(); 7585 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 7586 } else { 7587 // TODO(narayan): Should we throw an exception in this case ? It means that we 7588 // haven't been able to derive a UID to attribute things to. 7589 return; 7590 } 7591 } 7592 7593 int standbyBucket = 0; 7594 7595 mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag); 7596 if (workSource != null) { 7597 String workSourcePackage = workSource.getPackageName(0); 7598 int workSourceUid = workSource.getAttributionUid(); 7599 if (workSourcePackage == null) { 7600 workSourcePackage = sourcePkg; 7601 workSourceUid = sourceUid; 7602 } 7603 7604 if (mUsageStatsService != null) { 7605 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage, 7606 UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime()); 7607 } 7608 7609 FrameworkStatsLog.write(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag, 7610 sourcePkg, standbyBucket); 7611 if (DEBUG_POWER) { 7612 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 7613 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 7614 + standbyBucket + " wsName=" + workSourcePackage + ")]"); 7615 } 7616 } else { 7617 if (mUsageStatsService != null) { 7618 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg, 7619 UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime()); 7620 } 7621 FrameworkStatsLog.write_non_chained(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, sourceUid, 7622 null, tag, sourcePkg, standbyBucket); 7623 if (DEBUG_POWER) { 7624 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 7625 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 7626 + standbyBucket + "]"); 7627 } 7628 } 7629 7630 } 7631 7632 @Override noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)7633 public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, 7634 String tag) { 7635 if (workSource != null && workSource.isEmpty()) { 7636 workSource = null; 7637 } 7638 7639 if (sourceUid <= 0 && workSource == null) { 7640 // Try and derive a UID to attribute things to based on the caller. 7641 if (sender != null) { 7642 if (!(sender instanceof PendingIntentRecord)) { 7643 return; 7644 } 7645 7646 final PendingIntentRecord rec = (PendingIntentRecord) sender; 7647 final int callerUid = Binder.getCallingUid(); 7648 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 7649 } else { 7650 // TODO(narayan): Should we throw an exception in this case ? It means that we 7651 // haven't been able to derive a UID to attribute things to. 7652 return; 7653 } 7654 } 7655 7656 if (DEBUG_POWER) { 7657 Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource + 7658 ", tag=" + tag + "]"); 7659 } 7660 7661 mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid); 7662 } 7663 7664 @Override noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)7665 public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, 7666 String tag) { 7667 if (workSource != null && workSource.isEmpty()) { 7668 workSource = null; 7669 } 7670 7671 if (sourceUid <= 0 && workSource == null) { 7672 // Try and derive a UID to attribute things to based on the caller. 7673 if (sender != null) { 7674 if (!(sender instanceof PendingIntentRecord)) { 7675 return; 7676 } 7677 7678 final PendingIntentRecord rec = (PendingIntentRecord) sender; 7679 final int callerUid = Binder.getCallingUid(); 7680 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 7681 } else { 7682 // TODO(narayan): Should we throw an exception in this case ? It means that we 7683 // haven't been able to derive a UID to attribute things to. 7684 return; 7685 } 7686 } 7687 7688 if (DEBUG_POWER) { 7689 Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource + 7690 ", tag=" + tag + "]"); 7691 } 7692 7693 mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid); 7694 } 7695 killPids(int[] pids, String pReason, boolean secure)7696 public boolean killPids(int[] pids, String pReason, boolean secure) { 7697 if (Binder.getCallingUid() != SYSTEM_UID) { 7698 throw new SecurityException("killPids only available to the system"); 7699 } 7700 final String reason = (pReason == null) ? "Unknown" : pReason; 7701 // XXX Note: don't acquire main activity lock here, because the window 7702 // manager calls in with its locks held. 7703 7704 boolean killed = false; 7705 final ArrayList<ProcessRecord> killCandidates = new ArrayList<>(); 7706 synchronized (mPidsSelfLocked) { 7707 int worstType = 0; 7708 for (int i = 0; i < pids.length; i++) { 7709 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 7710 if (proc != null) { 7711 int type = proc.mState.getSetAdj(); 7712 if (type > worstType) { 7713 worstType = type; 7714 } 7715 } 7716 } 7717 7718 // If the worst oom_adj is somewhere in the cached proc LRU range, 7719 // then constrain it so we will kill all cached procs. 7720 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 7721 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 7722 worstType = ProcessList.CACHED_APP_MIN_ADJ; 7723 } 7724 7725 // If this is not a secure call, don't let it kill processes that 7726 // are important. 7727 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 7728 worstType = ProcessList.SERVICE_ADJ; 7729 } 7730 7731 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 7732 for (int i = 0; i < pids.length; i++) { 7733 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 7734 if (proc == null) { 7735 continue; 7736 } 7737 int adj = proc.mState.getSetAdj(); 7738 if (adj >= worstType && !proc.isKilledByAm()) { 7739 killCandidates.add(proc); 7740 killed = true; 7741 } 7742 } 7743 } 7744 if (!killCandidates.isEmpty()) { 7745 mHandler.post(() -> { 7746 synchronized (ActivityManagerService.this) { 7747 for (int i = 0, size = killCandidates.size(); i < size; i++) { 7748 killCandidates.get(i).killLocked(reason, 7749 ApplicationExitInfo.REASON_OTHER, 7750 ApplicationExitInfo.SUBREASON_KILL_PID, true); 7751 } 7752 } 7753 }); 7754 } 7755 return killed; 7756 } 7757 7758 @Override killUid(int appId, int userId, String reason)7759 public void killUid(int appId, int userId, String reason) { 7760 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 7761 synchronized (this) { 7762 final long identity = Binder.clearCallingIdentity(); 7763 try { 7764 synchronized (mProcLock) { 7765 mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId, 7766 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 7767 true /* callerWillRestart */, true /* doit */, 7768 true /* evenPersistent */, false /* setRemoved */, 7769 false /* uninstalling */, 7770 ApplicationExitInfo.REASON_OTHER, 7771 ApplicationExitInfo.SUBREASON_KILL_UID, 7772 reason != null ? reason : "kill uid"); 7773 } 7774 } finally { 7775 Binder.restoreCallingIdentity(identity); 7776 } 7777 } 7778 } 7779 7780 @Override killUidForPermissionChange(int appId, int userId, String reason)7781 public void killUidForPermissionChange(int appId, int userId, String reason) { 7782 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 7783 synchronized (this) { 7784 final long identity = Binder.clearCallingIdentity(); 7785 try { 7786 synchronized (mProcLock) { 7787 mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId, 7788 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 7789 true /* callerWillRestart */, true /* doit */, 7790 true /* evenPersistent */, false /* setRemoved */, 7791 false /* uninstalling */, 7792 ApplicationExitInfo.REASON_PERMISSION_CHANGE, 7793 ApplicationExitInfo.SUBREASON_UNKNOWN, 7794 reason != null ? reason : "kill uid"); 7795 } 7796 } finally { 7797 Binder.restoreCallingIdentity(identity); 7798 } 7799 } 7800 } 7801 7802 @Override killProcessesBelowForeground(String reason)7803 public boolean killProcessesBelowForeground(String reason) { 7804 if (Binder.getCallingUid() != SYSTEM_UID) { 7805 throw new SecurityException("killProcessesBelowForeground() only available to system"); 7806 } 7807 7808 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 7809 } 7810 killProcessesBelowAdj(int belowAdj, String reason)7811 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 7812 if (Binder.getCallingUid() != SYSTEM_UID) { 7813 throw new SecurityException("killProcessesBelowAdj() only available to system"); 7814 } 7815 7816 boolean killed = false; 7817 synchronized (this) { 7818 synchronized (mProcLock) { 7819 synchronized (mPidsSelfLocked) { 7820 final int size = mPidsSelfLocked.size(); 7821 for (int i = 0; i < size; i++) { 7822 final int pid = mPidsSelfLocked.keyAt(i); 7823 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 7824 if (proc == null) continue; 7825 7826 final int adj = proc.mState.getSetAdj(); 7827 if (adj > belowAdj && !proc.isKilledByAm()) { 7828 proc.killLocked(reason, ApplicationExitInfo.REASON_PERMISSION_CHANGE, 7829 true); 7830 killed = true; 7831 } 7832 } 7833 } 7834 } 7835 } 7836 return killed; 7837 } 7838 7839 /** 7840 * Similar to {@link #killPids} but killing will be delayed until the device is idle 7841 * and the given process is imperceptible. 7842 */ 7843 @Override killProcessesWhenImperceptible(int[] pids, String reason)7844 public void killProcessesWhenImperceptible(int[] pids, String reason) { 7845 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 7846 != PackageManager.PERMISSION_GRANTED) { 7847 throw new SecurityException("Requires permission " 7848 + android.Manifest.permission.FORCE_STOP_PACKAGES); 7849 } 7850 int callerUid = Binder.getCallingUid(); 7851 final long iden = Binder.clearCallingIdentity(); 7852 try { 7853 mProcessList.killProcessesWhenImperceptible(pids, reason, callerUid); 7854 } finally { 7855 Binder.restoreCallingIdentity(iden); 7856 } 7857 } 7858 7859 @Override hang(final IBinder who, boolean allowRestart)7860 public void hang(final IBinder who, boolean allowRestart) { 7861 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7862 != PackageManager.PERMISSION_GRANTED) { 7863 throw new SecurityException("Requires permission " 7864 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7865 } 7866 7867 final IBinder.DeathRecipient death = new DeathRecipient() { 7868 @Override 7869 public void binderDied() { 7870 synchronized (this) { 7871 notifyAll(); 7872 } 7873 } 7874 }; 7875 7876 try { 7877 who.linkToDeath(death, 0); 7878 } catch (RemoteException e) { 7879 Slog.w(TAG, "hang: given caller IBinder is already dead."); 7880 return; 7881 } 7882 7883 synchronized (this) { 7884 Watchdog.getInstance().setAllowRestart(allowRestart); 7885 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 7886 synchronized (death) { 7887 while (who.isBinderAlive()) { 7888 try { 7889 death.wait(); 7890 } catch (InterruptedException e) { 7891 } 7892 } 7893 } 7894 Watchdog.getInstance().setAllowRestart(true); 7895 } 7896 } 7897 7898 @Override restart()7899 public void restart() { 7900 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7901 != PackageManager.PERMISSION_GRANTED) { 7902 throw new SecurityException("Requires permission " 7903 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7904 } 7905 7906 Log.i(TAG, "Sending shutdown broadcast..."); 7907 7908 BroadcastReceiver br = new BroadcastReceiver() { 7909 @Override public void onReceive(Context context, Intent intent) { 7910 // Now the broadcast is done, finish up the low-level shutdown. 7911 Log.i(TAG, "Shutting down activity manager..."); 7912 shutdown(10000); 7913 Log.i(TAG, "Shutdown complete, restarting!"); 7914 killProcess(myPid()); 7915 System.exit(10); 7916 } 7917 }; 7918 7919 // First send the high-level shut down broadcast. 7920 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 7921 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 7922 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 7923 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 7924 mContext.sendOrderedBroadcastAsUser(intent, 7925 UserHandle.ALL, null, br, mHandler, 0, null, null); 7926 */ 7927 br.onReceive(mContext, intent); 7928 } 7929 7930 @Override performIdleMaintenance()7931 public void performIdleMaintenance() { 7932 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7933 != PackageManager.PERMISSION_GRANTED) { 7934 throw new SecurityException("Requires permission " 7935 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7936 } 7937 7938 synchronized (mProcLock) { 7939 final long now = SystemClock.uptimeMillis(); 7940 final long timeSinceLastIdle = now - mLastIdleTime; 7941 7942 // Compact all non-zygote processes to freshen up the page cache. 7943 mOomAdjuster.mCachedAppOptimizer.compactAllSystem(); 7944 7945 final long lowRamSinceLastIdle = mAppProfiler.getLowRamTimeSinceIdleLPr(now); 7946 mLastIdleTime = now; 7947 mAppProfiler.updateLowRamTimestampLPr(now); 7948 7949 StringBuilder sb = new StringBuilder(128); 7950 sb.append("Idle maintenance over "); 7951 TimeUtils.formatDuration(timeSinceLastIdle, sb); 7952 sb.append(" low RAM for "); 7953 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 7954 Slog.i(TAG, sb.toString()); 7955 7956 // If at least 1/3 of our time since the last idle period has been spent 7957 // with RAM low, then we want to kill processes. 7958 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 7959 // If the processes' memory has increased by more than 1% of the total memory, 7960 // or 10 MB, whichever is greater, then the processes' are eligible to be killed. 7961 final long totalMemoryInKb = getTotalMemory() / 1000; 7962 final long memoryGrowthThreshold = 7963 Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD); 7964 mProcessList.forEachLruProcessesLOSP(false, proc -> { 7965 if (proc.getThread() == null) { 7966 return; 7967 } 7968 final ProcessProfileRecord pr = proc.mProfile; 7969 final ProcessStateRecord state = proc.mState; 7970 final int setProcState = state.getSetProcState(); 7971 if (state.isNotCachedSinceIdle()) { 7972 if (setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE 7973 && setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 7974 final long initialIdlePss, lastPss, lastSwapPss; 7975 synchronized (mAppProfiler.mProfilerLock) { 7976 initialIdlePss = pr.getInitialIdlePss(); 7977 lastPss = pr.getLastPss(); 7978 lastSwapPss = pr.getLastSwapPss(); 7979 } 7980 if (doKilling && initialIdlePss != 0 7981 && lastPss > (initialIdlePss * 3 / 2) 7982 && lastPss > (initialIdlePss + memoryGrowthThreshold)) { 7983 final StringBuilder sb2 = new StringBuilder(128); 7984 sb2.append("Kill"); 7985 sb2.append(proc.processName); 7986 sb2.append(" in idle maint: pss="); 7987 sb2.append(lastPss); 7988 sb2.append(", swapPss="); 7989 sb2.append(lastSwapPss); 7990 sb2.append(", initialPss="); 7991 sb2.append(initialIdlePss); 7992 sb2.append(", period="); 7993 TimeUtils.formatDuration(timeSinceLastIdle, sb2); 7994 sb2.append(", lowRamPeriod="); 7995 TimeUtils.formatDuration(lowRamSinceLastIdle, sb2); 7996 Slog.wtfQuiet(TAG, sb2.toString()); 7997 mHandler.post(() -> { 7998 synchronized (ActivityManagerService.this) { 7999 proc.killLocked("idle maint (pss " + lastPss 8000 + " from " + initialIdlePss + ")", 8001 ApplicationExitInfo.REASON_OTHER, 8002 ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE, 8003 true); 8004 } 8005 }); 8006 } 8007 } 8008 } else if (setProcState < ActivityManager.PROCESS_STATE_HOME 8009 && setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) { 8010 state.setNotCachedSinceIdle(true); 8011 synchronized (mAppProfiler.mProfilerLock) { 8012 pr.setInitialIdlePss(0); 8013 mAppProfiler.updateNextPssTimeLPf( 8014 state.getSetProcState(), proc.mProfile, now, true); 8015 } 8016 } 8017 }); 8018 } 8019 } 8020 8021 @Override sendIdleJobTrigger()8022 public void sendIdleJobTrigger() { 8023 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8024 != PackageManager.PERMISSION_GRANTED) { 8025 throw new SecurityException("Requires permission " 8026 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 8027 } 8028 8029 final long ident = Binder.clearCallingIdentity(); 8030 try { 8031 Intent intent = new Intent(ACTION_TRIGGER_IDLE) 8032 .setPackage("android") 8033 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 8034 broadcastIntent(null, intent, null, null, 0, null, null, null, 8035 OP_NONE, null, false, false, UserHandle.USER_ALL); 8036 } finally { 8037 Binder.restoreCallingIdentity(ident); 8038 } 8039 } 8040 retrieveSettings()8041 private void retrieveSettings() { 8042 final ContentResolver resolver = mContext.getContentResolver(); 8043 mActivityTaskManager.retrieveSettings(resolver); 8044 8045 final String debugApp = Settings.Global.getString(resolver, DEBUG_APP); 8046 final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0; 8047 final boolean alwaysFinishActivities = 8048 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0; 8049 mHiddenApiBlacklist.registerObserver(); 8050 mSdkSandboxSettings.registerObserver(); 8051 mPlatformCompat.registerContentObserver(); 8052 8053 mAppProfiler.retrieveSettings(); 8054 8055 final Resources res; 8056 synchronized (this) { 8057 mDebugApp = mOrigDebugApp = debugApp; 8058 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 8059 mAlwaysFinishActivities = alwaysFinishActivities; 8060 // Load resources only after the current configuration has been set. 8061 res = mContext.getResources(); 8062 final boolean userSwitchUiEnabled = !res.getBoolean( 8063 com.android.internal.R.bool.config_customUserSwitchUi); 8064 final int maxRunningUsers = res.getInteger( 8065 com.android.internal.R.integer.config_multiuserMaxRunningUsers); 8066 final boolean delayUserDataLocking = res.getBoolean( 8067 com.android.internal.R.bool.config_multiuserDelayUserDataLocking); 8068 mUserController.setInitialConfig(userSwitchUiEnabled, maxRunningUsers, 8069 delayUserDataLocking); 8070 } 8071 mAppErrors.loadAppsNotReportingCrashesFromConfig(res.getString( 8072 com.android.internal.R.string.config_appsNotReportingCrashes)); 8073 } 8074 8075 /** 8076 * Ready. Set. Go! 8077 */ systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t)8078 public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) { 8079 t.traceBegin("PhaseActivityManagerReady"); 8080 mSystemServiceManager.preSystemReady(); 8081 synchronized(this) { 8082 if (mSystemReady) { 8083 // If we're done calling all the receivers, run the next "boot phase" passed in 8084 // by the SystemServer 8085 if (goingCallback != null) { 8086 goingCallback.run(); 8087 } 8088 t.traceEnd(); // PhaseActivityManagerReady 8089 return; 8090 } 8091 8092 t.traceBegin("controllersReady"); 8093 mLocalDeviceIdleController = 8094 LocalServices.getService(DeviceIdleInternal.class); 8095 mActivityTaskManager.onSystemReady(); 8096 // Make sure we have the current profile info, since it is needed for security checks. 8097 mUserController.onSystemReady(); 8098 mAppOpsService.systemReady(); 8099 mProcessList.onSystemReady(); 8100 mAppRestrictionController.onSystemReady(); 8101 mSystemReady = true; 8102 t.traceEnd(); 8103 } 8104 8105 try { 8106 sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface( 8107 ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE)) 8108 .getSerial(); 8109 } catch (RemoteException e) {} 8110 8111 t.traceBegin("killProcesses"); 8112 ArrayList<ProcessRecord> procsToKill = null; 8113 synchronized(mPidsSelfLocked) { 8114 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 8115 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 8116 if (!isAllowedWhileBooting(proc.info)){ 8117 if (procsToKill == null) { 8118 procsToKill = new ArrayList<ProcessRecord>(); 8119 } 8120 procsToKill.add(proc); 8121 } 8122 } 8123 } 8124 8125 synchronized(this) { 8126 if (procsToKill != null) { 8127 for (int i = procsToKill.size() - 1; i >= 0; i--) { 8128 ProcessRecord proc = procsToKill.get(i); 8129 Slog.i(TAG, "Removing system update proc: " + proc); 8130 mProcessList.removeProcessLocked(proc, true, false, 8131 ApplicationExitInfo.REASON_OTHER, 8132 ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE, 8133 "system update done"); 8134 } 8135 } 8136 8137 // Now that we have cleaned up any update processes, we 8138 // are ready to start launching real processes and know that 8139 // we won't trample on them any more. 8140 mProcessesReady = true; 8141 } 8142 t.traceEnd(); // KillProcesses 8143 8144 Slog.i(TAG, "System now ready"); 8145 8146 EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis()); 8147 8148 t.traceBegin("updateTopComponentForFactoryTest"); 8149 mAtmInternal.updateTopComponentForFactoryTest(); 8150 t.traceEnd(); 8151 8152 t.traceBegin("registerActivityLaunchObserver"); 8153 mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver); 8154 t.traceEnd(); 8155 8156 t.traceBegin("watchDeviceProvisioning"); 8157 watchDeviceProvisioning(mContext); 8158 t.traceEnd(); 8159 8160 t.traceBegin("retrieveSettings"); 8161 retrieveSettings(); 8162 t.traceEnd(); 8163 8164 t.traceBegin("Ugm.onSystemReady"); 8165 mUgmInternal.onSystemReady(); 8166 t.traceEnd(); 8167 8168 t.traceBegin("updateForceBackgroundCheck"); 8169 final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class); 8170 if (pmi != null) { 8171 pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK, 8172 state -> updateForceBackgroundCheck(state.batterySaverEnabled)); 8173 updateForceBackgroundCheck( 8174 pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled); 8175 } else { 8176 Slog.wtf(TAG, "PowerManagerInternal not found."); 8177 } 8178 t.traceEnd(); 8179 8180 if (goingCallback != null) goingCallback.run(); 8181 8182 t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks 8183 // Check the current user here as a user can be started inside goingCallback.run() from 8184 // other system services. 8185 final int currentUserId = mUserController.getCurrentUserId(); 8186 Slog.i(TAG, "Current user:" + currentUserId); 8187 if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) { 8188 // User other than system user has started. Make sure that system user is already 8189 // started before switching user. 8190 throw new RuntimeException("System user not started while current user is:" 8191 + currentUserId); 8192 } 8193 t.traceEnd(); 8194 8195 t.traceBegin("ActivityManagerStartApps"); 8196 mBatteryStatsService.onSystemReady(); 8197 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 8198 Integer.toString(currentUserId), currentUserId); 8199 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 8200 Integer.toString(currentUserId), currentUserId); 8201 8202 // On Automotive / Headless System User Mode, at this point the system user has already been 8203 // started and unlocked, and some of the tasks we do here have already been done. So skip 8204 // those in that case. The duplicate system user start is guarded in SystemServiceManager. 8205 // TODO(b/242195409): this workaround shouldn't be necessary once we move the headless-user 8206 // start logic to UserManager-land. 8207 mSystemServiceManager.onUserStarting(t, currentUserId); 8208 8209 synchronized (this) { 8210 // Only start up encryption-aware persistent apps; once user is 8211 // unlocked we'll come back around and start unaware apps 8212 t.traceBegin("startPersistentApps"); 8213 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE); 8214 t.traceEnd(); 8215 8216 // Start up initial activity. 8217 mBooting = true; 8218 // Enable home activity for system user, so that the system can always boot. We don't 8219 // do this when the system user is not setup since the setup wizard should be the one 8220 // to handle home activity in this case. 8221 if (UserManager.isSplitSystemUser() && 8222 Settings.Secure.getInt(mContext.getContentResolver(), 8223 Settings.Secure.USER_SETUP_COMPLETE, 0) != 0 8224 || SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) { 8225 t.traceBegin("enableHomeActivity"); 8226 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class); 8227 try { 8228 AppGlobals.getPackageManager().setComponentEnabledSetting(cName, 8229 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0, 8230 UserHandle.USER_SYSTEM); 8231 } catch (RemoteException e) { 8232 throw e.rethrowAsRuntimeException(); 8233 } 8234 t.traceEnd(); 8235 } 8236 8237 boolean isBootingSystemUser = currentUserId == UserHandle.USER_SYSTEM; 8238 8239 // Some systems - like automotive - will explicitly unlock system user then switch 8240 // to a secondary user. 8241 // TODO(b/242195409): this workaround shouldn't be necessary once we move 8242 // the headless-user start logic to UserManager-land. 8243 if (isBootingSystemUser && !UserManager.isHeadlessSystemUserMode()) { 8244 t.traceBegin("startHomeOnAllDisplays"); 8245 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady"); 8246 t.traceEnd(); 8247 } 8248 8249 t.traceBegin("showSystemReadyErrorDialogs"); 8250 mAtmInternal.showSystemReadyErrorDialogsIfNeeded(); 8251 t.traceEnd(); 8252 8253 8254 if (isBootingSystemUser) { 8255 // Need to send the broadcasts for the system user here because 8256 // UserController#startUserInternal will not send them for the system user starting, 8257 // It checks if the user state already exists, which is always the case for the 8258 // system user. 8259 t.traceBegin("sendUserStartBroadcast"); 8260 final int callingUid = Binder.getCallingUid(); 8261 final int callingPid = Binder.getCallingPid(); 8262 final long ident = Binder.clearCallingIdentity(); 8263 try { 8264 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 8265 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 8266 | Intent.FLAG_RECEIVER_FOREGROUND); 8267 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); 8268 broadcastIntentLocked(null, null, null, intent, 8269 null, null, 0, null, null, null, null, null, OP_NONE, 8270 null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid, 8271 currentUserId); 8272 intent = new Intent(Intent.ACTION_USER_STARTING); 8273 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 8274 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); 8275 broadcastIntentLocked(null, null, null, intent, null, 8276 new IIntentReceiver.Stub() { 8277 @Override 8278 public void performReceive(Intent intent, int resultCode, 8279 String data, Bundle extras, boolean ordered, boolean sticky, 8280 int sendingUser) {} 8281 }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, null, null, 8282 OP_NONE, null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid, 8283 UserHandle.USER_ALL); 8284 } catch (Throwable e) { 8285 Slog.wtf(TAG, "Failed sending first user broadcasts", e); 8286 } finally { 8287 Binder.restoreCallingIdentity(ident); 8288 } 8289 t.traceEnd(); 8290 } else { 8291 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user " 8292 + currentUserId); 8293 } 8294 8295 t.traceBegin("resumeTopActivities"); 8296 mAtmInternal.resumeTopActivities(false /* scheduleIdle */); 8297 t.traceEnd(); 8298 8299 if (isBootingSystemUser) { 8300 t.traceBegin("sendUserSwitchBroadcasts"); 8301 mUserController.sendUserSwitchBroadcasts(-1, currentUserId); 8302 t.traceEnd(); 8303 } 8304 8305 t.traceBegin("setBinderProxies"); 8306 BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK, 8307 BINDER_PROXY_LOW_WATERMARK); 8308 BinderInternal.nSetBinderProxyCountEnabled(true); 8309 BinderInternal.setBinderProxyCountCallback( 8310 (uid) -> { 8311 Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid " 8312 + Process.myUid()); 8313 BinderProxy.dumpProxyDebugInfo(); 8314 if (uid == Process.SYSTEM_UID) { 8315 Slog.i(TAG, "Skipping kill (uid is SYSTEM)"); 8316 } else { 8317 killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid), 8318 "Too many Binders sent to SYSTEM"); 8319 // We need to run a GC here, because killing the processes involved 8320 // actually isn't guaranteed to free up the proxies; in fact, if the 8321 // GC doesn't run for a long time, we may even exceed the global 8322 // proxy limit for a process (20000), resulting in system_server itself 8323 // being killed. 8324 // Note that the GC here might not actually clean up all the proxies, 8325 // because the binder reference decrements will come in asynchronously; 8326 // but if new processes belonging to the UID keep adding proxies, we 8327 // will get another callback here, and run the GC again - this time 8328 // cleaning up the old proxies. 8329 VMRuntime.getRuntime().requestConcurrentGC(); 8330 } 8331 }, mHandler); 8332 t.traceEnd(); // setBinderProxies 8333 8334 t.traceEnd(); // ActivityManagerStartApps 8335 8336 // Load the component aliases. 8337 t.traceBegin("componentAlias"); 8338 mComponentAliasResolver.onSystemReady(mConstants.mEnableComponentAlias, 8339 mConstants.mComponentAliasOverrides); 8340 t.traceEnd(); // componentAlias 8341 8342 t.traceEnd(); // PhaseActivityManagerReady 8343 } 8344 } 8345 watchDeviceProvisioning(Context context)8346 private void watchDeviceProvisioning(Context context) { 8347 // setting system property based on whether device is provisioned 8348 8349 if (isDeviceProvisioned(context)) { 8350 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 8351 } else { 8352 // watch for device provisioning change 8353 context.getContentResolver().registerContentObserver( 8354 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false, 8355 new ContentObserver(new Handler(Looper.getMainLooper())) { 8356 @Override 8357 public void onChange(boolean selfChange) { 8358 if (isDeviceProvisioned(context)) { 8359 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 8360 context.getContentResolver().unregisterContentObserver(this); 8361 } 8362 } 8363 }); 8364 } 8365 } 8366 isDeviceProvisioned(Context context)8367 private boolean isDeviceProvisioned(Context context) { 8368 return Settings.Global.getInt(context.getContentResolver(), 8369 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 8370 } 8371 startBroadcastObservers()8372 private void startBroadcastObservers() { 8373 for (BroadcastQueue queue : mBroadcastQueues) { 8374 queue.start(mContext.getContentResolver()); 8375 } 8376 } 8377 updateForceBackgroundCheck(boolean enabled)8378 private void updateForceBackgroundCheck(boolean enabled) { 8379 synchronized (this) { 8380 synchronized (mProcLock) { 8381 if (mForceBackgroundCheck != enabled) { 8382 mForceBackgroundCheck = enabled; 8383 8384 if (DEBUG_BACKGROUND_CHECK) { 8385 Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled")); 8386 } 8387 8388 if (mForceBackgroundCheck) { 8389 // Stop background services for idle UIDs. 8390 mProcessList.doStopUidForIdleUidsLocked(); 8391 } 8392 } 8393 } 8394 } 8395 } 8396 killAppAtUsersRequest(ProcessRecord app)8397 void killAppAtUsersRequest(ProcessRecord app) { 8398 synchronized (this) { 8399 mAppErrors.killAppAtUserRequestLocked(app); 8400 } 8401 } 8402 skipCurrentReceiverLocked(ProcessRecord app)8403 void skipCurrentReceiverLocked(ProcessRecord app) { 8404 for (BroadcastQueue queue : mBroadcastQueues) { 8405 queue.skipCurrentReceiverLocked(app); 8406 } 8407 } 8408 8409 /** 8410 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 8411 * The application process will exit immediately after this call returns. 8412 * @param app object of the crashing app, null for the system server 8413 * @param crashInfo describing the exception 8414 */ handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)8415 public void handleApplicationCrash(IBinder app, 8416 ApplicationErrorReport.ParcelableCrashInfo crashInfo) { 8417 ProcessRecord r = findAppProcess(app, "Crash"); 8418 final String processName = app == null ? "system_server" 8419 : (r == null ? "unknown" : r.processName); 8420 8421 handleApplicationCrashInner("crash", r, processName, crashInfo); 8422 } 8423 8424 /* Native crash reporting uses this inner version because it needs to be somewhat 8425 * decoupled from the AM-managed cleanup lifecycle 8426 */ handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)8427 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 8428 ApplicationErrorReport.CrashInfo crashInfo) { 8429 float loadingProgress = 1; 8430 IncrementalMetrics incrementalMetrics = null; 8431 // Obtain Incremental information if available 8432 if (r != null && r.info != null && r.info.packageName != null) { 8433 IncrementalStatesInfo incrementalStatesInfo = 8434 mPackageManagerInt.getIncrementalStatesInfo(r.info.packageName, SYSTEM_UID, 8435 r.userId); 8436 if (incrementalStatesInfo != null) { 8437 loadingProgress = incrementalStatesInfo.getProgress(); 8438 } 8439 final String codePath = r.info.getCodePath(); 8440 if (codePath != null && !codePath.isEmpty() 8441 && IncrementalManager.isIncrementalPath(codePath)) { 8442 // Report in the main log about the incremental package 8443 Slog.e(TAG, "App crashed on incremental package " + r.info.packageName 8444 + " which is " + ((int) (loadingProgress * 100)) + "% loaded."); 8445 final IBinder incrementalService = ServiceManager.getService( 8446 Context.INCREMENTAL_SERVICE); 8447 if (incrementalService != null) { 8448 final IncrementalManager incrementalManager = new IncrementalManager( 8449 IIncrementalService.Stub.asInterface(incrementalService)); 8450 incrementalMetrics = incrementalManager.getMetrics(codePath); 8451 } 8452 } 8453 } 8454 8455 EventLogTags.writeAmCrash(Binder.getCallingPid(), 8456 UserHandle.getUserId(Binder.getCallingUid()), processName, 8457 r == null ? -1 : r.info.flags, 8458 crashInfo.exceptionClassName, 8459 crashInfo.exceptionMessage, 8460 crashInfo.throwFileName, 8461 crashInfo.throwLineNumber); 8462 8463 int processClassEnum = processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER 8464 : (r != null) ? r.getProcessClassEnum() 8465 : ServerProtoEnums.ERROR_SOURCE_UNKNOWN; 8466 int uid = (r != null) ? r.uid : -1; 8467 int pid = (r != null) ? r.getPid() : -1; 8468 FrameworkStatsLog.write(FrameworkStatsLog.APP_CRASH_OCCURRED, 8469 uid, 8470 eventType, 8471 processName, 8472 pid, 8473 (r != null && r.info != null) ? r.info.packageName : "", 8474 (r != null && r.info != null) ? (r.info.isInstantApp() 8475 ? FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE 8476 : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE) 8477 : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE, 8478 r != null ? (r.isInterestingToUserLocked() 8479 ? FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND 8480 : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND) 8481 : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN, 8482 processClassEnum, 8483 incrementalMetrics != null /* isIncremental */, loadingProgress, 8484 incrementalMetrics != null ? incrementalMetrics.getMillisSinceOldestPendingRead() 8485 : -1, 8486 incrementalMetrics != null ? incrementalMetrics.getStorageHealthStatusCode() 8487 : -1, 8488 incrementalMetrics != null ? incrementalMetrics.getDataLoaderStatusCode() 8489 : -1, 8490 incrementalMetrics != null && incrementalMetrics.getReadLogsEnabled(), 8491 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastDataLoaderBind() 8492 : -1, 8493 incrementalMetrics != null ? incrementalMetrics.getDataLoaderBindDelayMillis() 8494 : -1, 8495 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReads() 8496 : -1, 8497 incrementalMetrics != null ? incrementalMetrics.getTotalFailedReads() 8498 : -1, 8499 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorUid() 8500 : -1, 8501 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastReadError() 8502 : -1, 8503 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorNumber() 8504 : 0, 8505 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReadsDurationMillis() 8506 : -1 8507 ); 8508 8509 if (eventType.equals("native_crash")) { 8510 CriticalEventLog.getInstance().logNativeCrash(processClassEnum, processName, uid, pid); 8511 } else if (eventType.equals("crash")) { 8512 CriticalEventLog.getInstance().logJavaCrash(crashInfo.exceptionClassName, 8513 processClassEnum, processName, uid, pid); 8514 } 8515 8516 final int relaunchReason = r == null ? RELAUNCH_REASON_NONE 8517 : r.getWindowProcessController().computeRelaunchReason(); 8518 final String relaunchReasonString = relaunchReasonToString(relaunchReason); 8519 if (crashInfo.crashTag == null) { 8520 crashInfo.crashTag = relaunchReasonString; 8521 } else { 8522 crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString; 8523 } 8524 8525 addErrorToDropBox( 8526 eventType, r, processName, null, null, null, null, null, null, crashInfo, 8527 new Float(loadingProgress), incrementalMetrics, null); 8528 8529 mAppErrors.crashApplication(r, crashInfo); 8530 } 8531 handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)8532 public void handleApplicationStrictModeViolation( 8533 IBinder app, 8534 int penaltyMask, 8535 StrictMode.ViolationInfo info) { 8536 // We're okay if the ProcessRecord is missing; it probably means that 8537 // we're reporting a violation from the system process itself. 8538 final ProcessRecord r = findAppProcess(app, "StrictMode"); 8539 8540 if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) { 8541 Integer stackFingerprint = info.hashCode(); 8542 boolean logIt = true; 8543 synchronized (mAlreadyLoggedViolatedStacks) { 8544 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 8545 logIt = false; 8546 // TODO: sub-sample into EventLog for these, with 8547 // the info.durationMillis? Then we'd get 8548 // the relative pain numbers, without logging all 8549 // the stack traces repeatedly. We'd want to do 8550 // likewise in the client code, which also does 8551 // dup suppression, before the Binder call. 8552 } else { 8553 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 8554 mAlreadyLoggedViolatedStacks.clear(); 8555 } 8556 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 8557 } 8558 } 8559 if (logIt) { 8560 logStrictModeViolationToDropBox(r, info); 8561 } 8562 } 8563 8564 if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) { 8565 AppErrorResult result = new AppErrorResult(); 8566 final long origId = Binder.clearCallingIdentity(); 8567 try { 8568 Message msg = Message.obtain(); 8569 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG; 8570 HashMap<String, Object> data = new HashMap<String, Object>(); 8571 data.put("result", result); 8572 data.put("app", r); 8573 data.put("info", info); 8574 msg.obj = data; 8575 mUiHandler.sendMessage(msg); 8576 } finally { 8577 Binder.restoreCallingIdentity(origId); 8578 } 8579 int res = result.get(); 8580 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 8581 } 8582 } 8583 8584 // Depending on the policy in effect, there could be a bunch of 8585 // these in quick succession so we try to batch these together to 8586 // minimize disk writes, number of dropbox entries, and maximize 8587 // compression, by having more fewer, larger records. logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)8588 private void logStrictModeViolationToDropBox( 8589 ProcessRecord process, 8590 StrictMode.ViolationInfo info) { 8591 if (info == null) { 8592 return; 8593 } 8594 final boolean isSystemApp = process == null || 8595 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 8596 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 8597 final String processName = process == null ? "unknown" : process.processName; 8598 final DropBoxManager dbox = (DropBoxManager) 8599 mContext.getSystemService(Context.DROPBOX_SERVICE); 8600 8601 // Exit early if the dropbox isn't configured to accept this report type. 8602 final String dropboxTag = processClass(process) + "_strictmode"; 8603 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 8604 8605 final StringBuilder sb = new StringBuilder(1024); 8606 synchronized (sb) { 8607 appendDropBoxProcessHeaders(process, processName, sb); 8608 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 8609 sb.append("System-App: ").append(isSystemApp).append("\n"); 8610 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 8611 if (info.violationNumThisLoop != 0) { 8612 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 8613 } 8614 if (info.numAnimationsRunning != 0) { 8615 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 8616 } 8617 if (info.broadcastIntentAction != null) { 8618 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n"); 8619 } 8620 if (info.durationMillis != -1) { 8621 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 8622 } 8623 if (info.numInstances != -1) { 8624 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 8625 } 8626 if (info.tags != null) { 8627 for (String tag : info.tags) { 8628 sb.append("Span-Tag: ").append(tag).append("\n"); 8629 } 8630 } 8631 sb.append("\n"); 8632 sb.append(info.getStackTrace()); 8633 sb.append("\n"); 8634 if (info.getViolationDetails() != null) { 8635 sb.append(info.getViolationDetails()); 8636 sb.append("\n"); 8637 } 8638 } 8639 8640 final String res = sb.toString(); 8641 IoThread.getHandler().post(() -> { 8642 dbox.addText(dropboxTag, res); 8643 }); 8644 } 8645 8646 /** 8647 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 8648 * @param app object of the crashing app, null for the system server 8649 * @param tag reported by the caller 8650 * @param system whether this wtf is coming from the system 8651 * @param crashInfo describing the context of the error 8652 * @return true if the process should exit immediately (WTF is fatal) 8653 */ 8654 @Override handleApplicationWtf(@ullable final IBinder app, @Nullable final String tag, boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)8655 public boolean handleApplicationWtf(@Nullable final IBinder app, @Nullable final String tag, 8656 boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, 8657 int immediateCallerPid) { 8658 final int callingUid = Binder.getCallingUid(); 8659 final int callingPid = Binder.getCallingPid(); 8660 8661 // Internal callers in RuntimeInit should always generate a crashInfo. 8662 Preconditions.checkNotNull(crashInfo); 8663 8664 // If this is coming from the system, we could very well have low-level 8665 // system locks held, so we want to do this all asynchronously. And we 8666 // never want this to become fatal, so there is that too. 8667 // 8668 // Note: "callingPid == Process.myPid())" wouldn't be reliable because even if the caller 8669 // is within the system server, if it calls Log.wtf() without clearning the calling 8670 // identity, callingPid would still be of a remote caller. So we explicltly pass the 8671 // process PID from the caller. 8672 if (system || (immediateCallerPid == Process.myPid())) { 8673 mHandler.post(new Runnable() { 8674 @Override public void run() { 8675 handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo); 8676 } 8677 }); 8678 return false; 8679 } 8680 8681 final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag, 8682 crashInfo); 8683 8684 final boolean isFatal = Build.IS_ENG || Settings.Global 8685 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0; 8686 final boolean isSystem = (r == null) || r.isPersistent(); 8687 8688 if (isFatal && !isSystem) { 8689 mAppErrors.crashApplication(r, crashInfo); 8690 return true; 8691 } else { 8692 return false; 8693 } 8694 } 8695 handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo)8696 ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, 8697 @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo) { 8698 final ProcessRecord r = findAppProcess(app, "WTF"); 8699 final String processName = app == null ? "system_server" 8700 : (r == null ? "unknown" : r.processName); 8701 8702 EventLogTags.writeAmWtf(UserHandle.getUserId(callingUid), callingPid, 8703 processName, r == null ? -1 : r.info.flags, tag, 8704 crashInfo == null ? "unknown" : crashInfo.exceptionMessage); 8705 8706 FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, callingUid, tag, processName, 8707 callingPid, (r != null) ? r.getProcessClassEnum() : 0); 8708 8709 addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo, 8710 null, null, null); 8711 8712 return r; 8713 } 8714 8715 /** 8716 * Schedule to handle any pending system_server WTFs. 8717 */ schedulePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)8718 public void schedulePendingSystemServerWtfs( 8719 final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) { 8720 mHandler.post(() -> handlePendingSystemServerWtfs(list)); 8721 } 8722 8723 /** 8724 * Handle any pending system_server WTFs, add into the dropbox 8725 */ handlePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)8726 private void handlePendingSystemServerWtfs( 8727 final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) { 8728 ProcessRecord proc; 8729 synchronized (mPidsSelfLocked) { 8730 proc = mPidsSelfLocked.get(MY_PID); 8731 } 8732 for (Pair<String, ApplicationErrorReport.CrashInfo> p = list.poll(); 8733 p != null; p = list.poll()) { 8734 addErrorToDropBox("wtf", proc, "system_server", null, null, null, p.first, null, null, 8735 p.second, null, null, null); 8736 } 8737 } 8738 8739 /** 8740 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 8741 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 8742 */ findAppProcess(IBinder app, String reason)8743 private ProcessRecord findAppProcess(IBinder app, String reason) { 8744 if (app == null) { 8745 return null; 8746 } 8747 8748 synchronized (mProcLock) { 8749 return mProcessList.findAppProcessLOSP(app, reason); 8750 } 8751 } 8752 8753 /** 8754 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 8755 * to append various headers to the dropbox log text. 8756 */ appendDropBoxProcessHeaders(ProcessRecord process, String processName, final StringBuilder sb)8757 void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 8758 final StringBuilder sb) { 8759 // Watchdog thread ends up invoking this function (with 8760 // a null ProcessRecord) to add the stack file to dropbox. 8761 // Do not acquire a lock on this (am) in such cases, as it 8762 // could cause a potential deadlock, if and when watchdog 8763 // is invoked due to unavailability of lock on am and it 8764 // would prevent watchdog from killing system_server. 8765 if (process == null) { 8766 sb.append("Process: ").append(processName).append("\n"); 8767 return; 8768 } 8769 // Note: ProcessRecord 'process' is guarded by the service 8770 // instance. (notably process.pkgList, which could otherwise change 8771 // concurrently during execution of this method) 8772 synchronized (mProcLock) { 8773 sb.append("Process: ").append(processName).append("\n"); 8774 sb.append("PID: ").append(process.getPid()).append("\n"); 8775 sb.append("UID: ").append(process.uid).append("\n"); 8776 if (process.mOptRecord != null) { 8777 sb.append("Frozen: ").append(process.mOptRecord.isFrozen()).append("\n"); 8778 } 8779 int flags = process.info.flags; 8780 final IPackageManager pm = AppGlobals.getPackageManager(); 8781 sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n"); 8782 final int callingUserId = UserHandle.getCallingUserId(); 8783 process.getPkgList().forEachPackage(pkg -> { 8784 sb.append("Package: ").append(pkg); 8785 try { 8786 final PackageInfo pi = pm.getPackageInfo(pkg, 0, callingUserId); 8787 if (pi != null) { 8788 sb.append(" v").append(pi.getLongVersionCode()); 8789 if (pi.versionName != null) { 8790 sb.append(" (").append(pi.versionName).append(")"); 8791 } 8792 } 8793 } catch (RemoteException e) { 8794 Slog.e(TAG, "Error getting package info: " + pkg, e); 8795 } 8796 sb.append("\n"); 8797 }); 8798 if (process.info.isInstantApp()) { 8799 sb.append("Instant-App: true\n"); 8800 } 8801 8802 if (isSdkSandboxUid(process.uid)) { 8803 final int appUid = Process.getAppUidForSdkSandboxUid(process.uid); 8804 try { 8805 String[] clientPackages = pm.getPackagesForUid(appUid); 8806 // In shared UID case, don't add the package information 8807 if (clientPackages.length == 1) { 8808 appendSdkSandboxClientPackageHeader(sb, clientPackages[0], callingUserId); 8809 } 8810 } catch (RemoteException e) { 8811 Slog.e(TAG, "Error getting packages for client app uid: " + appUid, e); 8812 } 8813 sb.append("SdkSandbox: true\n"); 8814 } 8815 } 8816 } 8817 appendSdkSandboxClientPackageHeader(StringBuilder sb, String pkg, int userId)8818 private void appendSdkSandboxClientPackageHeader(StringBuilder sb, String pkg, int userId) { 8819 final IPackageManager pm = AppGlobals.getPackageManager(); 8820 sb.append("SdkSandbox-Client-Package: ").append(pkg); 8821 try { 8822 final PackageInfo pi = pm.getPackageInfo(pkg, 0, userId); 8823 if (pi != null) { 8824 sb.append(" v").append(pi.getLongVersionCode()); 8825 if (pi.versionName != null) { 8826 sb.append(" (").append(pi.versionName).append(")"); 8827 } 8828 } 8829 } catch (RemoteException e) { 8830 Slog.e(TAG, "Error getting package info for SDK sandbox client: " + pkg, e); 8831 } 8832 sb.append("\n"); 8833 } 8834 processClass(ProcessRecord process)8835 private static String processClass(ProcessRecord process) { 8836 if (process == null || process.getPid() == MY_PID) { 8837 return "system_server"; 8838 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8839 return "system_app"; 8840 } else { 8841 return "data_app"; 8842 } 8843 } 8844 8845 private final DropboxRateLimiter mDropboxRateLimiter = new DropboxRateLimiter(); 8846 8847 /** 8848 * Write a description of an error (crash, WTF, ANR) to the drop box. 8849 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 8850 * @param process which caused the error, null means the system server 8851 * @param activityShortComponentName which triggered the error, null if unknown 8852 * @param parentShortComponentName activity related to the error, null if unknown 8853 * @param parentProcess parent process 8854 * @param subject line related to the error, null if absent 8855 * @param report in long form describing the error, null if absent 8856 * @param dataFile text file to include in the report, null if none 8857 * @param crashInfo giving an application stack trace, null if absent 8858 * @param loadingProgress the loading progress of an installed package, range in [0, 1]. 8859 * @param incrementalMetrics metrics for apps installed on Incremental. 8860 * @param errorId a unique id to append to the dropbox headers. 8861 */ 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)8862 public void addErrorToDropBox(String eventType, 8863 ProcessRecord process, String processName, String activityShortComponentName, 8864 String parentShortComponentName, ProcessRecord parentProcess, 8865 String subject, final String report, final File dataFile, 8866 final ApplicationErrorReport.CrashInfo crashInfo, 8867 @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics, 8868 @Nullable UUID errorId) { 8869 // NOTE -- this must never acquire the ActivityManagerService lock, 8870 // otherwise the watchdog may be prevented from resetting the system. 8871 8872 // Bail early if not published yet 8873 if (ServiceManager.getService(Context.DROPBOX_SERVICE) == null) return; 8874 final DropBoxManager dbox = mContext.getSystemService(DropBoxManager.class); 8875 8876 // Exit early if the dropbox isn't configured to accept this report type. 8877 final String dropboxTag = processClass(process) + "_" + eventType; 8878 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 8879 8880 // Check if we should rate limit and abort early if needed. 8881 final DropboxRateLimiter.RateLimitResult rateLimitResult = 8882 mDropboxRateLimiter.shouldRateLimit(eventType, processName); 8883 if (rateLimitResult.shouldRateLimit()) return; 8884 8885 final StringBuilder sb = new StringBuilder(1024); 8886 appendDropBoxProcessHeaders(process, processName, sb); 8887 if (process != null) { 8888 sb.append("Foreground: ") 8889 .append(process.isInterestingToUserLocked() ? "Yes" : "No") 8890 .append("\n"); 8891 if (process.getStartTime() > 0) { 8892 long runtimeMillis = SystemClock.elapsedRealtime() - process.getStartTime(); 8893 sb.append("Process-Runtime: ").append(runtimeMillis).append("\n"); 8894 } 8895 } 8896 if (activityShortComponentName != null) { 8897 sb.append("Activity: ").append(activityShortComponentName).append("\n"); 8898 } 8899 if (parentShortComponentName != null) { 8900 if (parentProcess != null && parentProcess.getPid() != process.getPid()) { 8901 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n"); 8902 } 8903 if (!parentShortComponentName.equals(activityShortComponentName)) { 8904 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n"); 8905 } 8906 } 8907 if (subject != null) { 8908 sb.append("Subject: ").append(subject).append("\n"); 8909 } 8910 if (errorId != null) { 8911 sb.append("ErrorId: ").append(errorId.toString()).append("\n"); 8912 } 8913 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 8914 if (Debug.isDebuggerConnected()) { 8915 sb.append("Debugger: Connected\n"); 8916 } 8917 if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) { 8918 sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n"); 8919 } 8920 if (loadingProgress != null) { 8921 sb.append("Loading-Progress: ").append(loadingProgress.floatValue()).append("\n"); 8922 } 8923 if (incrementalMetrics != null) { 8924 sb.append("Incremental: Yes").append("\n"); 8925 final long millisSinceOldestPendingRead = 8926 incrementalMetrics.getMillisSinceOldestPendingRead(); 8927 if (millisSinceOldestPendingRead > 0) { 8928 sb.append("Millis-Since-Oldest-Pending-Read: ").append( 8929 millisSinceOldestPendingRead).append("\n"); 8930 } 8931 } 8932 sb.append(rateLimitResult.createHeader()); 8933 sb.append("\n"); 8934 8935 // Do the rest in a worker thread to avoid blocking the caller on I/O 8936 // (After this point, we shouldn't access AMS internal data structures.) 8937 Thread worker = new Thread("Error dump: " + dropboxTag) { 8938 @Override 8939 public void run() { 8940 if (report != null) { 8941 sb.append(report); 8942 } 8943 8944 String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 8945 String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag; 8946 int lines = Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0); 8947 int dropboxMaxSize = Settings.Global.getInt( 8948 mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE); 8949 int maxDataFileSize = dropboxMaxSize - sb.length() 8950 - lines * RESERVED_BYTES_PER_LOGCAT_LINE; 8951 8952 if (dataFile != null && maxDataFileSize > 0) { 8953 try { 8954 sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize, 8955 "\n\n[[TRUNCATED]]")); 8956 } catch (IOException e) { 8957 Slog.e(TAG, "Error reading " + dataFile, e); 8958 } 8959 } 8960 if (crashInfo != null && crashInfo.stackTrace != null) { 8961 sb.append(crashInfo.stackTrace); 8962 } 8963 8964 if (lines > 0) { 8965 sb.append("\n"); 8966 8967 InputStreamReader input = null; 8968 try { 8969 java.lang.Process logcat = new ProcessBuilder( 8970 // Time out after 10s, but kill logcat with SEGV 8971 // so we can investigate why it didn't finish. 8972 "/system/bin/timeout", "-s", "SEGV", "10s", 8973 // Merge several logcat streams, and take the last N lines. 8974 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system", 8975 "-b", "main", "-b", "crash", "-t", String.valueOf(lines)) 8976 .redirectErrorStream(true).start(); 8977 8978 try { logcat.getOutputStream().close(); } catch (IOException e) {} 8979 try { logcat.getErrorStream().close(); } catch (IOException e) {} 8980 input = new InputStreamReader(logcat.getInputStream()); 8981 8982 int num; 8983 char[] buf = new char[8192]; 8984 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num); 8985 } catch (IOException e) { 8986 Slog.e(TAG, "Error running logcat", e); 8987 } finally { 8988 if (input != null) try { input.close(); } catch (IOException e) {} 8989 } 8990 } 8991 8992 dbox.addText(dropboxTag, sb.toString()); 8993 } 8994 }; 8995 8996 if (process == null) { 8997 // If process is null, we are being called from some internal code 8998 // and may be about to die -- run this synchronously. 8999 final int oldMask = StrictMode.allowThreadDiskWritesMask(); 9000 try { 9001 worker.run(); 9002 } finally { 9003 StrictMode.setThreadPolicyMask(oldMask); 9004 } 9005 } else { 9006 worker.start(); 9007 } 9008 } 9009 9010 @Override getProcessesInErrorState()9011 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 9012 enforceNotIsolatedCaller("getProcessesInErrorState"); 9013 // assume our apps are happy - lazy create the list 9014 final List<ActivityManager.ProcessErrorStateInfo>[] errList = new List[1]; 9015 9016 final int callingUid = Binder.getCallingUid(); 9017 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 9018 callingUid) == PackageManager.PERMISSION_GRANTED; 9019 int userId = UserHandle.getUserId(callingUid); 9020 9021 final boolean hasDumpPermission = ActivityManager.checkUidPermission( 9022 android.Manifest.permission.DUMP, callingUid) == PackageManager.PERMISSION_GRANTED; 9023 9024 synchronized (mProcLock) { 9025 // iterate across all processes 9026 mProcessList.forEachLruProcessesLOSP(false, app -> { 9027 if (!allUsers && app.userId != userId) { 9028 return; 9029 } 9030 if (!hasDumpPermission && app.info.uid != callingUid) { 9031 return; 9032 } 9033 final ProcessErrorStateRecord errState = app.mErrorState; 9034 final boolean crashing = errState.isCrashing(); 9035 final boolean notResponding = errState.isNotResponding(); 9036 if ((app.getThread() != null) && (crashing || notResponding)) { 9037 // This one's in trouble, so we'll generate a report for it 9038 // crashes are higher priority (in case there's a crash *and* an anr) 9039 ActivityManager.ProcessErrorStateInfo report = null; 9040 if (crashing) { 9041 report = errState.getCrashingReport(); 9042 } else if (notResponding) { 9043 report = errState.getNotRespondingReport(); 9044 } 9045 9046 if (report != null) { 9047 if (errList[0] == null) { 9048 errList[0] = new ArrayList<>(1); 9049 } 9050 errList[0].add(report); 9051 } else { 9052 Slog.w(TAG, "Missing app error report, app = " + app.processName + 9053 " crashing = " + crashing + 9054 " notResponding = " + notResponding); 9055 } 9056 } 9057 }); 9058 } 9059 9060 return errList[0]; 9061 } 9062 9063 @Override getRunningAppProcesses()9064 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 9065 enforceNotIsolatedCaller("getRunningAppProcesses"); 9066 9067 final int callingUid = Binder.getCallingUid(); 9068 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 9069 9070 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 9071 callingUid) == PackageManager.PERMISSION_GRANTED; 9072 final int userId = UserHandle.getUserId(callingUid); 9073 final boolean allUids = mAtmInternal.isGetTasksAllowed( 9074 "getRunningAppProcesses", Binder.getCallingPid(), callingUid); 9075 9076 synchronized (mProcLock) { 9077 // Iterate across all processes 9078 return mProcessList.getRunningAppProcessesLOSP(allUsers, userId, allUids, 9079 callingUid, clientTargetSdk); 9080 } 9081 } 9082 9083 @Override getRunningExternalApplications()9084 public List<ApplicationInfo> getRunningExternalApplications() { 9085 enforceNotIsolatedCaller("getRunningExternalApplications"); 9086 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 9087 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 9088 if (runningApps != null && runningApps.size() > 0) { 9089 Set<String> extList = new HashSet<String>(); 9090 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 9091 if (app.pkgList != null) { 9092 for (String pkg : app.pkgList) { 9093 extList.add(pkg); 9094 } 9095 } 9096 } 9097 IPackageManager pm = AppGlobals.getPackageManager(); 9098 for (String pkg : extList) { 9099 try { 9100 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 9101 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 9102 retList.add(info); 9103 } 9104 } catch (RemoteException e) { 9105 } 9106 } 9107 } 9108 return retList; 9109 } 9110 9111 @Override getHistoricalProcessExitReasons( String packageName, int pid, int maxNum, int userId)9112 public ParceledListSlice<ApplicationExitInfo> getHistoricalProcessExitReasons( 9113 String packageName, int pid, int maxNum, int userId) { 9114 enforceNotIsolatedCaller("getHistoricalProcessExitReasons"); 9115 9116 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 9117 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 9118 throw new IllegalArgumentException("Unsupported userId"); 9119 } 9120 9121 final int callingPid = Binder.getCallingPid(); 9122 final int callingUid = Binder.getCallingUid(); 9123 final int callingUserId = UserHandle.getCallingUserId(); 9124 mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL, 9125 "getHistoricalProcessExitReasons", null); 9126 9127 NativeTombstoneManager tombstoneService = LocalServices.getService( 9128 NativeTombstoneManager.class); 9129 9130 final ArrayList<ApplicationExitInfo> results = new ArrayList<ApplicationExitInfo>(); 9131 if (!TextUtils.isEmpty(packageName)) { 9132 final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid, 9133 "getHistoricalProcessExitReasons"); 9134 if (uid != INVALID_UID) { 9135 mProcessList.mAppExitInfoTracker.getExitInfo( 9136 packageName, uid, pid, maxNum, results); 9137 tombstoneService.collectTombstones(results, uid, pid, maxNum); 9138 } 9139 } else { 9140 // If no package name is given, use the caller's uid as the filter uid. 9141 mProcessList.mAppExitInfoTracker.getExitInfo( 9142 packageName, callingUid, pid, maxNum, results); 9143 tombstoneService.collectTombstones(results, callingUid, pid, maxNum); 9144 } 9145 9146 return new ParceledListSlice<ApplicationExitInfo>(results); 9147 } 9148 9149 @Override setProcessStateSummary(@ullable byte[] state)9150 public void setProcessStateSummary(@Nullable byte[] state) { 9151 if (state != null && state.length > MAX_STATE_DATA_SIZE) { 9152 throw new IllegalArgumentException("Data size is too large"); 9153 } 9154 mProcessList.mAppExitInfoTracker.setProcessStateSummary(Binder.getCallingUid(), 9155 Binder.getCallingPid(), state); 9156 } 9157 9158 /** 9159 * Check if the calling process has the permission to dump given package, 9160 * throw SecurityException if it doesn't have the permission. 9161 * 9162 * @return The UID of the given package, or {@link android.os.Process#INVALID_UID} 9163 * if the package is not found. 9164 */ enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, String function)9165 int enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, 9166 String function) { 9167 final long identity = Binder.clearCallingIdentity(); 9168 int uid = INVALID_UID; 9169 try { 9170 uid = mPackageManagerInt.getPackageUid(packageName, 9171 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId); 9172 } finally { 9173 Binder.restoreCallingIdentity(identity); 9174 } 9175 // If the uid is Process.INVALID_UID, the below 'if' check will be always true 9176 if (UserHandle.getAppId(uid) != UserHandle.getAppId(callingUid)) { 9177 // Requires the DUMP permission if the target package doesn't belong 9178 // to the caller or it doesn't exist. 9179 enforceCallingPermission(android.Manifest.permission.DUMP, function); 9180 } 9181 return uid; 9182 } 9183 9184 @Override getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)9185 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) { 9186 if (outState == null) { 9187 throw new IllegalArgumentException("outState is null"); 9188 } 9189 enforceNotIsolatedCaller("getMyMemoryState"); 9190 9191 final int callingUid = Binder.getCallingUid(); 9192 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 9193 9194 synchronized (mProcLock) { 9195 ProcessRecord proc; 9196 synchronized (mPidsSelfLocked) { 9197 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 9198 } 9199 if (proc != null) { 9200 mProcessList.fillInProcMemInfoLOSP(proc, outState, clientTargetSdk); 9201 } 9202 } 9203 } 9204 9205 @Override getMemoryTrimLevel()9206 public @MemFactor int getMemoryTrimLevel() { 9207 enforceNotIsolatedCaller("getMyMemoryState"); 9208 synchronized (this) { 9209 return mAppProfiler.getLastMemoryLevelLocked(); 9210 } 9211 } 9212 setMemFactorOverride(@emFactor int level)9213 void setMemFactorOverride(@MemFactor int level) { 9214 synchronized (this) { 9215 if (level == mAppProfiler.getLastMemoryLevelLocked()) { 9216 return; 9217 } 9218 9219 mAppProfiler.setMemFactorOverrideLocked(level); 9220 // Kick off an oom adj update since we forced a mem factor update. 9221 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 9222 } 9223 } 9224 9225 /** 9226 * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}. 9227 */ setServiceRestartBackoffEnabled(@onNull String packageName, boolean enable, @NonNull String reason)9228 void setServiceRestartBackoffEnabled(@NonNull String packageName, boolean enable, 9229 @NonNull String reason) { 9230 synchronized (this) { 9231 mServices.setServiceRestartBackoffEnabledLocked(packageName, enable, reason); 9232 } 9233 } 9234 9235 /** 9236 * @return {@code false} if the given package has been disable from enforcing the service 9237 * restart backoff policy, used by {@link ActivityManagerShellCommand}. 9238 */ isServiceRestartBackoffEnabled(@onNull String packageName)9239 boolean isServiceRestartBackoffEnabled(@NonNull String packageName) { 9240 synchronized (this) { 9241 return mServices.isServiceRestartBackoffEnabledLocked(packageName); 9242 } 9243 } 9244 9245 @Override onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)9246 public void onShellCommand(FileDescriptor in, FileDescriptor out, 9247 FileDescriptor err, String[] args, ShellCallback callback, 9248 ResultReceiver resultReceiver) { 9249 (new ActivityManagerShellCommand(this, false)).exec( 9250 this, in, out, err, args, callback, resultReceiver); 9251 } 9252 9253 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)9254 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9255 PriorityDump.dump(mPriorityDumper, fd, pw, args); 9256 } 9257 dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies)9258 private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, 9259 boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, 9260 int dumpAppId, boolean dumpProxies) { 9261 9262 ActiveServices.ServiceDumper sdumper; 9263 9264 synchronized(this) { 9265 mConstants.dump(pw); 9266 synchronized (mProcLock) { 9267 mOomAdjuster.dumpCachedAppOptimizerSettings(pw); 9268 } 9269 mOomAdjuster.dumpCacheOomRankerSettings(pw); 9270 pw.println(); 9271 if (dumpAll) { 9272 pw.println("-------------------------------------------------------------------------------"); 9273 9274 } 9275 dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9276 pw.println(); 9277 if (dumpAll) { 9278 pw.println("-------------------------------------------------------------------------------"); 9279 9280 } 9281 mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage); 9282 pw.println(); 9283 if (dumpAll) { 9284 pw.println("-------------------------------------------------------------------------------"); 9285 } 9286 dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9287 pw.println(); 9288 if (dumpAll) { 9289 pw.println("-------------------------------------------------------------------------------"); 9290 } 9291 if (dumpAll || dumpPackage != null) { 9292 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9293 pw.println(); 9294 if (dumpAll) { 9295 pw.println("-------------------------------------------------------------------------------"); 9296 } 9297 } 9298 mCpHelper.dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9299 pw.println(); 9300 if (dumpAll) { 9301 pw.println("-------------------------------------------------------------------------------"); 9302 } 9303 dumpPermissions(fd, pw, args, opti, dumpAll, dumpPackage); 9304 pw.println(); 9305 sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage); 9306 if (!dumpClient) { 9307 if (dumpAll) { 9308 pw.println("-------------------------------------------------------------------------------"); 9309 } 9310 sdumper.dumpLocked(); 9311 } 9312 } 9313 // We drop the lock here because we can't call dumpWithClient() with the lock held; 9314 // if the caller wants a consistent state for the !dumpClient case, it can call this 9315 // method with the lock held. 9316 if (dumpClient) { 9317 if (dumpAll) { 9318 pw.println("-------------------------------------------------------------------------------"); 9319 } 9320 sdumper.dumpWithClient(); 9321 } 9322 if (dumpPackage == null && dumpProxies) { 9323 // Intentionally dropping the lock for this, because dumpBinderProxies() will make many 9324 // outgoing binder calls to retrieve interface descriptors; while that is system code, 9325 // there is nothing preventing an app from overriding this implementation by talking to 9326 // the binder driver directly, and hang up system_server in the process. So, dump 9327 // without locks held, and even then only when there is an unreasonably large number of 9328 // proxies in the first place. 9329 pw.println(); 9330 if (dumpAll) { 9331 pw.println("-------------------------------------------------------------------------------"); 9332 } 9333 dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */); 9334 } 9335 synchronized(this) { 9336 pw.println(); 9337 if (dumpAll) { 9338 pw.println("-------------------------------------------------------------------------------"); 9339 } 9340 mAtmInternal.dump( 9341 DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9342 pw.println(); 9343 if (dumpAll) { 9344 pw.println("-------------------------------------------------------------------------------"); 9345 } 9346 mAtmInternal.dump( 9347 DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9348 pw.println(); 9349 if (dumpAll) { 9350 pw.println("-------------------------------------------------------------------------------"); 9351 } 9352 mAtmInternal.dump( 9353 DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9354 if (dumpPackage == null) { 9355 pw.println(); 9356 if (dumpAll) { 9357 pw.println("-------------------------------------------------------------------------------"); 9358 } 9359 mAtmInternal.dump( 9360 DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9361 } 9362 // Activities section is dumped as part of the Critical priority dump. Exclude the 9363 // section if priority is Normal. 9364 if (!dumpNormalPriority) { 9365 pw.println(); 9366 if (dumpAll) { 9367 pw.println("-------------------------------------------------------------------------------"); 9368 } 9369 mAtmInternal.dump( 9370 DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9371 } 9372 if (mAssociations.size() > 0) { 9373 pw.println(); 9374 if (dumpAll) { 9375 pw.println("-------------------------------------------------------------------------------"); 9376 } 9377 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 9378 } 9379 pw.println(); 9380 if (dumpAll) { 9381 pw.println("-------------------------------------------------------------------------------"); 9382 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage); 9383 } 9384 if (dumpPackage == null) { 9385 pw.println(); 9386 if (dumpAll) { 9387 pw.println("-------------------------------------------------------------------------------"); 9388 } 9389 mOomAdjProfiler.dump(pw); 9390 pw.println(); 9391 if (dumpAll) { 9392 pw.println("-------------------------------------------------------------------------------"); 9393 } 9394 dumpLmkLocked(pw); 9395 } 9396 pw.println(); 9397 if (dumpAll) { 9398 pw.println("-------------------------------------------------------------------------------"); 9399 } 9400 synchronized (mProcLock) { 9401 mProcessList.dumpProcessesLSP(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId); 9402 } 9403 pw.println(); 9404 if (dumpAll) { 9405 pw.println("-------------------------------------------------------------------------------"); 9406 } 9407 dumpUsers(pw); 9408 9409 pw.println(); 9410 if (dumpAll) { 9411 pw.println("-------------------------------------------------------------------------------"); 9412 } 9413 mComponentAliasResolver.dump(pw); 9414 } 9415 } 9416 9417 /** 9418 * Dump the app restriction controller, it's required not to hold the global lock here. 9419 */ dumpAppRestrictionController(PrintWriter pw)9420 private void dumpAppRestrictionController(PrintWriter pw) { 9421 pw.println("-------------------------------------------------------------------------------"); 9422 mAppRestrictionController.dump(pw, ""); 9423 } 9424 dumpAppRestrictionController(ProtoOutputStream proto, int uid)9425 void dumpAppRestrictionController(ProtoOutputStream proto, int uid) { 9426 mAppRestrictionController.dumpAsProto(proto, uid); 9427 } 9428 9429 /** 9430 * Wrapper function to print out debug data filtered by specified arguments. 9431 */ 9432 @NeverCompile // Avoid size overhead of debugging code. doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)9433 private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) { 9434 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 9435 9436 boolean dumpAll = false; 9437 boolean dumpClient = false; 9438 boolean dumpCheckin = false; 9439 boolean dumpCheckinFormat = false; 9440 boolean dumpNormalPriority = false; 9441 boolean dumpVisibleStacksOnly = false; 9442 boolean dumpFocusedStackOnly = false; 9443 String dumpPackage = null; 9444 int dumpUserId = UserHandle.USER_ALL; 9445 9446 int opti = 0; 9447 while (opti < args.length) { 9448 String opt = args[opti]; 9449 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 9450 break; 9451 } 9452 opti++; 9453 if ("-a".equals(opt)) { 9454 dumpAll = true; 9455 } else if ("-c".equals(opt)) { 9456 dumpClient = true; 9457 } else if ("-v".equals(opt)) { 9458 dumpVisibleStacksOnly = true; 9459 } else if ("-f".equals(opt)) { 9460 dumpFocusedStackOnly = true; 9461 } else if ("-p".equals(opt)) { 9462 if (opti < args.length) { 9463 dumpPackage = args[opti]; 9464 opti++; 9465 } else { 9466 pw.println("Error: -p option requires package argument"); 9467 return; 9468 } 9469 dumpClient = true; 9470 } else if ("--checkin".equals(opt)) { 9471 dumpCheckin = dumpCheckinFormat = true; 9472 } else if ("-C".equals(opt)) { 9473 dumpCheckinFormat = true; 9474 } else if ("--normal-priority".equals(opt)) { 9475 dumpNormalPriority = true; 9476 } else if ("--user".equals(opt)) { 9477 if (opti < args.length) { 9478 dumpUserId = UserHandle.parseUserArg(args[opti]); 9479 if (dumpUserId == UserHandle.USER_CURRENT) { 9480 dumpUserId = mUserController.getCurrentUserId(); 9481 } 9482 opti++; 9483 } else { 9484 pw.println("Error: --user option requires user id argument"); 9485 return; 9486 } 9487 } else if ("-h".equals(opt)) { 9488 ActivityManagerShellCommand.dumpHelp(pw, true); 9489 return; 9490 } else { 9491 pw.println("Unknown argument: " + opt + "; use -h for help"); 9492 } 9493 } 9494 9495 final long origId = Binder.clearCallingIdentity(); 9496 9497 if (useProto) { 9498 final ProtoOutputStream proto = new ProtoOutputStream(fd); 9499 String cmd = opti < args.length ? args[opti] : ""; 9500 opti++; 9501 9502 if ("activities".equals(cmd) || "a".equals(cmd)) { 9503 // output proto is ActivityManagerServiceDumpActivitiesProto 9504 mAtmInternal.writeActivitiesToProto(proto); 9505 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 9506 // output proto is ActivityManagerServiceDumpBroadcastsProto 9507 synchronized (this) { 9508 writeBroadcastsToProtoLocked(proto); 9509 } 9510 } else if ("provider".equals(cmd)) { 9511 String[] newArgs; 9512 String name; 9513 if (opti >= args.length) { 9514 name = null; 9515 newArgs = EMPTY_STRING_ARRAY; 9516 } else { 9517 name = args[opti]; 9518 opti++; 9519 newArgs = new String[args.length - opti]; 9520 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 9521 args.length - opti); 9522 } 9523 if (!mCpHelper.dumpProviderProto(fd, pw, name, newArgs)) { 9524 pw.println("No providers match: " + name); 9525 pw.println("Use -h for help."); 9526 } 9527 } else if ("service".equals(cmd)) { 9528 // output proto is ActivityManagerServiceDumpServicesProto 9529 mServices.dumpDebug(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 9530 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 9531 if (opti < args.length) { 9532 dumpPackage = args[opti]; 9533 opti++; 9534 } 9535 // output proto is ProcessProto 9536 synchronized (this) { 9537 synchronized (mProcLock) { 9538 mProcessList.writeProcessesToProtoLSP(proto, dumpPackage); 9539 } 9540 } 9541 } else if ("app-restrictions".equals(cmd)) { 9542 int uid = Process.INVALID_UID; 9543 boolean error = false; 9544 for (int i = 0; i < args.length; i++) { 9545 if ("--uid".equals(args[i])) { 9546 if (i + 1 < args.length) { 9547 try { 9548 uid = Integer.parseInt(args[i + 1]); 9549 } catch (NumberFormatException e) { 9550 error = true; 9551 } 9552 } else { 9553 error = true; 9554 } 9555 break; 9556 } 9557 } 9558 if (error) { 9559 pw.println("Invalid --uid argument"); 9560 pw.println("Use -h for help."); 9561 } else { 9562 dumpAppRestrictionController(proto, uid); 9563 } 9564 } else { 9565 // default option, dump everything, output is ActivityManagerServiceProto 9566 synchronized (this) { 9567 long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES); 9568 mAtmInternal.writeActivitiesToProto(proto); 9569 proto.end(activityToken); 9570 9571 long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS); 9572 writeBroadcastsToProtoLocked(proto); 9573 proto.end(broadcastToken); 9574 9575 long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES); 9576 mServices.dumpDebug(proto, 9577 ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 9578 proto.end(serviceToken); 9579 9580 long processToken = proto.start(ActivityManagerServiceProto.PROCESSES); 9581 synchronized (mProcLock) { 9582 mProcessList.writeProcessesToProtoLSP(proto, dumpPackage); 9583 } 9584 proto.end(processToken); 9585 } 9586 } 9587 proto.flush(); 9588 Binder.restoreCallingIdentity(origId); 9589 return; 9590 } 9591 9592 int dumpAppId = getAppId(dumpPackage); 9593 boolean more = false; 9594 // Is the caller requesting to dump a particular piece of data? 9595 if (opti < args.length) { 9596 String cmd = args[opti]; 9597 opti++; 9598 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd) 9599 || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd) 9600 || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd) 9601 || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd) 9602 || DUMP_TOP_RESUMED_ACTIVITY.equals(cmd) 9603 || DUMP_VISIBLE_ACTIVITIES.equals(cmd)) { 9604 mAtmInternal.dump( 9605 cmd, fd, pw, args, opti, true /* dumpAll */, dumpClient, dumpPackage); 9606 } else if ("binder-proxies".equals(cmd)) { 9607 if (opti >= args.length) { 9608 dumpBinderProxies(pw, 0 /* minToDump */); 9609 } else { 9610 String uid = args[opti]; 9611 opti++; 9612 // Ensure Binder Proxy Count is as up to date as possible 9613 System.gc(); 9614 System.runFinalization(); 9615 System.gc(); 9616 pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid))); 9617 } 9618 } else if ("allowed-associations".equals(cmd)) { 9619 if (opti < args.length) { 9620 dumpPackage = args[opti]; 9621 opti++; 9622 } 9623 synchronized (this) { 9624 dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage); 9625 } 9626 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 9627 if (opti < args.length) { 9628 dumpPackage = args[opti]; 9629 opti++; 9630 } 9631 synchronized (this) { 9632 dumpBroadcastsLocked(fd, pw, args, opti, true, dumpPackage); 9633 } 9634 } else if ("broadcast-stats".equals(cmd)) { 9635 if (opti < args.length) { 9636 dumpPackage = args[opti]; 9637 opti++; 9638 } 9639 synchronized (this) { 9640 if (dumpCheckinFormat) { 9641 dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, 9642 dumpPackage); 9643 } else { 9644 dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage); 9645 } 9646 } 9647 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 9648 if (opti < args.length) { 9649 dumpPackage = args[opti]; 9650 opti++; 9651 } 9652 mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage); 9653 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 9654 if (opti < args.length) { 9655 dumpPackage = args[opti]; 9656 opti++; 9657 } 9658 synchronized (this) { 9659 synchronized (mProcLock) { 9660 mProcessList.dumpProcessesLSP( 9661 fd, pw, args, opti, true, dumpPackage, dumpAppId); 9662 } 9663 } 9664 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 9665 synchronized (this) { 9666 mProcessList.dumpOomLocked(fd, pw, false, args, opti, true, dumpPackage, true); 9667 } 9668 } else if ("lmk".equals(cmd)) { 9669 synchronized (this) { 9670 dumpLmkLocked(pw); 9671 } 9672 } else if ("lru".equals(cmd)) { 9673 synchronized (this) { 9674 mProcessList.dumpLruLocked(pw, dumpPackage, null); 9675 } 9676 } else if ("permissions".equals(cmd) || "perm".equals(cmd)) { 9677 dumpPermissions(fd, pw, args, opti, true, dumpPackage); 9678 } else if ("provider".equals(cmd)) { 9679 String[] newArgs; 9680 String name; 9681 if (opti >= args.length) { 9682 name = null; 9683 newArgs = EMPTY_STRING_ARRAY; 9684 } else { 9685 name = args[opti]; 9686 opti++; 9687 newArgs = new String[args.length - opti]; 9688 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti); 9689 } 9690 if (!mCpHelper.dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 9691 pw.println("No providers match: " + name); 9692 pw.println("Use -h for help."); 9693 } 9694 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 9695 synchronized (this) { 9696 mCpHelper.dumpProvidersLocked(fd, pw, args, opti, true, dumpPackage); 9697 } 9698 } else if ("service".equals(cmd)) { 9699 String[] newArgs; 9700 String name; 9701 if (opti >= args.length) { 9702 name = null; 9703 newArgs = EMPTY_STRING_ARRAY; 9704 } else { 9705 name = args[opti]; 9706 opti++; 9707 newArgs = new String[args.length - opti]; 9708 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 9709 args.length - opti); 9710 } 9711 int[] users = dumpUserId == UserHandle.USER_ALL ? null : new int[] { dumpUserId }; 9712 if (!mServices.dumpService(fd, pw, name, users, newArgs, 0, dumpAll)) { 9713 pw.println("No services match: " + name); 9714 pw.println("Use -h for help."); 9715 } 9716 } else if ("package".equals(cmd)) { 9717 String[] newArgs; 9718 if (opti >= args.length) { 9719 pw.println("package: no package name specified"); 9720 pw.println("Use -h for help."); 9721 } else { 9722 dumpPackage = args[opti]; 9723 opti++; 9724 newArgs = new String[args.length - opti]; 9725 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 9726 args.length - opti); 9727 args = newArgs; 9728 opti = 0; 9729 more = true; 9730 } 9731 } else if ("associations".equals(cmd) || "as".equals(cmd)) { 9732 synchronized (this) { 9733 dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage); 9734 } 9735 } else if ("settings".equals(cmd)) { 9736 synchronized (this) { 9737 mConstants.dump(pw); 9738 } 9739 synchronized (mProcLock) { 9740 mOomAdjuster.dumpCachedAppOptimizerSettings(pw); 9741 mOomAdjuster.dumpCacheOomRankerSettings(pw); 9742 } 9743 } else if ("services".equals(cmd) || "s".equals(cmd)) { 9744 if (dumpClient) { 9745 ActiveServices.ServiceDumper dumper; 9746 synchronized (this) { 9747 dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true, 9748 dumpPackage); 9749 } 9750 dumper.dumpWithClient(); 9751 } else { 9752 synchronized (this) { 9753 mServices.newServiceDumperLocked(fd, pw, args, opti, true, 9754 dumpPackage).dumpLocked(); 9755 } 9756 } 9757 } else if ("locks".equals(cmd)) { 9758 LockGuard.dump(fd, pw, args); 9759 } else if ("users".equals(cmd)) { 9760 dumpUsers(pw); 9761 } else if ("exit-info".equals(cmd)) { 9762 if (opti < args.length) { 9763 dumpPackage = args[opti]; 9764 opti++; 9765 } 9766 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage); 9767 } else if ("component-alias".equals(cmd)) { 9768 mComponentAliasResolver.dump(pw); 9769 } else { 9770 // Dumping a single activity? 9771 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll, 9772 dumpVisibleStacksOnly, dumpFocusedStackOnly, dumpUserId)) { 9773 ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true); 9774 int res = shell.exec(this, null, fd, null, args, null, 9775 new ResultReceiver(null)); 9776 if (res < 0) { 9777 pw.println("Bad activity command, or no activities match: " + cmd); 9778 pw.println("Use -h for help."); 9779 } 9780 } 9781 } 9782 if (!more) { 9783 Binder.restoreCallingIdentity(origId); 9784 return; 9785 } 9786 } 9787 9788 // No piece of data specified, dump everything. 9789 if (dumpCheckinFormat) { 9790 dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage); 9791 } else { 9792 if (dumpClient) { 9793 // dumpEverything() will take the lock when needed, and momentarily drop 9794 // it for dumping client state. 9795 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient, 9796 dumpNormalPriority, dumpAppId, true /* dumpProxies */); 9797 } else { 9798 // Take the lock here, so we get a consistent state for the entire dump; 9799 // dumpEverything() will take the lock as well, which is fine for everything 9800 // except dumping proxies, which can take a long time; exclude them. 9801 synchronized(this) { 9802 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient, 9803 dumpNormalPriority, dumpAppId, false /* dumpProxies */); 9804 } 9805 } 9806 if (dumpAll) { 9807 dumpAppRestrictionController(pw); 9808 } 9809 } 9810 Binder.restoreCallingIdentity(origId); 9811 } 9812 dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)9813 void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 9814 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 9815 pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)"); 9816 9817 int dumpUid = 0; 9818 if (dumpPackage != null) { 9819 IPackageManager pm = AppGlobals.getPackageManager(); 9820 try { 9821 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0); 9822 } catch (RemoteException e) { 9823 } 9824 } 9825 9826 boolean printedAnything = false; 9827 9828 final long now = SystemClock.uptimeMillis(); 9829 9830 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 9831 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 9832 = mAssociations.valueAt(i1); 9833 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 9834 SparseArray<ArrayMap<String, Association>> sourceUids 9835 = targetComponents.valueAt(i2); 9836 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) { 9837 ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3); 9838 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 9839 Association ass = sourceProcesses.valueAt(i4); 9840 if (dumpPackage != null) { 9841 if (!ass.mTargetComponent.getPackageName().equals(dumpPackage) 9842 && UserHandle.getAppId(ass.mSourceUid) != dumpUid) { 9843 continue; 9844 } 9845 } 9846 printedAnything = true; 9847 pw.print(" "); 9848 pw.print(ass.mTargetProcess); 9849 pw.print("/"); 9850 UserHandle.formatUid(pw, ass.mTargetUid); 9851 pw.print(" <- "); 9852 pw.print(ass.mSourceProcess); 9853 pw.print("/"); 9854 UserHandle.formatUid(pw, ass.mSourceUid); 9855 pw.println(); 9856 pw.print(" via "); 9857 pw.print(ass.mTargetComponent.flattenToShortString()); 9858 pw.println(); 9859 pw.print(" "); 9860 long dur = ass.mTime; 9861 if (ass.mNesting > 0) { 9862 dur += now - ass.mStartTime; 9863 } 9864 TimeUtils.formatDuration(dur, pw); 9865 pw.print(" ("); 9866 pw.print(ass.mCount); 9867 pw.print(" times)"); 9868 pw.print(" "); 9869 for (int i=0; i<ass.mStateTimes.length; i++) { 9870 long amt = ass.mStateTimes[i]; 9871 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 9872 amt += now - ass.mLastStateUptime; 9873 } 9874 if (amt != 0) { 9875 pw.print(" "); 9876 pw.print(ProcessList.makeProcStateString( 9877 i + ActivityManager.MIN_PROCESS_STATE)); 9878 pw.print("="); 9879 TimeUtils.formatDuration(amt, pw); 9880 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 9881 pw.print("*"); 9882 } 9883 } 9884 } 9885 pw.println(); 9886 if (ass.mNesting > 0) { 9887 pw.print(" Currently active: "); 9888 TimeUtils.formatDuration(now - ass.mStartTime, pw); 9889 pw.println(); 9890 } 9891 } 9892 } 9893 } 9894 9895 } 9896 9897 if (!printedAnything) { 9898 pw.println(" (nothing)"); 9899 } 9900 } 9901 getAppId(String dumpPackage)9902 int getAppId(String dumpPackage) { 9903 if (dumpPackage != null) { 9904 try { 9905 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 9906 dumpPackage, 0); 9907 return UserHandle.getAppId(info.uid); 9908 } catch (NameNotFoundException e) { 9909 e.printStackTrace(); 9910 } 9911 } 9912 return -1; 9913 } 9914 dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)9915 void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) { 9916 final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50); 9917 9918 pw.println(header); 9919 for (int i = 0; i < proxyCounts.length; i++) { 9920 pw.println(" #" + (i + 1) + ": " + proxyCounts[i]); 9921 } 9922 } 9923 dumpBinderProxiesCounts(PrintWriter pw, String header)9924 boolean dumpBinderProxiesCounts(PrintWriter pw, String header) { 9925 SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts(); 9926 if(counts != null) { 9927 pw.println(header); 9928 for (int i = 0; i < counts.size(); i++) { 9929 final int uid = counts.keyAt(i); 9930 final int binderCount = counts.valueAt(i); 9931 pw.print(" UID "); 9932 pw.print(uid); 9933 pw.print(", binder count = "); 9934 pw.print(binderCount); 9935 pw.print(", package(s)= "); 9936 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid); 9937 if (pkgNames != null) { 9938 for (int j = 0; j < pkgNames.length; j++) { 9939 pw.print(pkgNames[j]); 9940 pw.print("; "); 9941 } 9942 } else { 9943 pw.print("NO PACKAGE NAME FOUND"); 9944 } 9945 pw.println(); 9946 } 9947 return true; 9948 } 9949 return false; 9950 } 9951 dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)9952 void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) { 9953 pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)"); 9954 final int proxyCount = BinderProxy.getProxyCount(); 9955 if (proxyCount >= minCountToDumpInterfaces) { 9956 dumpBinderProxyInterfaceCounts(pw, 9957 "Top proxy interface names held by SYSTEM"); 9958 } else { 9959 pw.print("Not dumping proxy interface counts because size (" 9960 + Integer.toString(proxyCount) + ") looks reasonable"); 9961 pw.println(); 9962 } 9963 dumpBinderProxiesCounts(pw, 9964 " Counts of Binder Proxies held by SYSTEM"); 9965 } 9966 9967 @GuardedBy("this") dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep)9968 boolean dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep) { 9969 final int size = mActiveInstrumentation.size(); 9970 if (size > 0) { 9971 boolean printed = false; 9972 for (int i = 0; i < size; i++) { 9973 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 9974 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 9975 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 9976 continue; 9977 } 9978 if (!printed) { 9979 if (needSep) { 9980 pw.println(); 9981 } 9982 pw.println(" Active instrumentation:"); 9983 printed = true; 9984 needSep = true; 9985 } 9986 pw.print(" Instrumentation #"); pw.print(i); pw.print(": "); 9987 pw.println(ai); 9988 ai.dump(pw, " "); 9989 } 9990 } 9991 return needSep; 9992 } 9993 9994 @NeverCompile // Avoid size overhead of debugging code. 9995 @GuardedBy({"this", "mProcLock"}) dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep)9996 void dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, 9997 boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep) { 9998 if (dumpAll || dumpPackage != null) { 9999 final SparseArray<ProcessRecord> pidToProcess = new SparseArray<>(); 10000 synchronized (mPidsSelfLocked) { 10001 boolean printed = false; 10002 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 10003 ProcessRecord r = mPidsSelfLocked.valueAt(i); 10004 pidToProcess.put(r.getPid(), r); 10005 if (dumpPackage != null && !r.getPkgList().containsKey(dumpPackage)) { 10006 continue; 10007 } 10008 if (!printed) { 10009 if (needSep) pw.println(); 10010 needSep = true; 10011 pw.println(" PID mappings:"); 10012 printed = true; 10013 } 10014 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 10015 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 10016 } 10017 } 10018 10019 synchronized (sActiveProcessInfoSelfLocked) { 10020 boolean printed = false; 10021 for (int i = 0, size = sActiveProcessInfoSelfLocked.size(); i < size; i++) { 10022 ProcessInfo info = sActiveProcessInfoSelfLocked.valueAt(i); 10023 ProcessRecord r = pidToProcess.get(sActiveProcessInfoSelfLocked.keyAt(i)); 10024 if (r != null && dumpPackage != null 10025 && !r.getPkgList().containsKey(dumpPackage)) { 10026 continue; 10027 } 10028 if (!printed) { 10029 if (needSep) pw.println(); 10030 needSep = true; 10031 pw.println(" Active process infos:"); 10032 printed = true; 10033 } 10034 pw.print(" Pinfo PID #"); pw.print(sActiveProcessInfoSelfLocked.keyAt(i)); 10035 pw.println(":"); 10036 pw.print(" name="); pw.println(info.name); 10037 if (info.deniedPermissions != null) { 10038 for (int j = 0; j < info.deniedPermissions.size(); j++) { 10039 pw.print(" deny: "); 10040 pw.println(info.deniedPermissions.valueAt(j)); 10041 } 10042 } 10043 } 10044 } 10045 } 10046 10047 if (dumpAll) { 10048 mPhantomProcessList.dump(pw, " "); 10049 } 10050 10051 if (mImportantProcesses.size() > 0) { 10052 synchronized (mPidsSelfLocked) { 10053 boolean printed = false; 10054 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) { 10055 ProcessRecord r = mPidsSelfLocked.get(mImportantProcesses.valueAt(i).pid); 10056 if (dumpPackage != null && (r == null 10057 || !r.getPkgList().containsKey(dumpPackage))) { 10058 continue; 10059 } 10060 if (!printed) { 10061 if (needSep) pw.println(); 10062 needSep = true; 10063 pw.println(" Foreground Processes:"); 10064 printed = true; 10065 } 10066 pw.print(" PID #"); pw.print(mImportantProcesses.keyAt(i)); 10067 pw.print(": "); pw.println(mImportantProcesses.valueAt(i)); 10068 } 10069 } 10070 } 10071 10072 if (mPersistentStartingProcesses.size() > 0) { 10073 if (needSep) pw.println(); 10074 needSep = true; 10075 pw.println(" Persisent processes that are starting:"); 10076 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 10077 "Starting Norm", "Restarting PERS", dumpPackage); 10078 } 10079 10080 if (mProcessList.mRemovedProcesses.size() > 0) { 10081 if (needSep) pw.println(); 10082 needSep = true; 10083 pw.println(" Processes that are being removed:"); 10084 dumpProcessList(pw, this, mProcessList.mRemovedProcesses, " ", 10085 "Removed Norm", "Removed PERS", dumpPackage); 10086 } 10087 10088 if (mProcessesOnHold.size() > 0) { 10089 if (needSep) pw.println(); 10090 needSep = true; 10091 pw.println(" Processes that are on old until the system is ready:"); 10092 dumpProcessList(pw, this, mProcessesOnHold, " ", 10093 "OnHold Norm", "OnHold PERS", dumpPackage); 10094 } 10095 10096 needSep = mAppErrors.dumpLPr(fd, pw, needSep, dumpPackage); 10097 10098 needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep, 10099 mAppProfiler.getTestPssMode(), mWakefulness.get()); 10100 10101 if (dumpAll && mProcessList.mPendingStarts.size() > 0) { 10102 if (needSep) pw.println(); 10103 needSep = true; 10104 pw.println(" mPendingStarts: "); 10105 for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) { 10106 pw.println(" " + mProcessList.mPendingStarts.keyAt(i) + ": " 10107 + mProcessList.mPendingStarts.valueAt(i)); 10108 } 10109 } 10110 if (dumpAll) { 10111 mUidObserverController.dump(pw, dumpPackage); 10112 10113 pw.println(" mDeviceIdleAllowlist=" + Arrays.toString(mDeviceIdleAllowlist)); 10114 pw.println(" mDeviceIdleExceptIdleAllowlist=" 10115 + Arrays.toString(mDeviceIdleExceptIdleAllowlist)); 10116 pw.println(" mDeviceIdleTempAllowlist=" + Arrays.toString(mDeviceIdleTempAllowlist)); 10117 if (mPendingTempAllowlist.size() > 0) { 10118 pw.println(" mPendingTempAllowlist:"); 10119 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) { 10120 PendingTempAllowlist ptw = mPendingTempAllowlist.valueAt(i); 10121 pw.print(" "); 10122 UserHandle.formatUid(pw, ptw.targetUid); 10123 pw.print(": "); 10124 TimeUtils.formatDuration(ptw.duration, pw); 10125 pw.print(" "); 10126 pw.println(ptw.tag); 10127 pw.print(" "); 10128 pw.print(ptw.type); 10129 pw.print(" "); 10130 pw.print(ptw.reasonCode); 10131 pw.print(" "); 10132 pw.print(ptw.callingUid); 10133 } 10134 } 10135 pw.println(" mFgsStartTempAllowList:"); 10136 final long currentTimeNow = System.currentTimeMillis(); 10137 final long elapsedRealtimeNow = SystemClock.elapsedRealtime(); 10138 mFgsStartTempAllowList.forEach((uid, entry) -> { 10139 pw.print(" " + UserHandle.formatUid(uid) + ": "); 10140 entry.second.dump(pw); 10141 pw.print(" expiration="); 10142 // Convert entry.mExpirationTime, which is an elapsed time since boot, 10143 // to a time since epoch (i.e. System.currentTimeMillis()-based time.) 10144 final long expirationInCurrentTime = 10145 currentTimeNow - elapsedRealtimeNow + entry.first; 10146 TimeUtils.dumpTimeWithDelta(pw, expirationInCurrentTime, currentTimeNow); 10147 pw.println(); 10148 }); 10149 10150 if (!mProcessList.mAppsInBackgroundRestricted.isEmpty()) { 10151 pw.println(" Processes that are in background restricted:"); 10152 for (int i = 0, size = mProcessList.mAppsInBackgroundRestricted.size(); 10153 i < size; i++) { 10154 pw.println(String.format("%s #%2d: %s", " ", i, 10155 mProcessList.mAppsInBackgroundRestricted.valueAt(i).toString())); 10156 } 10157 } 10158 } 10159 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 10160 || mOrigWaitForDebugger) { 10161 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 10162 || dumpPackage.equals(mOrigDebugApp)) { 10163 if (needSep) { 10164 pw.println(); 10165 needSep = false; 10166 } 10167 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 10168 + " mDebugTransient=" + mDebugTransient 10169 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 10170 } 10171 } 10172 synchronized (mAppProfiler.mProfilerLock) { 10173 needSep = mAppProfiler.dumpMemWatchProcessesLPf(pw, needSep); 10174 } 10175 if (mTrackAllocationApp != null) { 10176 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 10177 if (needSep) { 10178 pw.println(); 10179 needSep = false; 10180 } 10181 pw.println(" mTrackAllocationApp=" + mTrackAllocationApp); 10182 } 10183 } 10184 needSep = mAppProfiler.dumpProfileDataLocked(pw, dumpPackage, needSep); 10185 if (mNativeDebuggingApp != null) { 10186 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 10187 if (needSep) { 10188 pw.println(); 10189 needSep = false; 10190 } 10191 pw.println(" mNativeDebuggingApp=" + mNativeDebuggingApp); 10192 } 10193 } 10194 if (dumpPackage == null) { 10195 if (mAlwaysFinishActivities) { 10196 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities); 10197 } 10198 if (dumpAll) { 10199 pw.println(" Total persistent processes: " + numPers); 10200 pw.println(" mProcessesReady=" + mProcessesReady 10201 + " mSystemReady=" + mSystemReady 10202 + " mBooted=" + mBooted 10203 + " mFactoryTest=" + mFactoryTest); 10204 pw.println(" mBooting=" + mBooting 10205 + " mCallFinishBooting=" + mCallFinishBooting 10206 + " mBootAnimationComplete=" + mBootAnimationComplete); 10207 pw.print(" mLastPowerCheckUptime="); 10208 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 10209 pw.println(""); 10210 mOomAdjuster.dumpSequenceNumbersLocked(pw); 10211 mOomAdjuster.dumpProcCountsLocked(pw); 10212 mAppProfiler.dumpMemoryLevelsLocked(pw); 10213 long now = SystemClock.uptimeMillis(); 10214 pw.print(" mLastIdleTime="); 10215 TimeUtils.formatDuration(now, mLastIdleTime, pw); 10216 pw.print(" mLowRamSinceLastIdle="); 10217 TimeUtils.formatDuration( 10218 mAppProfiler.getLowRamTimeSinceIdleLPr(now), pw); 10219 pw.println(); 10220 10221 pw.println(); 10222 pw.println(" ServiceManager statistics:"); 10223 ServiceManager.sStatLogger.dump(pw, " "); 10224 pw.println(); 10225 } 10226 } 10227 pw.println(" mForceBackgroundCheck=" + mForceBackgroundCheck); 10228 } 10229 dumpUsers(PrintWriter pw)10230 private void dumpUsers(PrintWriter pw) { 10231 pw.println("ACTIVITY MANAGER USERS (dumpsys activity users)"); 10232 mUserController.dump(pw); 10233 } 10234 10235 @GuardedBy({"this", "mProcLock"}) writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, int dumpAppId, int numPers)10236 void writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, 10237 int dumpAppId, int numPers) { 10238 for (int i = 0, size = mActiveInstrumentation.size(); i < size; i++) { 10239 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 10240 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 10241 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 10242 continue; 10243 } 10244 ai.dumpDebug(proto, 10245 ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS); 10246 } 10247 10248 mUidObserverController.dumpValidateUidsProto(proto, dumpPackage, dumpAppId, 10249 ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS); 10250 10251 if (dumpPackage != null) { 10252 synchronized (mPidsSelfLocked) { 10253 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 10254 ProcessRecord r = mPidsSelfLocked.valueAt(i); 10255 if (!r.getPkgList().containsKey(dumpPackage)) { 10256 continue; 10257 } 10258 r.dumpDebug(proto, 10259 ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED); 10260 } 10261 } 10262 } 10263 10264 if (mImportantProcesses.size() > 0) { 10265 synchronized (mPidsSelfLocked) { 10266 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) { 10267 ImportanceToken it = mImportantProcesses.valueAt(i); 10268 ProcessRecord r = mPidsSelfLocked.get(it.pid); 10269 if (dumpPackage != null && (r == null 10270 || !r.getPkgList().containsKey(dumpPackage))) { 10271 continue; 10272 } 10273 it.dumpDebug(proto, 10274 ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS); 10275 } 10276 } 10277 } 10278 10279 for (int i = 0, size = mPersistentStartingProcesses.size(); i < size; i++) { 10280 ProcessRecord r = mPersistentStartingProcesses.get(i); 10281 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 10282 continue; 10283 } 10284 r.dumpDebug(proto, 10285 ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS); 10286 } 10287 10288 for (int i = 0, size = mProcessList.mRemovedProcesses.size(); i < size; i++) { 10289 ProcessRecord r = mProcessList.mRemovedProcesses.get(i); 10290 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 10291 continue; 10292 } 10293 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS); 10294 } 10295 10296 for (int i = 0, size = mProcessesOnHold.size(); i < size; i++) { 10297 ProcessRecord r = mProcessesOnHold.get(i); 10298 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 10299 continue; 10300 } 10301 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS); 10302 } 10303 10304 synchronized (mAppProfiler.mProfilerLock) { 10305 mAppProfiler.writeProcessesToGcToProto(proto, 10306 ActivityManagerServiceDumpProcessesProto.GC_PROCS, 10307 dumpPackage); 10308 } 10309 mAppErrors.dumpDebugLPr(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS, 10310 dumpPackage); 10311 mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness.get(), 10312 mAppProfiler.getTestPssMode()); 10313 10314 if (dumpPackage == null) { 10315 mUserController.dumpDebug(proto, 10316 ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER); 10317 } 10318 10319 mUidObserverController.dumpDebug(proto, dumpPackage); 10320 10321 for (int v : mDeviceIdleAllowlist) { 10322 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v); 10323 } 10324 10325 for (int v : mDeviceIdleTempAllowlist) { 10326 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v); 10327 } 10328 10329 if (mPendingTempAllowlist.size() > 0) { 10330 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) { 10331 mPendingTempAllowlist.valueAt(i).dumpDebug(proto, 10332 ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST); 10333 } 10334 } 10335 10336 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 10337 || mOrigWaitForDebugger) { 10338 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 10339 || dumpPackage.equals(mOrigDebugApp)) { 10340 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG); 10341 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp); 10342 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp); 10343 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient); 10344 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger); 10345 proto.end(debugAppToken); 10346 } 10347 } 10348 10349 synchronized (mAppProfiler.mProfilerLock) { 10350 mAppProfiler.writeMemWatchProcessToProtoLPf(proto); 10351 } 10352 10353 if (mTrackAllocationApp != null) { 10354 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 10355 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP, 10356 mTrackAllocationApp); 10357 } 10358 } 10359 10360 mAppProfiler.writeProfileDataToProtoLocked(proto, dumpPackage); 10361 10362 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 10363 proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp); 10364 } 10365 10366 if (dumpPackage == null) { 10367 proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities); 10368 proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers); 10369 proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady); 10370 proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady); 10371 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted); 10372 proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest); 10373 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting); 10374 proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting); 10375 proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete); 10376 proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime); 10377 mOomAdjuster.dumpProcessListVariablesLocked(proto); 10378 mAppProfiler.writeMemoryLevelsToProtoLocked(proto); 10379 long now = SystemClock.uptimeMillis(); 10380 ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now); 10381 proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS, 10382 mAppProfiler.getLowRamTimeSinceIdleLPr(now)); 10383 } 10384 } 10385 reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)10386 private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) { 10387 Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj); 10388 if (cnt != null) { 10389 pw.println(" kills at or below oom_adj " + oom_adj + ": " + cnt); 10390 return true; 10391 } 10392 return false; 10393 } 10394 dumpLmkLocked(PrintWriter pw)10395 boolean dumpLmkLocked(PrintWriter pw) { 10396 pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)"); 10397 Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ, 10398 ProcessList.UNKNOWN_ADJ); 10399 if (cnt == null) { 10400 return false; 10401 } 10402 pw.println(" Total number of kills: " + cnt); 10403 10404 return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) && 10405 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) && 10406 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) && 10407 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) && 10408 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) && 10409 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) && 10410 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) && 10411 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) && 10412 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) && 10413 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) && 10414 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) && 10415 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ); 10416 } 10417 10418 public static class ItemMatcher { 10419 ArrayList<ComponentName> components; 10420 ArrayList<String> strings; 10421 ArrayList<Integer> objects; 10422 boolean all; 10423 ItemMatcher()10424 public ItemMatcher() { 10425 all = true; 10426 } 10427 build(String name)10428 public void build(String name) { 10429 ComponentName componentName = ComponentName.unflattenFromString(name); 10430 if (componentName != null) { 10431 if (components == null) { 10432 components = new ArrayList<ComponentName>(); 10433 } 10434 components.add(componentName); 10435 all = false; 10436 } else { 10437 int objectId = 0; 10438 // Not a '/' separated full component name; maybe an object ID? 10439 try { 10440 objectId = Integer.parseInt(name, 16); 10441 if (objects == null) { 10442 objects = new ArrayList<Integer>(); 10443 } 10444 objects.add(objectId); 10445 all = false; 10446 } catch (RuntimeException e) { 10447 // Not an integer; just do string match. 10448 if (strings == null) { 10449 strings = new ArrayList<String>(); 10450 } 10451 strings.add(name); 10452 all = false; 10453 } 10454 } 10455 } 10456 build(String[] args, int opti)10457 public int build(String[] args, int opti) { 10458 for (; opti<args.length; opti++) { 10459 String name = args[opti]; 10460 if ("--".equals(name)) { 10461 return opti+1; 10462 } 10463 build(name); 10464 } 10465 return opti; 10466 } 10467 match(Object object, ComponentName comp)10468 public boolean match(Object object, ComponentName comp) { 10469 if (all) { 10470 return true; 10471 } 10472 if (components != null) { 10473 for (int i=0; i<components.size(); i++) { 10474 if (components.get(i).equals(comp)) { 10475 return true; 10476 } 10477 } 10478 } 10479 if (objects != null) { 10480 for (int i=0; i<objects.size(); i++) { 10481 if (System.identityHashCode(object) == objects.get(i)) { 10482 return true; 10483 } 10484 } 10485 } 10486 if (strings != null) { 10487 String flat = comp.flattenToString(); 10488 for (int i=0; i<strings.size(); i++) { 10489 if (flat.contains(strings.get(i))) { 10490 return true; 10491 } 10492 } 10493 } 10494 return false; 10495 } 10496 } 10497 writeBroadcastsToProtoLocked(ProtoOutputStream proto)10498 void writeBroadcastsToProtoLocked(ProtoOutputStream proto) { 10499 if (mRegisteredReceivers.size() > 0) { 10500 Iterator it = mRegisteredReceivers.values().iterator(); 10501 while (it.hasNext()) { 10502 ReceiverList r = (ReceiverList)it.next(); 10503 r.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST); 10504 } 10505 } 10506 mReceiverResolver.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER); 10507 for (BroadcastQueue q : mBroadcastQueues) { 10508 q.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE); 10509 } 10510 for (int user=0; user<mStickyBroadcasts.size(); user++) { 10511 long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS); 10512 proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user)); 10513 for (Map.Entry<String, ArrayList<Intent>> ent 10514 : mStickyBroadcasts.valueAt(user).entrySet()) { 10515 long actionToken = proto.start(StickyBroadcastProto.ACTIONS); 10516 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey()); 10517 for (Intent intent : ent.getValue()) { 10518 intent.dumpDebug(proto, StickyBroadcastProto.StickyAction.INTENTS, 10519 false, true, true, false); 10520 } 10521 proto.end(actionToken); 10522 } 10523 proto.end(token); 10524 } 10525 10526 long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER); 10527 proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString()); 10528 mHandler.getLooper().dumpDebug(proto, 10529 ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER); 10530 proto.end(handlerToken); 10531 } 10532 dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)10533 void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 10534 int opti, boolean dumpAll, String dumpPackage) { 10535 pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)"); 10536 boolean printed = false; 10537 if (mAllowedAssociations != null) { 10538 for (int i = 0; i < mAllowedAssociations.size(); i++) { 10539 final String pkg = mAllowedAssociations.keyAt(i); 10540 final ArraySet<String> asc = 10541 mAllowedAssociations.valueAt(i).getAllowedPackageAssociations(); 10542 if (!printed) { 10543 pw.println(" Allowed associations (by restricted package):"); 10544 printed = true; 10545 } 10546 pw.print(" * "); 10547 pw.print(pkg); 10548 pw.println(":"); 10549 for (int j = 0; j < asc.size(); j++) { 10550 if (dumpPackage == null || pkg.equals(dumpPackage) 10551 || asc.valueAt(j).equals(dumpPackage)) { 10552 pw.print(" Allow: "); 10553 pw.println(asc.valueAt(j)); 10554 } 10555 } 10556 if (mAllowedAssociations.valueAt(i).isDebuggable()) { 10557 pw.println(" (debuggable)"); 10558 } 10559 } 10560 } 10561 if (!printed) { 10562 pw.println(" (No association restrictions)"); 10563 } 10564 } 10565 dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)10566 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 10567 int opti, boolean dumpAll, String dumpPackage) { 10568 boolean needSep = false; 10569 boolean onlyHistory = false; 10570 boolean printedAnything = false; 10571 10572 if ("history".equals(dumpPackage)) { 10573 if (opti < args.length && "-s".equals(args[opti])) { 10574 dumpAll = false; 10575 } 10576 onlyHistory = true; 10577 dumpPackage = null; 10578 } 10579 10580 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 10581 if (!onlyHistory && dumpAll) { 10582 if (mRegisteredReceivers.size() > 0) { 10583 boolean printed = false; 10584 Iterator it = mRegisteredReceivers.values().iterator(); 10585 while (it.hasNext()) { 10586 ReceiverList r = (ReceiverList)it.next(); 10587 if (dumpPackage != null && (r.app == null || 10588 !dumpPackage.equals(r.app.info.packageName))) { 10589 continue; 10590 } 10591 if (!printed) { 10592 pw.println(" Registered Receivers:"); 10593 needSep = true; 10594 printed = true; 10595 printedAnything = true; 10596 } 10597 pw.print(" * "); pw.println(r); 10598 r.dump(pw, " "); 10599 } 10600 } 10601 10602 if (mReceiverResolver.dump(pw, needSep ? 10603 "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 10604 " ", dumpPackage, false, false)) { 10605 needSep = true; 10606 printedAnything = true; 10607 } 10608 } 10609 10610 for (BroadcastQueue q : mBroadcastQueues) { 10611 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep); 10612 printedAnything |= needSep; 10613 } 10614 10615 needSep = true; 10616 10617 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) { 10618 for (int user=0; user<mStickyBroadcasts.size(); user++) { 10619 if (needSep) { 10620 pw.println(); 10621 } 10622 needSep = true; 10623 printedAnything = true; 10624 pw.print(" Sticky broadcasts for user "); 10625 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":"); 10626 StringBuilder sb = new StringBuilder(128); 10627 for (Map.Entry<String, ArrayList<Intent>> ent 10628 : mStickyBroadcasts.valueAt(user).entrySet()) { 10629 pw.print(" * Sticky action "); pw.print(ent.getKey()); 10630 if (dumpAll) { 10631 pw.println(":"); 10632 ArrayList<Intent> intents = ent.getValue(); 10633 final int N = intents.size(); 10634 for (int i=0; i<N; i++) { 10635 sb.setLength(0); 10636 sb.append(" Intent: "); 10637 intents.get(i).toShortString(sb, false, true, false, false); 10638 pw.println(sb.toString()); 10639 Bundle bundle = intents.get(i).getExtras(); 10640 if (bundle != null) { 10641 pw.print(" "); 10642 pw.println(bundle.toString()); 10643 } 10644 } 10645 } else { 10646 pw.println(""); 10647 } 10648 } 10649 } 10650 } 10651 10652 if (!onlyHistory && dumpAll) { 10653 pw.println(); 10654 for (BroadcastQueue queue : mBroadcastQueues) { 10655 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]=" 10656 + queue.mBroadcastsScheduled); 10657 } 10658 pw.println(" mHandler:"); 10659 mHandler.dump(new PrintWriterPrinter(pw), " "); 10660 needSep = true; 10661 printedAnything = true; 10662 } 10663 10664 if (!printedAnything) { 10665 pw.println(" (nothing)"); 10666 } 10667 } 10668 dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)10669 void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 10670 int opti, boolean dumpAll, String dumpPackage) { 10671 if (mCurBroadcastStats == null) { 10672 return; 10673 } 10674 10675 pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)"); 10676 final long now = SystemClock.elapsedRealtime(); 10677 if (mLastBroadcastStats != null) { 10678 pw.print(" Last stats (from "); 10679 TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw); 10680 pw.print(" to "); 10681 TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw); 10682 pw.print(", "); 10683 TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime 10684 - mLastBroadcastStats.mStartUptime, pw); 10685 pw.println(" uptime):"); 10686 if (!mLastBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 10687 pw.println(" (nothing)"); 10688 } 10689 pw.println(); 10690 } 10691 pw.print(" Current stats (from "); 10692 TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw); 10693 pw.print(" to now, "); 10694 TimeUtils.formatDuration(SystemClock.uptimeMillis() 10695 - mCurBroadcastStats.mStartUptime, pw); 10696 pw.println(" uptime):"); 10697 if (!mCurBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 10698 pw.println(" (nothing)"); 10699 } 10700 } 10701 dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)10702 void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, 10703 int opti, boolean fullCheckin, String dumpPackage) { 10704 if (mCurBroadcastStats == null) { 10705 return; 10706 } 10707 10708 if (mLastBroadcastStats != null) { 10709 mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage); 10710 if (fullCheckin) { 10711 mLastBroadcastStats = null; 10712 return; 10713 } 10714 } 10715 mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage); 10716 if (fullCheckin) { 10717 mCurBroadcastStats = null; 10718 } 10719 } 10720 dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)10721 void dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, 10722 int opti, boolean dumpAll, String dumpPackage) { 10723 10724 pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)"); 10725 10726 mUgmInternal.dump(pw, dumpAll, dumpPackage); 10727 } 10728 dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)10729 private static int dumpProcessList(PrintWriter pw, 10730 ActivityManagerService service, List list, 10731 String prefix, String normalLabel, String persistentLabel, 10732 String dumpPackage) { 10733 int numPers = 0; 10734 for (int i = list.size() - 1; i >= 0; i--) { 10735 ProcessRecord r = (ProcessRecord) list.get(i); 10736 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 10737 continue; 10738 } 10739 pw.println(String.format("%s%s #%2d: %s", 10740 prefix, (r.isPersistent() ? persistentLabel : normalLabel), 10741 i, r.toString())); 10742 if (r.isPersistent()) { 10743 numPers++; 10744 } 10745 } 10746 return numPers; 10747 } 10748 collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)10749 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs, 10750 String[] args) { 10751 synchronized (mProcLock) { 10752 return mProcessList.collectProcessesLOSP(start, allPkgs, args); 10753 } 10754 } 10755 dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)10756 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 10757 PrintWriter pw, String[] args) { 10758 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 10759 if (procs == null) { 10760 pw.println("No process found for: " + args[0]); 10761 return; 10762 } 10763 10764 long uptime = SystemClock.uptimeMillis(); 10765 long realtime = SystemClock.elapsedRealtime(); 10766 pw.println("Applications Graphics Acceleration Info:"); 10767 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 10768 10769 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 10770 ProcessRecord r = procs.get(i); 10771 final int pid = r.getPid(); 10772 final IApplicationThread thread = r.getThread(); 10773 if (thread != null) { 10774 pw.println("\n** Graphics info for pid " + pid + " [" + r.processName + "] **"); 10775 pw.flush(); 10776 try { 10777 TransferPipe tp = new TransferPipe(); 10778 try { 10779 thread.dumpGfxInfo(tp.getWriteFd(), args); 10780 tp.go(fd); 10781 } finally { 10782 tp.kill(); 10783 } 10784 } catch (IOException e) { 10785 pw.println("Failure while dumping the app: " + r); 10786 pw.flush(); 10787 } catch (RemoteException e) { 10788 pw.println("Got a RemoteException while dumping the app " + r); 10789 pw.flush(); 10790 } 10791 } 10792 } 10793 } 10794 dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args)10795 final void dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args) { 10796 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 10797 if (procs == null) { 10798 pw.println("No process found for: " + args[0]); 10799 return; 10800 } 10801 10802 pw.println("Per-process Binder Cache Contents"); 10803 10804 for (int i = procs.size() - 1; i >= 0; i--) { 10805 ProcessRecord r = procs.get(i); 10806 final int pid = r.getPid(); 10807 final IApplicationThread thread = r.getThread(); 10808 if (thread != null) { 10809 pw.println("\n\n** Cache info for pid " + pid + " [" + r.processName + "] **"); 10810 pw.flush(); 10811 try { 10812 TransferPipe tp = new TransferPipe(); 10813 try { 10814 thread.dumpCacheInfo(tp.getWriteFd(), args); 10815 tp.go(fd); 10816 } finally { 10817 tp.kill(); 10818 } 10819 } catch (IOException e) { 10820 pw.println("Failure while dumping the app " + r); 10821 pw.flush(); 10822 } catch (RemoteException e) { 10823 pw.println("Got a RemoteException while dumping the app " + r); 10824 pw.flush(); 10825 } 10826 } 10827 } 10828 } 10829 dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)10830 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 10831 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 10832 if (procs == null) { 10833 pw.println("No process found for: " + args[0]); 10834 return; 10835 } 10836 10837 pw.println("Applications Database Info:"); 10838 10839 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 10840 ProcessRecord r = procs.get(i); 10841 final int pid = r.getPid(); 10842 final IApplicationThread thread = r.getThread(); 10843 if (thread != null) { 10844 pw.println("\n** Database info for pid " + pid + " [" + r.processName + "] **"); 10845 pw.flush(); 10846 try { 10847 TransferPipe tp = new TransferPipe(); 10848 try { 10849 thread.dumpDbInfo(tp.getWriteFd(), args); 10850 tp.go(fd); 10851 } finally { 10852 tp.kill(); 10853 } 10854 } catch (IOException e) { 10855 pw.println("Failure while dumping the app: " + r); 10856 pw.flush(); 10857 } catch (RemoteException e) { 10858 pw.println("Got a RemoteException while dumping the app " + r); 10859 pw.flush(); 10860 } 10861 } 10862 } 10863 } 10864 10865 final static class MemItem { 10866 final boolean isProc; 10867 final String label; 10868 final String shortLabel; 10869 final long pss; 10870 final long swapPss; 10871 final long mRss; 10872 final int id; 10873 final boolean hasActivities; 10874 ArrayList<MemItem> subitems; 10875 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id, boolean hasActivities)10876 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id, 10877 boolean hasActivities) { 10878 this.isProc = true; 10879 this.label = label; 10880 this.shortLabel = shortLabel; 10881 this.pss = pss; 10882 this.swapPss = swapPss; 10883 this.mRss = rss; 10884 this.id = id; 10885 this.hasActivities = hasActivities; 10886 } 10887 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id)10888 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id) { 10889 this.isProc = false; 10890 this.label = label; 10891 this.shortLabel = shortLabel; 10892 this.pss = pss; 10893 this.swapPss = swapPss; 10894 this.mRss = rss; 10895 this.id = id; 10896 this.hasActivities = false; 10897 } 10898 } 10899 sortMemItems(List<MemItem> items, final boolean pss)10900 private static void sortMemItems(List<MemItem> items, final boolean pss) { 10901 Collections.sort(items, new Comparator<MemItem>() { 10902 @Override 10903 public int compare(MemItem lhs, MemItem rhs) { 10904 long lss = pss ? lhs.pss : lhs.mRss; 10905 long rss = pss ? rhs.pss : rhs.mRss; 10906 if (lss < rss) { 10907 return 1; 10908 } else if (lss > rss) { 10909 return -1; 10910 } 10911 return 0; 10912 } 10913 }); 10914 } 10915 dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, boolean dumpSwapPss)10916 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 10917 ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, 10918 boolean dumpSwapPss) { 10919 if (sort && !isCompact) { 10920 sortMemItems(items, dumpPss); 10921 } 10922 10923 for (int i=0; i<items.size(); i++) { 10924 MemItem mi = items.get(i); 10925 if (!isCompact) { 10926 if (dumpPss && dumpSwapPss) { 10927 pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss), 10928 mi.label, stringifyKBSize(mi.swapPss)); 10929 } else { 10930 pw.printf("%s%s: %s\n", prefix, stringifyKBSize(dumpPss ? mi.pss : mi.mRss), 10931 mi.label); 10932 } 10933 } else if (mi.isProc) { 10934 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 10935 pw.print(","); pw.print(mi.id); pw.print(","); 10936 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(","); 10937 pw.print(dumpSwapPss ? mi.swapPss : "N/A"); 10938 pw.println(mi.hasActivities ? ",a" : ",e"); 10939 } else { 10940 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 10941 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(","); 10942 pw.println(dumpSwapPss ? mi.swapPss : "N/A"); 10943 } 10944 if (mi.subitems != null) { 10945 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 10946 true, isCompact, dumpPss, dumpSwapPss); 10947 } 10948 } 10949 } 10950 dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss)10951 static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, 10952 ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss) { 10953 if (sort) { 10954 sortMemItems(items, dumpPss); 10955 } 10956 10957 for (int i=0; i<items.size(); i++) { 10958 MemItem mi = items.get(i); 10959 final long token = proto.start(fieldId); 10960 10961 proto.write(MemInfoDumpProto.MemItem.TAG, tag); 10962 proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel); 10963 proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc); 10964 proto.write(MemInfoDumpProto.MemItem.ID, mi.id); 10965 proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities); 10966 proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss); 10967 proto.write(MemInfoDumpProto.MemItem.RSS_KB, mi.mRss); 10968 if (dumpSwapPss) { 10969 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss); 10970 } 10971 if (mi.subitems != null) { 10972 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems, 10973 true, dumpPss, dumpSwapPss); 10974 } 10975 proto.end(token); 10976 } 10977 } 10978 10979 // These are in KB. 10980 static final long[] DUMP_MEM_BUCKETS = new long[] { 10981 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 10982 120*1024, 160*1024, 200*1024, 10983 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 10984 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 10985 }; 10986 appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)10987 static final void appendMemBucket(StringBuilder out, long memKB, String label, 10988 boolean stackLike) { 10989 int start = label.lastIndexOf('.'); 10990 if (start >= 0) start++; 10991 else start = 0; 10992 int end = label.length(); 10993 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 10994 if (DUMP_MEM_BUCKETS[i] >= memKB) { 10995 long bucket = DUMP_MEM_BUCKETS[i]/1024; 10996 out.append(bucket); 10997 out.append(stackLike ? "MB." : "MB "); 10998 out.append(label, start, end); 10999 return; 11000 } 11001 } 11002 out.append(memKB/1024); 11003 out.append(stackLike ? "MB." : "MB "); 11004 out.append(label, start, end); 11005 } 11006 11007 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 11008 ProcessList.NATIVE_ADJ, 11009 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, 11010 ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ, 11011 ProcessList.VISIBLE_APP_ADJ, 11012 ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ, 11013 ProcessList.PERCEPTIBLE_MEDIUM_APP_ADJ, 11014 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 11015 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 11016 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ 11017 }; 11018 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 11019 "Native", 11020 "System", "Persistent", "Persistent Service", "Foreground", 11021 "Visible", "Perceptible", "Perceptible Low", "Perceptible Medium", 11022 "Backup", "Heavy Weight", 11023 "A Services", "Home", 11024 "Previous", "B Services", "Cached" 11025 }; 11026 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 11027 "native", 11028 "sys", "pers", "persvc", "fore", 11029 "vis", "percept", "perceptl", "perceptm", 11030 "backup", "heavy", 11031 "servicea", "home", 11032 "prev", "serviceb", "cached" 11033 }; 11034 dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)11035 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 11036 long realtime, boolean isCheckinRequest, boolean isCompact) { 11037 if (isCompact) { 11038 pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION); 11039 } 11040 if (isCheckinRequest || isCompact) { 11041 // short checkin version 11042 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 11043 } else { 11044 pw.println("Applications Memory Usage (in Kilobytes):"); 11045 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 11046 } 11047 } 11048 11049 static final int KSM_SHARED = 0; 11050 static final int KSM_SHARING = 1; 11051 static final int KSM_UNSHARED = 2; 11052 static final int KSM_VOLATILE = 3; 11053 getKsmInfo()11054 static final long[] getKsmInfo() { 11055 long[] longOut = new long[4]; 11056 final int[] SINGLE_LONG_FORMAT = new int[] { 11057 PROC_SPACE_TERM| PROC_OUT_LONG 11058 }; 11059 long[] longTmp = new long[1]; 11060 readProcFile("/sys/kernel/mm/ksm/pages_shared", 11061 SINGLE_LONG_FORMAT, null, longTmp, null); 11062 longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 11063 longTmp[0] = 0; 11064 readProcFile("/sys/kernel/mm/ksm/pages_sharing", 11065 SINGLE_LONG_FORMAT, null, longTmp, null); 11066 longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 11067 longTmp[0] = 0; 11068 readProcFile("/sys/kernel/mm/ksm/pages_unshared", 11069 SINGLE_LONG_FORMAT, null, longTmp, null); 11070 longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 11071 longTmp[0] = 0; 11072 readProcFile("/sys/kernel/mm/ksm/pages_volatile", 11073 SINGLE_LONG_FORMAT, null, longTmp, null); 11074 longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 11075 return longOut; 11076 } 11077 stringifySize(long size, int order)11078 static String stringifySize(long size, int order) { 11079 Locale locale = Locale.US; 11080 switch (order) { 11081 case 1: 11082 return String.format(locale, "%,13d", size); 11083 case 1024: 11084 return String.format(locale, "%,9dK", size / 1024); 11085 case 1024 * 1024: 11086 return String.format(locale, "%,5dM", size / 1024 / 1024); 11087 case 1024 * 1024 * 1024: 11088 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024); 11089 default: 11090 throw new IllegalArgumentException("Invalid size order"); 11091 } 11092 } 11093 stringifyKBSize(long size)11094 static String stringifyKBSize(long size) { 11095 return stringifySize(size * 1024, 1024); 11096 } 11097 11098 // Update this version number if you change the 'compact' format. 11099 private static final int MEMINFO_COMPACT_VERSION = 1; 11100 11101 private static class MemoryUsageDumpOptions { 11102 boolean dumpDetails; 11103 boolean dumpFullDetails; 11104 boolean dumpDalvik; 11105 boolean dumpSummaryOnly; 11106 boolean dumpUnreachable; 11107 boolean oomOnly; 11108 boolean isCompact; 11109 boolean localOnly; 11110 boolean packages; 11111 boolean isCheckinRequest; 11112 boolean dumpSwapPss; 11113 boolean dumpProto; 11114 } 11115 11116 @NeverCompile // Avoid size overhead of debugging code. dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)11117 final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 11118 String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) { 11119 MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions(); 11120 opts.dumpDetails = false; 11121 opts.dumpFullDetails = false; 11122 opts.dumpDalvik = false; 11123 opts.dumpSummaryOnly = false; 11124 opts.dumpUnreachable = false; 11125 opts.oomOnly = false; 11126 opts.isCompact = false; 11127 opts.localOnly = false; 11128 opts.packages = false; 11129 opts.isCheckinRequest = false; 11130 opts.dumpSwapPss = false; 11131 opts.dumpProto = asProto; 11132 11133 int opti = 0; 11134 while (opti < args.length) { 11135 String opt = args[opti]; 11136 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11137 break; 11138 } 11139 opti++; 11140 if ("-a".equals(opt)) { 11141 opts.dumpDetails = true; 11142 opts.dumpFullDetails = true; 11143 opts.dumpDalvik = true; 11144 opts.dumpSwapPss = true; 11145 } else if ("-d".equals(opt)) { 11146 opts.dumpDalvik = true; 11147 } else if ("-c".equals(opt)) { 11148 opts.isCompact = true; 11149 } else if ("-s".equals(opt)) { 11150 opts.dumpDetails = true; 11151 opts.dumpSummaryOnly = true; 11152 } else if ("-S".equals(opt)) { 11153 opts.dumpSwapPss = true; 11154 } else if ("--unreachable".equals(opt)) { 11155 opts.dumpUnreachable = true; 11156 } else if ("--oom".equals(opt)) { 11157 opts.oomOnly = true; 11158 } else if ("--local".equals(opt)) { 11159 opts.localOnly = true; 11160 } else if ("--package".equals(opt)) { 11161 opts.packages = true; 11162 } else if ("--checkin".equals(opt)) { 11163 opts.isCheckinRequest = true; 11164 } else if ("--proto".equals(opt)) { 11165 opts.dumpProto = true; 11166 11167 } else if ("-h".equals(opt)) { 11168 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]"); 11169 pw.println(" -a: include all available information for each process."); 11170 pw.println(" -d: include dalvik details."); 11171 pw.println(" -c: dump in a compact machine-parseable representation."); 11172 pw.println(" -s: dump only summary of application memory usage."); 11173 pw.println(" -S: dump also SwapPss."); 11174 pw.println(" --oom: only show processes organized by oom adj."); 11175 pw.println(" --local: only collect details locally, don't call process."); 11176 pw.println(" --package: interpret process arg as package, dumping all"); 11177 pw.println(" processes that have loaded that package."); 11178 pw.println(" --checkin: dump data for a checkin"); 11179 pw.println(" --proto: dump data to proto"); 11180 pw.println("If [process] is specified it can be the name or "); 11181 pw.println("pid of a specific process to dump."); 11182 return; 11183 } else { 11184 pw.println("Unknown argument: " + opt + "; use -h for help"); 11185 } 11186 } 11187 11188 String[] innerArgs = new String[args.length-opti]; 11189 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 11190 11191 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args); 11192 if (opts.dumpProto) { 11193 dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs); 11194 } else { 11195 dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw); 11196 } 11197 } 11198 11199 @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)11200 private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 11201 MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, 11202 ArrayList<ProcessRecord> procs, PrintWriter categoryPw) { 11203 long uptime = SystemClock.uptimeMillis(); 11204 long realtime = SystemClock.elapsedRealtime(); 11205 final long[] tmpLong = new long[3]; 11206 11207 if (procs == null) { 11208 // No Java processes. Maybe they want to print a native process. 11209 String proc = "N/A"; 11210 if (innerArgs.length > 0) { 11211 proc = innerArgs[0]; 11212 if (proc.charAt(0) != '-') { 11213 ArrayList<ProcessCpuTracker.Stats> nativeProcs 11214 = new ArrayList<ProcessCpuTracker.Stats>(); 11215 updateCpuStatsNow(); 11216 int findPid = -1; 11217 try { 11218 findPid = Integer.parseInt(innerArgs[0]); 11219 } catch (NumberFormatException e) { 11220 } 11221 final int fFindPid = findPid; 11222 mAppProfiler.forAllCpuStats((st) -> { 11223 if (st.pid == fFindPid || (st.baseName != null 11224 && st.baseName.equals(innerArgs[0]))) { 11225 nativeProcs.add(st); 11226 } 11227 }); 11228 if (nativeProcs.size() > 0) { 11229 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, 11230 opts.isCheckinRequest, opts.isCompact); 11231 Debug.MemoryInfo mi = null; 11232 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 11233 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 11234 final int pid = r.pid; 11235 if (mi == null) { 11236 mi = new Debug.MemoryInfo(); 11237 } 11238 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 11239 if (!Debug.getMemoryInfo(pid, mi)) { 11240 continue; 11241 } 11242 } else { 11243 long pss = Debug.getPss(pid, tmpLong, null); 11244 if (pss == 0) { 11245 continue; 11246 } 11247 mi.nativePss = (int) pss; 11248 mi.nativePrivateDirty = (int) tmpLong[0]; 11249 mi.nativeRss = (int) tmpLong[2]; 11250 } 11251 if (!opts.isCheckinRequest && opts.dumpDetails) { 11252 pw.println("\n** MEMINFO in pid " + pid + " [" 11253 + r.baseName + "] **"); 11254 } 11255 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, 11256 opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 11257 pid, r.baseName, 0, 0, 0, 0, 0, 0); 11258 if (opts.isCheckinRequest) { 11259 pw.println(); 11260 } 11261 } 11262 return; 11263 } 11264 } 11265 } 11266 pw.println("No process found for: " + proc); 11267 return; 11268 } 11269 11270 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 11271 opts.dumpDetails = true; 11272 } 11273 final int numProcs = procs.size(); 11274 final boolean collectNative = !opts.isCheckinRequest && numProcs > 1 && !opts.packages; 11275 if (collectNative) { 11276 // If we are showing aggregations, also look for native processes to 11277 // include so that our aggregations are more accurate. 11278 updateCpuStatsNow(); 11279 } 11280 11281 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact); 11282 11283 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 11284 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 11285 final long[] ss = new long[INDEX_LAST]; 11286 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11287 EmptyArray.LONG; 11288 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11289 EmptyArray.LONG; 11290 long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11291 EmptyArray.LONG; 11292 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11293 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11294 long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11295 long[] memtrackTmp = new long[4]; 11296 11297 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 11298 long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 11299 long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length]; 11300 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 11301 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 11302 11303 long totalSwapPss = 0; 11304 long totalRss = 0; 11305 long cachedPss = 0; 11306 long cachedSwapPss = 0; 11307 boolean hasSwapPss = false; 11308 11309 Debug.MemoryInfo mi = null; 11310 for (int i = numProcs - 1; i >= 0; i--) { 11311 final ProcessRecord r = procs.get(i); 11312 final IApplicationThread thread; 11313 final int pid; 11314 final int oomAdj; 11315 final boolean hasActivities; 11316 synchronized (mProcLock) { 11317 thread = r.getThread(); 11318 pid = r.getPid(); 11319 oomAdj = r.mState.getSetAdjWithServices(); 11320 hasActivities = r.hasActivities(); 11321 } 11322 if (thread != null) { 11323 if (mi == null) { 11324 mi = new Debug.MemoryInfo(); 11325 } 11326 final int reportType; 11327 final long startTime; 11328 final long endTime; 11329 long memtrackGraphics = 0; 11330 long memtrackGl = 0; 11331 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 11332 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 11333 startTime = SystemClock.currentThreadTimeMillis(); 11334 if (!Debug.getMemoryInfo(pid, mi)) { 11335 continue; 11336 } 11337 endTime = SystemClock.currentThreadTimeMillis(); 11338 hasSwapPss = mi.hasSwappedOutPss; 11339 memtrackGraphics = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS); 11340 memtrackGl = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GL); 11341 } else { 11342 reportType = ProcessStats.ADD_PSS_EXTERNAL; 11343 startTime = SystemClock.currentThreadTimeMillis(); 11344 long pss = Debug.getPss(pid, tmpLong, memtrackTmp); 11345 if (pss == 0) { 11346 continue; 11347 } 11348 mi.dalvikPss = (int) pss; 11349 endTime = SystemClock.currentThreadTimeMillis(); 11350 mi.dalvikPrivateDirty = (int) tmpLong[0]; 11351 mi.dalvikRss = (int) tmpLong[2]; 11352 memtrackGraphics = memtrackTmp[1]; 11353 memtrackGl = memtrackTmp[2]; 11354 } 11355 if (!opts.isCheckinRequest && opts.dumpDetails) { 11356 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 11357 } 11358 if (opts.dumpDetails) { 11359 if (opts.localOnly) { 11360 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails, 11361 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0); 11362 if (opts.isCheckinRequest) { 11363 pw.println(); 11364 } 11365 } else { 11366 pw.flush(); 11367 try { 11368 TransferPipe tp = new TransferPipe(); 11369 try { 11370 thread.dumpMemInfo(tp.getWriteFd(), 11371 mi, opts.isCheckinRequest, opts.dumpFullDetails, 11372 opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs); 11373 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000); 11374 } finally { 11375 tp.kill(); 11376 } 11377 } catch (IOException e) { 11378 if (!opts.isCheckinRequest) { 11379 pw.println("Got IoException! " + e); 11380 pw.flush(); 11381 } 11382 } catch (RemoteException e) { 11383 if (!opts.isCheckinRequest) { 11384 pw.println("Got RemoteException! " + e); 11385 pw.flush(); 11386 } 11387 } 11388 } 11389 } 11390 11391 final long myTotalPss = mi.getTotalPss(); 11392 final long myTotalUss = mi.getTotalUss(); 11393 final long myTotalRss = mi.getTotalRss(); 11394 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 11395 11396 synchronized (mProcLock) { 11397 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) { 11398 // Record this for posterity if the process has been stable. 11399 r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true, 11400 reportType, endTime - startTime); 11401 r.getPkgList().forEachPackageProcessStats(holder -> { 11402 FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED, 11403 r.info.uid, 11404 holder.state.getName(), 11405 holder.state.getPackage(), 11406 myTotalPss, myTotalUss, myTotalRss, reportType, 11407 endTime-startTime, 11408 holder.appVersion, 11409 r.mProfile.getCurrentHostingComponentTypes(), 11410 r.mProfile.getHistoricalHostingComponentTypes()); 11411 }); 11412 } 11413 } 11414 11415 if (!opts.isCheckinRequest && mi != null) { 11416 ss[INDEX_TOTAL_PSS] += myTotalPss; 11417 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 11418 ss[INDEX_TOTAL_RSS] += myTotalRss; 11419 ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics; 11420 ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl; 11421 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 11422 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 11423 myTotalSwapPss, myTotalRss, pid, hasActivities); 11424 procMems.add(pssItem); 11425 procMemsMap.put(pid, pssItem); 11426 11427 ss[INDEX_NATIVE_PSS] += mi.nativePss; 11428 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss; 11429 ss[INDEX_NATIVE_RSS] += mi.nativeRss; 11430 ss[INDEX_DALVIK_PSS] += mi.dalvikPss; 11431 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss; 11432 ss[INDEX_DALVIK_RSS] += mi.dalvikRss; 11433 for (int j=0; j<dalvikSubitemPss.length; j++) { 11434 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 11435 dalvikSubitemSwapPss[j] += 11436 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 11437 dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 11438 } 11439 ss[INDEX_OTHER_PSS] += mi.otherPss; 11440 ss[INDEX_OTHER_RSS] += mi.otherRss; 11441 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss; 11442 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 11443 long mem = mi.getOtherPss(j); 11444 miscPss[j] += mem; 11445 ss[INDEX_OTHER_PSS] -= mem; 11446 mem = mi.getOtherSwappedOutPss(j); 11447 miscSwapPss[j] += mem; 11448 ss[INDEX_OTHER_SWAP_PSS] -= mem; 11449 mem = mi.getOtherRss(j); 11450 miscRss[j] += mem; 11451 ss[INDEX_OTHER_RSS] -= mem; 11452 } 11453 11454 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 11455 cachedPss += myTotalPss; 11456 cachedSwapPss += myTotalSwapPss; 11457 } 11458 11459 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 11460 if (oomIndex == (oomPss.length - 1) 11461 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 11462 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 11463 oomPss[oomIndex] += myTotalPss; 11464 oomSwapPss[oomIndex] += myTotalSwapPss; 11465 if (oomProcs[oomIndex] == null) { 11466 oomProcs[oomIndex] = new ArrayList<MemItem>(); 11467 } 11468 oomProcs[oomIndex].add(pssItem); 11469 oomRss[oomIndex] += myTotalRss; 11470 break; 11471 } 11472 } 11473 } 11474 } 11475 } 11476 11477 long nativeProcTotalPss = 0; 11478 11479 if (collectNative) { 11480 mi = null; 11481 final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1]; 11482 mAppProfiler.forAllCpuStats((st) -> { 11483 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 11484 long memtrackGraphics = 0; 11485 long memtrackGl = 0; 11486 if (memInfos[0] == null) { 11487 memInfos[0] = new Debug.MemoryInfo(); 11488 } 11489 final Debug.MemoryInfo info = memInfos[0]; 11490 if (!brief && !opts.oomOnly) { 11491 if (!Debug.getMemoryInfo(st.pid, info)) { 11492 return; 11493 } 11494 memtrackGraphics = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS); 11495 memtrackGl = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GL); 11496 } else { 11497 long pss = Debug.getPss(st.pid, tmpLong, memtrackTmp); 11498 if (pss == 0) { 11499 return; 11500 } 11501 info.nativePss = (int) pss; 11502 info.nativePrivateDirty = (int) tmpLong[0]; 11503 info.nativeRss = (int) tmpLong[2]; 11504 memtrackGraphics = memtrackTmp[1]; 11505 memtrackGl = memtrackTmp[2]; 11506 } 11507 11508 final long myTotalPss = info.getTotalPss(); 11509 final long myTotalSwapPss = info.getTotalSwappedOutPss(); 11510 final long myTotalRss = info.getTotalRss(); 11511 ss[INDEX_TOTAL_PSS] += myTotalPss; 11512 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 11513 ss[INDEX_TOTAL_RSS] += myTotalRss; 11514 ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss; 11515 ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics; 11516 ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl; 11517 11518 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 11519 st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss, 11520 st.pid, false); 11521 procMems.add(pssItem); 11522 11523 ss[INDEX_NATIVE_PSS] += info.nativePss; 11524 ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss; 11525 ss[INDEX_NATIVE_RSS] += info.nativeRss; 11526 ss[INDEX_DALVIK_PSS] += info.dalvikPss; 11527 ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss; 11528 ss[INDEX_DALVIK_RSS] += info.dalvikRss; 11529 for (int j = 0; j < dalvikSubitemPss.length; j++) { 11530 dalvikSubitemPss[j] += info.getOtherPss( 11531 Debug.MemoryInfo.NUM_OTHER_STATS + j); 11532 dalvikSubitemSwapPss[j] += 11533 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 11534 dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS 11535 + j); 11536 } 11537 ss[INDEX_OTHER_PSS] += info.otherPss; 11538 ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss; 11539 ss[INDEX_OTHER_RSS] += info.otherRss; 11540 for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 11541 long mem = info.getOtherPss(j); 11542 miscPss[j] += mem; 11543 ss[INDEX_OTHER_PSS] -= mem; 11544 mem = info.getOtherSwappedOutPss(j); 11545 miscSwapPss[j] += mem; 11546 ss[INDEX_OTHER_SWAP_PSS] -= mem; 11547 mem = info.getOtherRss(j); 11548 miscRss[j] += mem; 11549 ss[INDEX_OTHER_RSS] -= mem; 11550 } 11551 oomPss[0] += myTotalPss; 11552 oomSwapPss[0] += myTotalSwapPss; 11553 if (oomProcs[0] == null) { 11554 oomProcs[0] = new ArrayList<MemItem>(); 11555 } 11556 oomProcs[0].add(pssItem); 11557 oomRss[0] += myTotalRss; 11558 } 11559 }); 11560 11561 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 11562 11563 catMems.add(new MemItem("Native", "Native", 11564 ss[INDEX_NATIVE_PSS], ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1)); 11565 final int dalvikId = -2; 11566 catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS], 11567 ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId)); 11568 catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS], 11569 ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3)); 11570 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 11571 String label = Debug.MemoryInfo.getOtherLabel(j); 11572 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], j)); 11573 } 11574 if (dalvikSubitemPss.length > 0) { 11575 // Add dalvik subitems. 11576 for (MemItem memItem : catMems) { 11577 int memItemStart = 0, memItemEnd = 0; 11578 if (memItem.id == dalvikId) { 11579 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 11580 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 11581 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 11582 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 11583 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 11584 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 11585 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 11586 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 11587 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 11588 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 11589 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 11590 } else { 11591 continue; // No subitems, continue. 11592 } 11593 memItem.subitems = new ArrayList<MemItem>(); 11594 for (int j=memItemStart; j<=memItemEnd; j++) { 11595 final String name = Debug.MemoryInfo.getOtherLabel( 11596 Debug.MemoryInfo.NUM_OTHER_STATS + j); 11597 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 11598 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j)); 11599 } 11600 } 11601 } 11602 11603 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 11604 for (int j=0; j<oomPss.length; j++) { 11605 if (oomPss[j] != 0) { 11606 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 11607 : DUMP_MEM_OOM_LABEL[j]; 11608 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j], 11609 DUMP_MEM_OOM_ADJ[j]); 11610 item.subitems = oomProcs[j]; 11611 oomMems.add(item); 11612 } 11613 } 11614 if (!opts.isCompact) { 11615 pw.println(); 11616 } 11617 if (!brief && !opts.oomOnly && !opts.isCompact) { 11618 pw.println(); 11619 pw.println("Total RSS by process:"); 11620 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, false, false); 11621 pw.println(); 11622 } 11623 if (!opts.isCompact) { 11624 pw.println("Total RSS by OOM adjustment:"); 11625 } 11626 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, false, false); 11627 if (!brief && !opts.oomOnly) { 11628 PrintWriter out = categoryPw != null ? categoryPw : pw; 11629 if (!opts.isCompact) { 11630 out.println(); 11631 out.println("Total RSS by category:"); 11632 } 11633 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, false, false); 11634 } 11635 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0; 11636 if (!brief && !opts.oomOnly && !opts.isCompact) { 11637 pw.println(); 11638 pw.println("Total PSS by process:"); 11639 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, true, 11640 opts.dumpSwapPss); 11641 pw.println(); 11642 } 11643 if (!opts.isCompact) { 11644 pw.println("Total PSS by OOM adjustment:"); 11645 } 11646 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, true, opts.dumpSwapPss); 11647 if (!brief && !opts.oomOnly) { 11648 PrintWriter out = categoryPw != null ? categoryPw : pw; 11649 if (!opts.isCompact) { 11650 out.println(); 11651 out.println("Total PSS by category:"); 11652 } 11653 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, true, 11654 opts.dumpSwapPss); 11655 } 11656 if (!opts.isCompact) { 11657 pw.println(); 11658 } 11659 MemInfoReader memInfo = new MemInfoReader(); 11660 memInfo.readMemInfo(); 11661 if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) { 11662 synchronized (mProcessStats.mLock) { 11663 final long cachedKb = memInfo.getCachedSizeKb(); 11664 final long freeKb = memInfo.getFreeSizeKb(); 11665 final long zramKb = memInfo.getZramTotalSizeKb(); 11666 final long kernelKb = memInfo.getKernelUsedSizeKb(); 11667 EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, 11668 kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024); 11669 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 11670 ss[INDEX_TOTAL_NATIVE_PSS]); 11671 } 11672 } 11673 if (!brief) { 11674 if (!opts.isCompact) { 11675 pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb())); 11676 pw.print(" (status "); 11677 mAppProfiler.dumpLastMemoryLevelLocked(pw); 11678 pw.print(" Free RAM: "); 11679 pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb() 11680 + memInfo.getFreeSizeKb())); 11681 pw.print(" ("); 11682 pw.print(stringifyKBSize(cachedPss)); 11683 pw.print(" cached pss + "); 11684 pw.print(stringifyKBSize(memInfo.getCachedSizeKb())); 11685 pw.print(" cached kernel + "); 11686 pw.print(stringifyKBSize(memInfo.getFreeSizeKb())); 11687 pw.println(" free)"); 11688 } else { 11689 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 11690 pw.print(cachedPss + memInfo.getCachedSizeKb() 11691 + memInfo.getFreeSizeKb()); pw.print(","); 11692 pw.println(ss[INDEX_TOTAL_PSS] - cachedPss); 11693 } 11694 } 11695 long kernelUsed = memInfo.getKernelUsedSizeKb(); 11696 final long ionHeap = Debug.getIonHeapsSizeKb(); 11697 final long ionPool = Debug.getIonPoolsSizeKb(); 11698 final long dmabufMapped = Debug.getDmabufMappedSizeKb(); 11699 if (ionHeap >= 0 && ionPool >= 0) { 11700 final long ionUnmapped = ionHeap - dmabufMapped; 11701 pw.print(" ION: "); 11702 pw.print(stringifyKBSize(ionHeap + ionPool)); 11703 pw.print(" ("); 11704 pw.print(stringifyKBSize(dmabufMapped)); 11705 pw.print(" mapped + "); 11706 pw.print(stringifyKBSize(ionUnmapped)); 11707 pw.print(" unmapped + "); 11708 pw.print(stringifyKBSize(ionPool)); 11709 pw.println(" pools)"); 11710 kernelUsed += ionUnmapped; 11711 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being 11712 // set on ION VMAs, however it might be included by the memtrack HAL. 11713 // Replace memtrack HAL reported Graphics category with mapped dmabufs 11714 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS]; 11715 ss[INDEX_TOTAL_PSS] += dmabufMapped; 11716 } else { 11717 final long totalExportedDmabuf = Debug.getDmabufTotalExportedKb(); 11718 if (totalExportedDmabuf >= 0) { 11719 final long dmabufUnmapped = totalExportedDmabuf - dmabufMapped; 11720 pw.print("DMA-BUF: "); 11721 pw.print(stringifyKBSize(totalExportedDmabuf)); 11722 pw.print(" ("); 11723 pw.print(stringifyKBSize(dmabufMapped)); 11724 pw.print(" mapped + "); 11725 pw.print(stringifyKBSize(dmabufUnmapped)); 11726 pw.println(" unmapped)"); 11727 // Account unmapped dmabufs as part of kernel memory allocations 11728 kernelUsed += dmabufUnmapped; 11729 // Replace memtrack HAL reported Graphics category with mapped dmabufs 11730 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS]; 11731 ss[INDEX_TOTAL_PSS] += dmabufMapped; 11732 } 11733 11734 // totalDmabufHeapExported is included in totalExportedDmabuf above and hence do not 11735 // need to be added to kernelUsed. 11736 final long totalDmabufHeapExported = Debug.getDmabufHeapTotalExportedKb(); 11737 if (totalDmabufHeapExported >= 0) { 11738 pw.print("DMA-BUF Heaps: "); 11739 pw.println(stringifyKBSize(totalDmabufHeapExported)); 11740 } 11741 11742 final long totalDmabufHeapPool = Debug.getDmabufHeapPoolsSizeKb(); 11743 if (totalDmabufHeapPool >= 0) { 11744 pw.print("DMA-BUF Heaps pool: "); 11745 pw.println(stringifyKBSize(totalDmabufHeapPool)); 11746 } 11747 } 11748 final long gpuUsage = Debug.getGpuTotalUsageKb(); 11749 if (gpuUsage >= 0) { 11750 final long gpuPrivateUsage = Debug.getGpuPrivateMemoryKb(); 11751 if (gpuPrivateUsage >= 0) { 11752 final long gpuDmaBufUsage = gpuUsage - gpuPrivateUsage; 11753 pw.print(" GPU: "); 11754 pw.print(stringifyKBSize(gpuUsage)); 11755 pw.print(" ("); 11756 pw.print(stringifyKBSize(gpuDmaBufUsage)); 11757 pw.print(" dmabuf + "); 11758 pw.print(stringifyKBSize(gpuPrivateUsage)); 11759 pw.println(" private)"); 11760 // Replace memtrack HAL reported GL category with private GPU allocations and 11761 // account it as part of kernel memory allocations 11762 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GL]; 11763 kernelUsed += gpuPrivateUsage; 11764 } else { 11765 pw.print(" GPU: "); pw.println(stringifyKBSize(gpuUsage)); 11766 } 11767 } 11768 11769 // Note: ION/DMA-BUF heap pools are reclaimable and hence, they are included as part of 11770 // memInfo.getCachedSizeKb(). 11771 final long lostRAM = memInfo.getTotalSizeKb() 11772 - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS]) 11773 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 11774 - kernelUsed - memInfo.getZramTotalSizeKb(); 11775 if (!opts.isCompact) { 11776 pw.print(" Used RAM: "); pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss 11777 + kernelUsed)); pw.print(" ("); 11778 pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss)); pw.print(" used pss + "); 11779 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n"); 11780 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM)); 11781 } else { 11782 pw.print("lostram,"); pw.println(lostRAM); 11783 } 11784 if (!brief) { 11785 if (memInfo.getZramTotalSizeKb() != 0) { 11786 if (!opts.isCompact) { 11787 pw.print(" ZRAM: "); 11788 pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb())); 11789 pw.print(" physical used for "); 11790 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb() 11791 - memInfo.getSwapFreeSizeKb())); 11792 pw.print(" in swap ("); 11793 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb())); 11794 pw.println(" total swap)"); 11795 } else { 11796 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 11797 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 11798 pw.println(memInfo.getSwapFreeSizeKb()); 11799 } 11800 } 11801 final long[] ksm = getKsmInfo(); 11802 if (!opts.isCompact) { 11803 if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 11804 || ksm[KSM_VOLATILE] != 0) { 11805 pw.print(" KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING])); 11806 pw.print(" saved from shared "); 11807 pw.print(stringifyKBSize(ksm[KSM_SHARED])); 11808 pw.print(" "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED])); 11809 pw.print(" unshared; "); 11810 pw.print(stringifyKBSize( 11811 ksm[KSM_VOLATILE])); pw.println(" volatile"); 11812 } 11813 pw.print(" Tuning: "); 11814 pw.print(ActivityManager.staticGetMemoryClass()); 11815 pw.print(" (large "); 11816 pw.print(ActivityManager.staticGetLargeMemoryClass()); 11817 pw.print("), oom "); 11818 pw.print(stringifySize( 11819 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024)); 11820 pw.print(", restore limit "); 11821 pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb())); 11822 if (ActivityManager.isLowRamDeviceStatic()) { 11823 pw.print(" (low-ram)"); 11824 } 11825 if (ActivityManager.isHighEndGfx()) { 11826 pw.print(" (high-end-gfx)"); 11827 } 11828 pw.println(); 11829 } else { 11830 pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(","); 11831 pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]); 11832 pw.print(","); pw.println(ksm[KSM_VOLATILE]); 11833 pw.print("tuning,"); 11834 pw.print(ActivityManager.staticGetMemoryClass()); 11835 pw.print(','); 11836 pw.print(ActivityManager.staticGetLargeMemoryClass()); 11837 pw.print(','); 11838 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 11839 if (ActivityManager.isLowRamDeviceStatic()) { 11840 pw.print(",low-ram"); 11841 } 11842 if (ActivityManager.isHighEndGfx()) { 11843 pw.print(",high-end-gfx"); 11844 } 11845 pw.println(); 11846 } 11847 } 11848 } 11849 } 11850 11851 @NeverCompile // Avoid size overhead of debugging code. dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)11852 private final void dumpApplicationMemoryUsage(FileDescriptor fd, 11853 MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, 11854 ArrayList<ProcessRecord> procs) { 11855 final long uptimeMs = SystemClock.uptimeMillis(); 11856 final long realtimeMs = SystemClock.elapsedRealtime(); 11857 final long[] tmpLong = new long[3]; 11858 11859 if (procs == null) { 11860 // No Java processes. Maybe they want to print a native process. 11861 String proc = "N/A"; 11862 if (innerArgs.length > 0) { 11863 proc = innerArgs[0]; 11864 if (proc.charAt(0) != '-') { 11865 final ArrayList<ProcessCpuTracker.Stats> nativeProcs 11866 = new ArrayList<ProcessCpuTracker.Stats>(); 11867 updateCpuStatsNow(); 11868 int findPid = -1; 11869 try { 11870 findPid = Integer.parseInt(innerArgs[0]); 11871 } catch (NumberFormatException e) { 11872 } 11873 final int fFindPid = findPid; 11874 mAppProfiler.forAllCpuStats((st) -> { 11875 if (st.pid == fFindPid || (st.baseName != null 11876 && st.baseName.equals(innerArgs[0]))) { 11877 nativeProcs.add(st); 11878 } 11879 }); 11880 if (nativeProcs.size() > 0) { 11881 ProtoOutputStream proto = new ProtoOutputStream(fd); 11882 11883 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 11884 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 11885 Debug.MemoryInfo mi = null; 11886 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 11887 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 11888 final int pid = r.pid; 11889 11890 if (mi == null) { 11891 mi = new Debug.MemoryInfo(); 11892 } 11893 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 11894 if (!Debug.getMemoryInfo(pid, mi)) { 11895 continue; 11896 } 11897 } else { 11898 long pss = Debug.getPss(pid, tmpLong, null); 11899 if (pss == 0) { 11900 continue; 11901 } 11902 mi.nativePss = (int) pss; 11903 mi.nativePrivateDirty = (int) tmpLong[0]; 11904 mi.nativeRss = (int) tmpLong[2]; 11905 } 11906 11907 final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES); 11908 11909 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 11910 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName); 11911 11912 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 11913 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 11914 11915 proto.end(nToken); 11916 } 11917 11918 proto.flush(); 11919 return; 11920 } 11921 } 11922 } 11923 Log.d(TAG, "No process found for: " + innerArgs[0]); 11924 return; 11925 } 11926 11927 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 11928 opts.dumpDetails = true; 11929 } 11930 final int numProcs = procs.size(); 11931 final boolean collectNative = numProcs > 1 && !opts.packages; 11932 if (collectNative) { 11933 // If we are showing aggregations, also look for native processes to 11934 // include so that our aggregations are more accurate. 11935 updateCpuStatsNow(); 11936 } 11937 11938 ProtoOutputStream proto = new ProtoOutputStream(fd); 11939 11940 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 11941 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 11942 11943 final ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 11944 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 11945 final long[] ss = new long[INDEX_LAST]; 11946 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11947 EmptyArray.LONG; 11948 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11949 EmptyArray.LONG; 11950 long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11951 EmptyArray.LONG; 11952 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11953 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11954 long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11955 11956 final long[] oomPss = new long[DUMP_MEM_OOM_LABEL.length]; 11957 final long[] oomSwapPss = new long[DUMP_MEM_OOM_LABEL.length]; 11958 final long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length]; 11959 final ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 11960 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 11961 11962 long cachedPss = 0; 11963 long cachedSwapPss = 0; 11964 boolean hasSwapPss = false; 11965 11966 Debug.MemoryInfo mi = null; 11967 for (int i = numProcs - 1; i >= 0; i--) { 11968 final ProcessRecord r = procs.get(i); 11969 final IApplicationThread thread; 11970 final int pid; 11971 final int oomAdj; 11972 final boolean hasActivities; 11973 synchronized (mProcLock) { 11974 thread = r.getThread(); 11975 pid = r.getPid(); 11976 oomAdj = r.mState.getSetAdjWithServices(); 11977 hasActivities = r.hasActivities(); 11978 } 11979 if (thread == null) { 11980 continue; 11981 } 11982 if (mi == null) { 11983 mi = new Debug.MemoryInfo(); 11984 } 11985 final int reportType; 11986 final long startTime; 11987 final long endTime; 11988 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 11989 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 11990 startTime = SystemClock.currentThreadTimeMillis(); 11991 if (!Debug.getMemoryInfo(pid, mi)) { 11992 continue; 11993 } 11994 endTime = SystemClock.currentThreadTimeMillis(); 11995 hasSwapPss = mi.hasSwappedOutPss; 11996 } else { 11997 reportType = ProcessStats.ADD_PSS_EXTERNAL; 11998 startTime = SystemClock.currentThreadTimeMillis(); 11999 long pss = Debug.getPss(pid, tmpLong, null); 12000 if (pss == 0) { 12001 continue; 12002 } 12003 mi.dalvikPss = (int) pss; 12004 endTime = SystemClock.currentThreadTimeMillis(); 12005 mi.dalvikPrivateDirty = (int) tmpLong[0]; 12006 mi.dalvikRss = (int) tmpLong[2]; 12007 } 12008 if (opts.dumpDetails) { 12009 if (opts.localOnly) { 12010 final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES); 12011 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY); 12012 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 12013 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName); 12014 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 12015 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 12016 proto.end(mToken); 12017 proto.end(aToken); 12018 } else { 12019 try { 12020 ByteTransferPipe tp = new ByteTransferPipe(); 12021 try { 12022 thread.dumpMemInfoProto(tp.getWriteFd(), 12023 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 12024 opts.dumpUnreachable, innerArgs); 12025 proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get()); 12026 } finally { 12027 tp.kill(); 12028 } 12029 } catch (IOException e) { 12030 Log.e(TAG, "Got IOException!", e); 12031 } catch (RemoteException e) { 12032 Log.e(TAG, "Got RemoteException!", e); 12033 } 12034 } 12035 } 12036 12037 final long myTotalPss = mi.getTotalPss(); 12038 final long myTotalUss = mi.getTotalUss(); 12039 final long myTotalRss = mi.getTotalRss(); 12040 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 12041 12042 synchronized (mProcLock) { 12043 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) { 12044 // Record this for posterity if the process has been stable. 12045 r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true, 12046 reportType, endTime - startTime); 12047 r.getPkgList().forEachPackageProcessStats(holder -> { 12048 FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED, 12049 r.info.uid, 12050 holder.state.getName(), 12051 holder.state.getPackage(), 12052 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime, 12053 holder.appVersion, 12054 r.mProfile.getCurrentHostingComponentTypes(), 12055 r.mProfile.getHistoricalHostingComponentTypes()); 12056 }); 12057 } 12058 } 12059 12060 if (!opts.isCheckinRequest && mi != null) { 12061 ss[INDEX_TOTAL_PSS] += myTotalPss; 12062 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 12063 ss[INDEX_TOTAL_RSS] += myTotalRss; 12064 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 12065 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 12066 myTotalSwapPss, myTotalRss, pid, hasActivities); 12067 procMems.add(pssItem); 12068 procMemsMap.put(pid, pssItem); 12069 12070 ss[INDEX_NATIVE_PSS] += mi.nativePss; 12071 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss; 12072 ss[INDEX_NATIVE_RSS] += mi.nativeRss; 12073 ss[INDEX_DALVIK_PSS] += mi.dalvikPss; 12074 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss; 12075 ss[INDEX_DALVIK_RSS] += mi.dalvikRss; 12076 for (int j=0; j<dalvikSubitemPss.length; j++) { 12077 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12078 dalvikSubitemSwapPss[j] += 12079 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12080 dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12081 } 12082 ss[INDEX_OTHER_PSS] += mi.otherPss; 12083 ss[INDEX_OTHER_RSS] += mi.otherRss; 12084 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss; 12085 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12086 long mem = mi.getOtherPss(j); 12087 miscPss[j] += mem; 12088 ss[INDEX_OTHER_PSS] -= mem; 12089 mem = mi.getOtherSwappedOutPss(j); 12090 miscSwapPss[j] += mem; 12091 ss[INDEX_OTHER_SWAP_PSS] -= mem; 12092 mem = mi.getOtherRss(j); 12093 miscRss[j] += mem; 12094 ss[INDEX_OTHER_RSS] -= mem; 12095 } 12096 12097 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 12098 cachedPss += myTotalPss; 12099 cachedSwapPss += myTotalSwapPss; 12100 } 12101 12102 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 12103 if (oomIndex == (oomPss.length - 1) 12104 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 12105 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 12106 oomPss[oomIndex] += myTotalPss; 12107 oomSwapPss[oomIndex] += myTotalSwapPss; 12108 if (oomProcs[oomIndex] == null) { 12109 oomProcs[oomIndex] = new ArrayList<MemItem>(); 12110 } 12111 oomProcs[oomIndex].add(pssItem); 12112 oomRss[oomIndex] += myTotalRss; 12113 break; 12114 } 12115 } 12116 } 12117 } 12118 12119 long nativeProcTotalPss = 0; 12120 12121 if (collectNative) { 12122 mi = null; 12123 final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1]; 12124 mAppProfiler.forAllCpuStats((st) -> { 12125 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 12126 if (memInfos[0] == null) { 12127 memInfos[0] = new Debug.MemoryInfo(); 12128 } 12129 final Debug.MemoryInfo info = memInfos[0]; 12130 if (!brief && !opts.oomOnly) { 12131 if (!Debug.getMemoryInfo(st.pid, info)) { 12132 return; 12133 } 12134 } else { 12135 long pss = Debug.getPss(st.pid, tmpLong, null); 12136 if (pss == 0) { 12137 return; 12138 } 12139 info.nativePss = (int) pss; 12140 info.nativePrivateDirty = (int) tmpLong[0]; 12141 info.nativeRss = (int) tmpLong[2]; 12142 } 12143 12144 final long myTotalPss = info.getTotalPss(); 12145 final long myTotalSwapPss = info.getTotalSwappedOutPss(); 12146 final long myTotalRss = info.getTotalRss(); 12147 ss[INDEX_TOTAL_PSS] += myTotalPss; 12148 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 12149 ss[INDEX_TOTAL_RSS] += myTotalRss; 12150 ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss; 12151 12152 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 12153 st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss, 12154 st.pid, false); 12155 procMems.add(pssItem); 12156 12157 ss[INDEX_NATIVE_PSS] += info.nativePss; 12158 ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss; 12159 ss[INDEX_NATIVE_RSS] += info.nativeRss; 12160 ss[INDEX_DALVIK_PSS] += info.dalvikPss; 12161 ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss; 12162 ss[INDEX_DALVIK_RSS] += info.dalvikRss; 12163 for (int j = 0; j < dalvikSubitemPss.length; j++) { 12164 dalvikSubitemPss[j] += info.getOtherPss( 12165 Debug.MemoryInfo.NUM_OTHER_STATS + j); 12166 dalvikSubitemSwapPss[j] += 12167 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 12168 dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS 12169 + j); 12170 } 12171 ss[INDEX_OTHER_PSS] += info.otherPss; 12172 ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss; 12173 ss[INDEX_OTHER_RSS] += info.otherRss; 12174 for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12175 long mem = info.getOtherPss(j); 12176 miscPss[j] += mem; 12177 ss[INDEX_OTHER_PSS] -= mem; 12178 mem = info.getOtherSwappedOutPss(j); 12179 miscSwapPss[j] += mem; 12180 ss[INDEX_OTHER_SWAP_PSS] -= mem; 12181 mem = info.getOtherRss(j); 12182 miscRss[j] += mem; 12183 ss[INDEX_OTHER_RSS] -= mem; 12184 } 12185 oomPss[0] += myTotalPss; 12186 oomSwapPss[0] += myTotalSwapPss; 12187 if (oomProcs[0] == null) { 12188 oomProcs[0] = new ArrayList<MemItem>(); 12189 } 12190 oomProcs[0].add(pssItem); 12191 oomRss[0] += myTotalRss; 12192 } 12193 }); 12194 12195 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 12196 12197 catMems.add(new MemItem("Native", "Native", ss[INDEX_NATIVE_PSS], 12198 ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1)); 12199 final int dalvikId = -2; 12200 catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS], 12201 ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId)); 12202 catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS], 12203 ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3)); 12204 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 12205 String label = Debug.MemoryInfo.getOtherLabel(j); 12206 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], j)); 12207 } 12208 if (dalvikSubitemPss.length > 0) { 12209 // Add dalvik subitems. 12210 for (MemItem memItem : catMems) { 12211 int memItemStart = 0, memItemEnd = 0; 12212 if (memItem.id == dalvikId) { 12213 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 12214 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 12215 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 12216 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 12217 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 12218 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 12219 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 12220 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 12221 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 12222 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 12223 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 12224 } else { 12225 continue; // No subitems, continue. 12226 } 12227 memItem.subitems = new ArrayList<MemItem>(); 12228 for (int j=memItemStart; j<=memItemEnd; j++) { 12229 final String name = Debug.MemoryInfo.getOtherLabel( 12230 Debug.MemoryInfo.NUM_OTHER_STATS + j); 12231 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 12232 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j)); 12233 } 12234 } 12235 } 12236 12237 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 12238 for (int j=0; j<oomPss.length; j++) { 12239 if (oomPss[j] != 0) { 12240 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 12241 : DUMP_MEM_OOM_LABEL[j]; 12242 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j], 12243 DUMP_MEM_OOM_ADJ[j]); 12244 item.subitems = oomProcs[j]; 12245 oomMems.add(item); 12246 } 12247 } 12248 12249 if (!opts.oomOnly) { 12250 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_PROCESS, "proc", 12251 procMems, true, false, false); 12252 } 12253 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_OOM_ADJUSTMENT, "oom", 12254 oomMems, false, false, false); 12255 if (!brief && !opts.oomOnly) { 12256 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_CATEGORY, "cat", 12257 catMems, true, false, false); 12258 } 12259 12260 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0; 12261 if (!opts.oomOnly) { 12262 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc", 12263 procMems, true, true, opts.dumpSwapPss); 12264 } 12265 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom", 12266 oomMems, false, true, opts.dumpSwapPss); 12267 if (!brief && !opts.oomOnly) { 12268 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat", 12269 catMems, true, true, opts.dumpSwapPss); 12270 } 12271 MemInfoReader memInfo = new MemInfoReader(); 12272 memInfo.readMemInfo(); 12273 if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) { 12274 synchronized (mProcessStats.mLock) { 12275 final long cachedKb = memInfo.getCachedSizeKb(); 12276 final long freeKb = memInfo.getFreeSizeKb(); 12277 final long zramKb = memInfo.getZramTotalSizeKb(); 12278 final long kernelKb = memInfo.getKernelUsedSizeKb(); 12279 EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, 12280 kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024); 12281 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 12282 ss[INDEX_TOTAL_NATIVE_PSS]); 12283 } 12284 } 12285 if (!brief) { 12286 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb()); 12287 proto.write(MemInfoDumpProto.STATUS, mAppProfiler.getLastMemoryLevelLocked()); 12288 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss); 12289 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb()); 12290 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb()); 12291 } 12292 long lostRAM = memInfo.getTotalSizeKb() 12293 - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS]) 12294 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 12295 - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb(); 12296 proto.write(MemInfoDumpProto.USED_PSS_KB, ss[INDEX_TOTAL_PSS] - cachedPss); 12297 proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb()); 12298 proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM); 12299 if (!brief) { 12300 if (memInfo.getZramTotalSizeKb() != 0) { 12301 proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb()); 12302 proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB, 12303 memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb()); 12304 proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb()); 12305 } 12306 final long[] ksm = getKsmInfo(); 12307 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]); 12308 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]); 12309 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]); 12310 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]); 12311 12312 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass()); 12313 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass()); 12314 proto.write(MemInfoDumpProto.OOM_KB, 12315 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024); 12316 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB, 12317 mProcessList.getCachedRestoreThresholdKb()); 12318 12319 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic()); 12320 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx()); 12321 } 12322 } 12323 12324 proto.flush(); 12325 } 12326 appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)12327 static void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, 12328 long memtrack, String name) { 12329 sb.append(" "); 12330 sb.append(ProcessList.makeOomAdjString(oomAdj, false)); 12331 sb.append(' '); 12332 sb.append(ProcessList.makeProcStateString(procState)); 12333 sb.append(' '); 12334 ProcessList.appendRamKb(sb, pss); 12335 sb.append(": "); 12336 sb.append(name); 12337 if (memtrack > 0) { 12338 sb.append(" ("); 12339 sb.append(stringifyKBSize(memtrack)); 12340 sb.append(" memtrack)"); 12341 } 12342 } 12343 appendMemInfo(StringBuilder sb, ProcessMemInfo mi)12344 static void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) { 12345 appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name); 12346 sb.append(" (pid "); 12347 sb.append(mi.pid); 12348 sb.append(") "); 12349 sb.append(mi.adjType); 12350 sb.append('\n'); 12351 if (mi.adjReason != null) { 12352 sb.append(" "); 12353 sb.append(mi.adjReason); 12354 sb.append('\n'); 12355 } 12356 } 12357 12358 /** 12359 * Searches array of arguments for the specified string 12360 * @param args array of argument strings 12361 * @param value value to search for 12362 * @return true if the value is contained in the array 12363 */ scanArgs(String[] args, String value)12364 private static boolean scanArgs(String[] args, String value) { 12365 if (args != null) { 12366 for (String arg : args) { 12367 if (value.equals(arg)) { 12368 return true; 12369 } 12370 } 12371 } 12372 return false; 12373 } 12374 12375 /** 12376 * Main code for cleaning up a process when it has gone away. This is 12377 * called both as a result of the process dying, or directly when stopping 12378 * a process when running in single process mode. 12379 * 12380 * @return Returns true if the given process has been restarted, so the 12381 * app that was passed in must remain on the process lists. 12382 */ 12383 @GuardedBy("this") cleanUpApplicationRecordLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, int index, boolean replacingPid, boolean fromBinderDied)12384 final boolean cleanUpApplicationRecordLocked(ProcessRecord app, int pid, 12385 boolean restarting, boolean allowRestart, int index, boolean replacingPid, 12386 boolean fromBinderDied) { 12387 boolean restart; 12388 synchronized (mProcLock) { 12389 if (index >= 0) { 12390 removeLruProcessLocked(app); 12391 ProcessList.remove(pid); 12392 } 12393 12394 // We don't want to unlinkDeathRecipient immediately, if it's not called from binder 12395 // and it's not isolated, as we'd need the signal to bookkeeping the dying process list. 12396 restart = app.onCleanupApplicationRecordLSP(mProcessStats, allowRestart, 12397 fromBinderDied || app.isolated /* unlinkDeath */); 12398 12399 // Cancel pending frozen task and clean up frozen record if there is any. 12400 mOomAdjuster.mCachedAppOptimizer.onCleanupApplicationRecordLocked(app); 12401 } 12402 mAppProfiler.onCleanupApplicationRecordLocked(app); 12403 skipCurrentReceiverLocked(app); 12404 updateProcessForegroundLocked(app, false, 0, false); 12405 mServices.killServicesLocked(app, allowRestart); 12406 mPhantomProcessList.onAppDied(pid); 12407 12408 // If the app is undergoing backup, tell the backup manager about it 12409 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 12410 if (backupTarget != null && pid == backupTarget.app.getPid()) { 12411 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App " 12412 + backupTarget.appInfo + " died during backup"); 12413 mHandler.post(new Runnable() { 12414 @Override 12415 public void run(){ 12416 try { 12417 IBackupManager bm = IBackupManager.Stub.asInterface( 12418 ServiceManager.getService(Context.BACKUP_SERVICE)); 12419 bm.agentDisconnectedForUser(app.userId, app.info.packageName); 12420 } catch (RemoteException e) { 12421 // can't happen; backup manager is local 12422 } 12423 } 12424 }); 12425 } 12426 12427 mProcessList.scheduleDispatchProcessDiedLocked(pid, app.info.uid); 12428 12429 // If this is a preceding instance of another process instance 12430 allowRestart = mProcessList.handlePrecedingAppDiedLocked(app); 12431 12432 // If somehow this process was still waiting for the death of its predecessor, 12433 // (probably it's "killed" before starting for real), reset the bookkeeping. 12434 final ProcessRecord predecessor = app.mPredecessor; 12435 if (predecessor != null) { 12436 predecessor.mSuccessor = null; 12437 predecessor.mSuccessorStartRunnable = null; 12438 app.mPredecessor = null; 12439 } 12440 12441 // If the caller is restarting this app, then leave it in its 12442 // current lists and let the caller take care of it. 12443 if (restarting) { 12444 return false; 12445 } 12446 12447 if (!app.isPersistent() || app.isolated) { 12448 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 12449 "Removing non-persistent process during cleanup: " + app); 12450 if (!replacingPid) { 12451 mProcessList.removeProcessNameLocked(app.processName, app.uid, app); 12452 } 12453 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 12454 } else if (!app.isRemoved()) { 12455 // This app is persistent, so we need to keep its record around. 12456 // If it is not already on the pending app list, add it there 12457 // and start a new process for it. 12458 if (mPersistentStartingProcesses.indexOf(app) < 0) { 12459 mPersistentStartingProcesses.add(app); 12460 restart = true; 12461 } 12462 } 12463 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v( 12464 TAG_CLEANUP, "Clean-up removing on hold: " + app); 12465 mProcessesOnHold.remove(app); 12466 12467 mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController()); 12468 mProcessList.noteProcessDiedLocked(app); 12469 12470 if (restart && allowRestart && !app.isolated) { 12471 // We have components that still need to be running in the 12472 // process, so re-launch it. 12473 if (index < 0) { 12474 ProcessList.remove(pid); 12475 } 12476 12477 // Remove provider publish timeout because we will start a new timeout when the 12478 // restarted process is attaching (if the process contains launching providers). 12479 mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, app); 12480 12481 mProcessList.addProcessNameLocked(app); 12482 app.setPendingStart(false); 12483 mProcessList.startProcessLocked(app, new HostingRecord( 12484 HostingRecord.HOSTING_TYPE_RESTART, app.processName), 12485 ZYGOTE_POLICY_FLAG_EMPTY); 12486 return true; 12487 } else if (pid > 0 && pid != MY_PID) { 12488 // Goodbye! 12489 removePidLocked(pid, app); 12490 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 12491 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 12492 if (app.isolated) { 12493 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 12494 } 12495 app.setPid(0); 12496 } 12497 return false; 12498 } 12499 12500 // ========================================================= 12501 // SERVICES 12502 // ========================================================= 12503 12504 @Override getServices(int maxNum, int flags)12505 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) { 12506 enforceNotIsolatedCaller("getServices"); 12507 12508 final int callingUid = Binder.getCallingUid(); 12509 final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission( 12510 INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED); 12511 final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices", 12512 Binder.getCallingPid(), callingUid); 12513 synchronized (this) { 12514 return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid, 12515 allowed, canInteractAcrossUsers); 12516 } 12517 } 12518 12519 @Override getRunningServiceControlPanel(ComponentName name)12520 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 12521 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 12522 synchronized (this) { 12523 return mServices.getRunningServiceControlPanelLocked(name); 12524 } 12525 } 12526 12527 @Override startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId)12528 public ComponentName startService(IApplicationThread caller, Intent service, 12529 String resolvedType, boolean requireForeground, String callingPackage, 12530 String callingFeatureId, int userId) 12531 throws TransactionTooLargeException { 12532 enforceNotIsolatedCaller("startService"); 12533 enforceAllowedToStartOrBindServiceIfSdkSandbox(service); 12534 // Refuse possible leaked file descriptors 12535 if (service != null && service.hasFileDescriptors() == true) { 12536 throw new IllegalArgumentException("File descriptors passed in Intent"); 12537 } 12538 12539 if (callingPackage == null) { 12540 throw new IllegalArgumentException("callingPackage cannot be null"); 12541 } 12542 12543 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 12544 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground); 12545 synchronized(this) { 12546 final int callingPid = Binder.getCallingPid(); 12547 final int callingUid = Binder.getCallingUid(); 12548 final long origId = Binder.clearCallingIdentity(); 12549 ComponentName res; 12550 try { 12551 res = mServices.startServiceLocked(caller, service, 12552 resolvedType, callingPid, callingUid, 12553 requireForeground, callingPackage, callingFeatureId, userId); 12554 } finally { 12555 Binder.restoreCallingIdentity(origId); 12556 } 12557 return res; 12558 } 12559 } 12560 12561 @Override stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)12562 public int stopService(IApplicationThread caller, Intent service, 12563 String resolvedType, int userId) { 12564 enforceNotIsolatedCaller("stopService"); 12565 // Refuse possible leaked file descriptors 12566 if (service != null && service.hasFileDescriptors() == true) { 12567 throw new IllegalArgumentException("File descriptors passed in Intent"); 12568 } 12569 12570 synchronized(this) { 12571 return mServices.stopServiceLocked(caller, service, resolvedType, userId); 12572 } 12573 } 12574 12575 @Override peekService(Intent service, String resolvedType, String callingPackage)12576 public IBinder peekService(Intent service, String resolvedType, String callingPackage) { 12577 enforceNotIsolatedCaller("peekService"); 12578 // Refuse possible leaked file descriptors 12579 if (service != null && service.hasFileDescriptors() == true) { 12580 throw new IllegalArgumentException("File descriptors passed in Intent"); 12581 } 12582 12583 if (callingPackage == null) { 12584 throw new IllegalArgumentException("callingPackage cannot be null"); 12585 } 12586 12587 synchronized(this) { 12588 return mServices.peekServiceLocked(service, resolvedType, callingPackage); 12589 } 12590 } 12591 12592 @Override stopServiceToken(ComponentName className, IBinder token, int startId)12593 public boolean stopServiceToken(ComponentName className, IBinder token, 12594 int startId) { 12595 synchronized(this) { 12596 return mServices.stopServiceTokenLocked(className, token, startId); 12597 } 12598 } 12599 12600 @Override setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)12601 public void setServiceForeground(ComponentName className, IBinder token, 12602 int id, Notification notification, int flags, int foregroundServiceType) { 12603 synchronized(this) { 12604 mServices.setServiceForegroundLocked(className, token, id, notification, flags, 12605 foregroundServiceType); 12606 } 12607 } 12608 12609 @Override getForegroundServiceType(ComponentName className, IBinder token)12610 public int getForegroundServiceType(ComponentName className, IBinder token) { 12611 synchronized (this) { 12612 return mServices.getForegroundServiceTypeLocked(className, token); 12613 } 12614 } 12615 12616 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)12617 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 12618 boolean requireFull, String name, String callerPackage) { 12619 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 12620 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 12621 } 12622 isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)12623 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 12624 String className, int flags) { 12625 boolean result = false; 12626 // For apps that don't have pre-defined UIDs, check for permission 12627 if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) { 12628 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 12629 if (ActivityManager.checkUidPermission( 12630 INTERACT_ACROSS_USERS, 12631 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 12632 ComponentName comp = new ComponentName(aInfo.packageName, className); 12633 String msg = "Permission Denial: Component " + comp.flattenToShortString() 12634 + " requests FLAG_SINGLE_USER, but app does not hold " 12635 + INTERACT_ACROSS_USERS; 12636 Slog.w(TAG, msg); 12637 throw new SecurityException(msg); 12638 } 12639 // Permission passed 12640 result = true; 12641 } 12642 } else if ("system".equals(componentProcessName)) { 12643 result = true; 12644 } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 12645 // Phone app and persistent apps are allowed to export singleuser providers. 12646 result = UserHandle.isSameApp(aInfo.uid, PHONE_UID) 12647 || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 12648 } 12649 if (DEBUG_MU) Slog.v(TAG_MU, 12650 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x" 12651 + Integer.toHexString(flags) + ") = " + result); 12652 return result; 12653 } 12654 12655 /** 12656 * Checks to see if the caller is in the same app as the singleton 12657 * component, or the component is in a special app. It allows special apps 12658 * to export singleton components but prevents exporting singleton 12659 * components for regular apps. 12660 */ isValidSingletonCall(int callingUid, int componentUid)12661 boolean isValidSingletonCall(int callingUid, int componentUid) { 12662 int componentAppId = UserHandle.getAppId(componentUid); 12663 return UserHandle.isSameApp(callingUid, componentUid) 12664 || componentAppId == SYSTEM_UID 12665 || componentAppId == PHONE_UID 12666 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 12667 == PackageManager.PERMISSION_GRANTED; 12668 } 12669 bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)12670 public int bindService(IApplicationThread caller, IBinder token, Intent service, 12671 String resolvedType, IServiceConnection connection, int flags, 12672 String callingPackage, int userId) throws TransactionTooLargeException { 12673 return bindServiceInstance(caller, token, service, resolvedType, connection, flags, 12674 null, callingPackage, userId); 12675 } 12676 12677 /** 12678 * Binds to a service with a given instanceName, creating it if it does not already exist. 12679 * If the instanceName field is not supplied, binding to the service occurs as usual. 12680 */ bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, String callingPackage, int userId)12681 public int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, 12682 String resolvedType, IServiceConnection connection, int flags, String instanceName, 12683 String callingPackage, int userId) throws TransactionTooLargeException { 12684 return bindServiceInstance(caller, token, service, resolvedType, connection, flags, 12685 instanceName, false, 0, null, callingPackage, userId); 12686 } 12687 bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String callingPackage, int userId)12688 private int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, 12689 String resolvedType, IServiceConnection connection, int flags, String instanceName, 12690 boolean isSdkSandboxService, int sdkSandboxClientAppUid, 12691 String sdkSandboxClientAppPackage, String callingPackage, int userId) 12692 throws TransactionTooLargeException { 12693 enforceNotIsolatedCaller("bindService"); 12694 enforceAllowedToStartOrBindServiceIfSdkSandbox(service); 12695 12696 // Refuse possible leaked file descriptors 12697 if (service != null && service.hasFileDescriptors() == true) { 12698 throw new IllegalArgumentException("File descriptors passed in Intent"); 12699 } 12700 12701 if (callingPackage == null) { 12702 throw new IllegalArgumentException("callingPackage cannot be null"); 12703 } 12704 12705 if (isSdkSandboxService && instanceName == null) { 12706 throw new IllegalArgumentException("No instance name provided for isolated process"); 12707 } 12708 12709 // Ensure that instanceName, which is caller provided, does not contain 12710 // unusual characters. 12711 if (instanceName != null) { 12712 for (int i = 0; i < instanceName.length(); ++i) { 12713 char c = instanceName.charAt(i); 12714 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') 12715 || (c >= '0' && c <= '9') || c == '_' || c == '.')) { 12716 throw new IllegalArgumentException("Illegal instanceName"); 12717 } 12718 } 12719 } 12720 12721 try { 12722 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 12723 final ComponentName cn = service.getComponent(); 12724 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindService:" 12725 + (cn != null ? cn.toShortString() : service.getAction())); 12726 } 12727 synchronized (this) { 12728 return mServices.bindServiceLocked(caller, token, service, resolvedType, connection, 12729 flags, instanceName, isSdkSandboxService, sdkSandboxClientAppUid, 12730 sdkSandboxClientAppPackage, callingPackage, userId); 12731 } 12732 } finally { 12733 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 12734 } 12735 } 12736 updateServiceGroup(IServiceConnection connection, int group, int importance)12737 public void updateServiceGroup(IServiceConnection connection, int group, int importance) { 12738 synchronized (this) { 12739 mServices.updateServiceGroupLocked(connection, group, importance); 12740 } 12741 } 12742 unbindService(IServiceConnection connection)12743 public boolean unbindService(IServiceConnection connection) { 12744 synchronized (this) { 12745 return mServices.unbindServiceLocked(connection); 12746 } 12747 } 12748 publishService(IBinder token, Intent intent, IBinder service)12749 public void publishService(IBinder token, Intent intent, IBinder service) { 12750 // Refuse possible leaked file descriptors 12751 if (intent != null && intent.hasFileDescriptors() == true) { 12752 throw new IllegalArgumentException("File descriptors passed in Intent"); 12753 } 12754 12755 synchronized(this) { 12756 if (!(token instanceof ServiceRecord)) { 12757 throw new IllegalArgumentException("Invalid service token"); 12758 } 12759 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 12760 } 12761 } 12762 unbindFinished(IBinder token, Intent intent, boolean doRebind)12763 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) { 12764 // Refuse possible leaked file descriptors 12765 if (intent != null && intent.hasFileDescriptors() == true) { 12766 throw new IllegalArgumentException("File descriptors passed in Intent"); 12767 } 12768 12769 synchronized(this) { 12770 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind); 12771 } 12772 } 12773 serviceDoneExecuting(IBinder token, int type, int startId, int res)12774 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) { 12775 synchronized(this) { 12776 if (!(token instanceof ServiceRecord)) { 12777 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token); 12778 throw new IllegalArgumentException("Invalid service token"); 12779 } 12780 mServices.serviceDoneExecutingLocked((ServiceRecord) token, type, startId, res, false); 12781 } 12782 } 12783 12784 // ========================================================= 12785 // BACKUP AND RESTORE 12786 // ========================================================= 12787 12788 // Cause the target app to be launched if necessary and its backup agent 12789 // instantiated. The backup agent will invoke backupAgentCreated() on the 12790 // activity manager to announce its creation. bindBackupAgent(String packageName, int backupMode, int targetUserId, @OperationType int operationType)12791 public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId, 12792 @OperationType int operationType) { 12793 if (DEBUG_BACKUP) { 12794 Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode 12795 + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid() 12796 + " uid = " + Process.myUid()); 12797 } 12798 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 12799 12800 // The instantiatedUserId is the user of the process the backup agent is started in. This is 12801 // different from the targetUserId which is the user whose data is to be backed up or 12802 // restored. This distinction is important for system-process packages that live in the 12803 // system user's process but backup/restore data for non-system users. 12804 // TODO (b/123688746): Handle all system-process packages with singleton check. 12805 boolean useSystemUser = PLATFORM_PACKAGE_NAME.equals(packageName) 12806 || getPackageManagerInternal().getSystemUiServiceComponent().getPackageName() 12807 .equals(packageName); 12808 final int instantiatedUserId = useSystemUser ? UserHandle.USER_SYSTEM : targetUserId; 12809 12810 IPackageManager pm = AppGlobals.getPackageManager(); 12811 ApplicationInfo app = null; 12812 try { 12813 app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId); 12814 } catch (RemoteException e) { 12815 // can't happen; package manager is process-local 12816 } 12817 if (app == null) { 12818 Slog.w(TAG, "Unable to bind backup agent for " + packageName); 12819 return false; 12820 } 12821 if (app.backupAgentName != null) { 12822 final ComponentName backupAgentName = new ComponentName( 12823 app.packageName, app.backupAgentName); 12824 int enableState = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 12825 try { 12826 enableState = pm.getComponentEnabledSetting(backupAgentName, instantiatedUserId); 12827 } catch (RemoteException e) { 12828 // can't happen; package manager is process-local 12829 } 12830 switch (enableState) { 12831 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED: 12832 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER: 12833 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED: 12834 Slog.w(TAG, "Unable to bind backup agent for " + backupAgentName 12835 + ", the backup agent component is disabled."); 12836 return false; 12837 12838 case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT: 12839 case PackageManager.COMPONENT_ENABLED_STATE_ENABLED: 12840 default: 12841 // Since there's no way to declare a backup agent disabled in the manifest, 12842 // assume the case COMPONENT_ENABLED_STATE_DEFAULT to be enabled. 12843 break; 12844 } 12845 } 12846 12847 int oldBackupUid; 12848 int newBackupUid; 12849 12850 synchronized(this) { 12851 // !!! TODO: currently no check here that we're already bound 12852 // Backup agent is now in use, its package can't be stopped. 12853 try { 12854 AppGlobals.getPackageManager().setPackageStoppedState( 12855 app.packageName, false, UserHandle.getUserId(app.uid)); 12856 } catch (RemoteException e) { 12857 } catch (IllegalArgumentException e) { 12858 Slog.w(TAG, "Failed trying to unstop package " 12859 + app.packageName + ": " + e); 12860 } 12861 12862 BackupRecord r = new BackupRecord(app, backupMode, targetUserId, operationType); 12863 ComponentName hostingName = 12864 (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL) 12865 ? new ComponentName(app.packageName, app.backupAgentName) 12866 : new ComponentName("android", "FullBackupAgent"); 12867 12868 // startProcessLocked() returns existing proc's record if it's already running 12869 ProcessRecord proc = startProcessLocked(app.processName, app, 12870 false, 0, 12871 new HostingRecord(HostingRecord.HOSTING_TYPE_BACKUP, hostingName), 12872 ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false); 12873 if (proc == null) { 12874 Slog.e(TAG, "Unable to start backup agent process " + r); 12875 return false; 12876 } 12877 12878 // If the app is a regular app (uid >= 10000) and not the system server or phone 12879 // process, etc, then mark it as being in full backup so that certain calls to the 12880 // process can be blocked. This is not reset to false anywhere because we kill the 12881 // process after the full backup is done and the ProcessRecord will vaporize anyway. 12882 if (UserHandle.isApp(app.uid) && 12883 backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) { 12884 proc.setInFullBackup(true); 12885 } 12886 r.app = proc; 12887 final BackupRecord backupTarget = mBackupTargets.get(targetUserId); 12888 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 12889 newBackupUid = proc.isInFullBackup() ? r.appInfo.uid : -1; 12890 mBackupTargets.put(targetUserId, r); 12891 12892 proc.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP); 12893 12894 // Try not to kill the process during backup 12895 updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_NONE); 12896 12897 // If the process is already attached, schedule the creation of the backup agent now. 12898 // If it is not yet live, this will be done when it attaches to the framework. 12899 final IApplicationThread thread = proc.getThread(); 12900 if (thread != null) { 12901 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc); 12902 try { 12903 thread.scheduleCreateBackupAgent(app, 12904 compatibilityInfoForPackage(app), backupMode, targetUserId, 12905 operationType); 12906 } catch (RemoteException e) { 12907 // Will time out on the backup manager side 12908 } 12909 } else { 12910 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach"); 12911 } 12912 // Invariants: at this point, the target app process exists and the application 12913 // is either already running or in the process of coming up. mBackupTarget and 12914 // mBackupAppName describe the app, so that when it binds back to the AM we 12915 // know that it's scheduled for a backup-agent operation. 12916 } 12917 12918 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 12919 if (oldBackupUid != -1) { 12920 js.removeBackingUpUid(oldBackupUid); 12921 } 12922 if (newBackupUid != -1) { 12923 js.addBackingUpUid(newBackupUid); 12924 } 12925 12926 return true; 12927 } 12928 clearPendingBackup(int userId)12929 private void clearPendingBackup(int userId) { 12930 if (DEBUG_BACKUP) { 12931 Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = " 12932 + Binder.getCallingUid() + " uid = " + Process.myUid()); 12933 } 12934 12935 synchronized (this) { 12936 final int indexOfKey = mBackupTargets.indexOfKey(userId); 12937 if (indexOfKey >= 0) { 12938 final BackupRecord backupTarget = mBackupTargets.valueAt(indexOfKey); 12939 if (backupTarget != null && backupTarget.app != null) { 12940 backupTarget.app.mProfile.clearHostingComponentType( 12941 HOSTING_COMPONENT_TYPE_BACKUP); 12942 } 12943 mBackupTargets.removeAt(indexOfKey); 12944 } 12945 } 12946 12947 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 12948 js.clearAllBackingUpUids(); 12949 } 12950 12951 // A backup agent has just come up 12952 @Override backupAgentCreated(String agentPackageName, IBinder agent, int userId)12953 public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) { 12954 // Resolve the target user id and enforce permissions. 12955 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 12956 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null); 12957 if (DEBUG_BACKUP) { 12958 Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent 12959 + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId 12960 + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid()); 12961 } 12962 12963 synchronized(this) { 12964 final BackupRecord backupTarget = mBackupTargets.get(userId); 12965 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 12966 if (!agentPackageName.equals(backupAppName)) { 12967 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 12968 return; 12969 } 12970 } 12971 12972 final long oldIdent = Binder.clearCallingIdentity(); 12973 try { 12974 IBackupManager bm = IBackupManager.Stub.asInterface( 12975 ServiceManager.getService(Context.BACKUP_SERVICE)); 12976 bm.agentConnectedForUser(userId, agentPackageName, agent); 12977 } catch (RemoteException e) { 12978 // can't happen; the backup manager service is local 12979 } catch (Exception e) { 12980 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 12981 e.printStackTrace(); 12982 } finally { 12983 Binder.restoreCallingIdentity(oldIdent); 12984 } 12985 } 12986 12987 // done with this agent unbindBackupAgent(ApplicationInfo appInfo)12988 public void unbindBackupAgent(ApplicationInfo appInfo) { 12989 if (DEBUG_BACKUP) { 12990 Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = " 12991 + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = " 12992 + Process.myUid()); 12993 } 12994 12995 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent"); 12996 if (appInfo == null) { 12997 Slog.w(TAG, "unbind backup agent for null app"); 12998 return; 12999 } 13000 13001 int oldBackupUid; 13002 13003 final int userId = UserHandle.getUserId(appInfo.uid); 13004 synchronized(this) { 13005 final BackupRecord backupTarget = mBackupTargets.get(userId); 13006 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 13007 try { 13008 if (backupAppName == null) { 13009 Slog.w(TAG, "Unbinding backup agent with no active backup"); 13010 return; 13011 } 13012 13013 if (!backupAppName.equals(appInfo.packageName)) { 13014 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 13015 return; 13016 } 13017 13018 // Not backing this app up any more; reset its OOM adjustment 13019 final ProcessRecord proc = backupTarget.app; 13020 updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_NONE); 13021 proc.setInFullBackup(false); 13022 proc.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP); 13023 13024 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 13025 13026 // If the app crashed during backup, 'thread' will be null here 13027 final IApplicationThread thread = proc.getThread(); 13028 if (thread != null) { 13029 try { 13030 thread.scheduleDestroyBackupAgent(appInfo, 13031 compatibilityInfoForPackage(appInfo), userId); 13032 } catch (Exception e) { 13033 Slog.e(TAG, "Exception when unbinding backup agent:"); 13034 e.printStackTrace(); 13035 } 13036 } 13037 } finally { 13038 mBackupTargets.delete(userId); 13039 } 13040 } 13041 13042 if (oldBackupUid != -1) { 13043 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 13044 js.removeBackingUpUid(oldBackupUid); 13045 } 13046 } 13047 13048 // ========================================================= 13049 // BROADCASTS 13050 // ========================================================= 13051 isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)13052 private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) { 13053 if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) { 13054 return false; 13055 } 13056 // Easy case -- we have the app's ProcessRecord. 13057 if (record != null) { 13058 return record.info.isInstantApp(); 13059 } 13060 // Otherwise check with PackageManager. 13061 IPackageManager pm = AppGlobals.getPackageManager(); 13062 try { 13063 if (callerPackage == null) { 13064 final String[] packageNames = pm.getPackagesForUid(uid); 13065 if (packageNames == null || packageNames.length == 0) { 13066 throw new IllegalArgumentException("Unable to determine caller package name"); 13067 } 13068 // Instant Apps can't use shared uids, so its safe to only check the first package. 13069 callerPackage = packageNames[0]; 13070 } 13071 mAppOpsService.checkPackage(uid, callerPackage); 13072 return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid)); 13073 } catch (RemoteException e) { 13074 Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e); 13075 return true; 13076 } 13077 } 13078 isPendingBroadcastProcessLocked(int pid)13079 boolean isPendingBroadcastProcessLocked(int pid) { 13080 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 13081 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 13082 || mBgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid) 13083 || mFgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid); 13084 } 13085 isPendingBroadcastProcessLocked(ProcessRecord app)13086 boolean isPendingBroadcastProcessLocked(ProcessRecord app) { 13087 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(app) 13088 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(app) 13089 || mBgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(app) 13090 || mFgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(app); 13091 } 13092 skipPendingBroadcastLocked(int pid)13093 void skipPendingBroadcastLocked(int pid) { 13094 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 13095 for (BroadcastQueue queue : mBroadcastQueues) { 13096 queue.skipPendingBroadcastLocked(pid); 13097 } 13098 } 13099 13100 // The app just attached; send any pending broadcasts that it should receive sendPendingBroadcastsLocked(ProcessRecord app)13101 boolean sendPendingBroadcastsLocked(ProcessRecord app) { 13102 boolean didSomething = false; 13103 for (BroadcastQueue queue : mBroadcastQueues) { 13104 didSomething |= queue.sendPendingBroadcastsLocked(app); 13105 } 13106 return didSomething; 13107 } 13108 updateUidReadyForBootCompletedBroadcastLocked(int uid)13109 void updateUidReadyForBootCompletedBroadcastLocked(int uid) { 13110 for (BroadcastQueue queue : mBroadcastQueues) { 13111 queue.updateUidReadyForBootCompletedBroadcastLocked(uid); 13112 queue.scheduleBroadcastsLocked(); 13113 } 13114 } 13115 13116 /** 13117 * @deprecated Use {@link #registerReceiverWithFeature} 13118 */ 13119 @Deprecated registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)13120 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 13121 IIntentReceiver receiver, IntentFilter filter, String permission, int userId, 13122 int flags) { 13123 return registerReceiverWithFeature(caller, callerPackage, null, null, 13124 receiver, filter, permission, userId, flags); 13125 } 13126 registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)13127 public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage, 13128 String callerFeatureId, String receiverId, IIntentReceiver receiver, 13129 IntentFilter filter, String permission, int userId, int flags) { 13130 enforceNotIsolatedCaller("registerReceiver"); 13131 13132 // Allow Sandbox process to register only unexported receivers. 13133 boolean unexported = (flags & Context.RECEIVER_NOT_EXPORTED) != 0; 13134 if (mSdkSandboxSettings.isBroadcastReceiverRestrictionsEnforced() 13135 && Process.isSdkSandboxUid(Binder.getCallingUid()) 13136 && !unexported) { 13137 throw new SecurityException("SDK sandbox process not allowed to call " 13138 + "registerReceiver"); 13139 } 13140 13141 ArrayList<Intent> stickyIntents = null; 13142 ProcessRecord callerApp = null; 13143 final boolean visibleToInstantApps 13144 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0; 13145 13146 int callingUid; 13147 int callingPid; 13148 boolean instantApp; 13149 synchronized(this) { 13150 if (caller != null) { 13151 callerApp = getRecordForAppLOSP(caller); 13152 if (callerApp == null) { 13153 throw new SecurityException( 13154 "Unable to find app for caller " + caller 13155 + " (pid=" + Binder.getCallingPid() 13156 + ") when registering receiver " + receiver); 13157 } 13158 if (callerApp.info.uid != SYSTEM_UID 13159 && !callerApp.getPkgList().containsKey(callerPackage) 13160 && !"android".equals(callerPackage)) { 13161 throw new SecurityException("Given caller package " + callerPackage 13162 + " is not running in process " + callerApp); 13163 } 13164 callingUid = callerApp.info.uid; 13165 callingPid = callerApp.getPid(); 13166 } else { 13167 callerPackage = null; 13168 callingUid = Binder.getCallingUid(); 13169 callingPid = Binder.getCallingPid(); 13170 } 13171 13172 instantApp = isInstantApp(callerApp, callerPackage, callingUid); 13173 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 13174 ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 13175 13176 Iterator<String> actions = filter.actionsIterator(); 13177 if (actions == null) { 13178 ArrayList<String> noAction = new ArrayList<String>(1); 13179 noAction.add(null); 13180 actions = noAction.iterator(); 13181 } 13182 boolean onlyProtectedBroadcasts = true; 13183 13184 // Collect stickies of users and check if broadcast is only registered for protected 13185 // broadcasts 13186 int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) }; 13187 while (actions.hasNext()) { 13188 String action = actions.next(); 13189 for (int id : userIds) { 13190 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(id); 13191 if (stickies != null) { 13192 ArrayList<Intent> intents = stickies.get(action); 13193 if (intents != null) { 13194 if (stickyIntents == null) { 13195 stickyIntents = new ArrayList<Intent>(); 13196 } 13197 stickyIntents.addAll(intents); 13198 } 13199 } 13200 } 13201 if (onlyProtectedBroadcasts) { 13202 try { 13203 onlyProtectedBroadcasts &= 13204 AppGlobals.getPackageManager().isProtectedBroadcast(action); 13205 } catch (RemoteException e) { 13206 onlyProtectedBroadcasts = false; 13207 Slog.w(TAG, "Remote exception", e); 13208 } 13209 } 13210 } 13211 13212 // If the change is enabled, but neither exported or not exported is set, we need to log 13213 // an error so the consumer can know to explicitly set the value for their flag. 13214 // If the caller is registering for a sticky broadcast with a null receiver, we won't 13215 // require a flag 13216 final boolean explicitExportStateDefined = 13217 (flags & (Context.RECEIVER_EXPORTED | Context.RECEIVER_NOT_EXPORTED)) != 0; 13218 if (((flags & Context.RECEIVER_EXPORTED) != 0) && ( 13219 (flags & Context.RECEIVER_NOT_EXPORTED) != 0)) { 13220 throw new IllegalArgumentException( 13221 "Receiver can't specify both RECEIVER_EXPORTED and RECEIVER_NOT_EXPORTED" 13222 + "flag"); 13223 } 13224 13225 // Don't enforce the flag check if we're EITHER registering for only protected 13226 // broadcasts, or the receiver is null (a sticky broadcast). Sticky broadcasts should 13227 // not be used generally, so we will be marking them as exported by default 13228 final boolean requireExplicitFlagForDynamicReceivers = CompatChanges.isChangeEnabled( 13229 DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED, callingUid); 13230 if (!onlyProtectedBroadcasts) { 13231 if (receiver == null && !explicitExportStateDefined) { 13232 // sticky broadcast, no flag specified (flag isn't required) 13233 flags |= Context.RECEIVER_EXPORTED; 13234 } else if (requireExplicitFlagForDynamicReceivers && !explicitExportStateDefined) { 13235 throw new SecurityException( 13236 callerPackage + ": One of RECEIVER_EXPORTED or " 13237 + "RECEIVER_NOT_EXPORTED should be specified when a receiver " 13238 + "isn't being registered exclusively for system broadcasts"); 13239 // Assume default behavior-- flag check is not enforced 13240 } else if (!requireExplicitFlagForDynamicReceivers && ( 13241 (flags & Context.RECEIVER_NOT_EXPORTED) == 0)) { 13242 // Change is not enabled, assume exported unless otherwise specified. 13243 flags |= Context.RECEIVER_EXPORTED; 13244 } 13245 } else if ((flags & Context.RECEIVER_NOT_EXPORTED) == 0) { 13246 flags |= Context.RECEIVER_EXPORTED; 13247 } 13248 } 13249 13250 // Dynamic receivers are exported by default for versions prior to T 13251 final boolean exported = (flags & Context.RECEIVER_EXPORTED) != 0; 13252 13253 ArrayList<Intent> allSticky = null; 13254 if (stickyIntents != null) { 13255 final ContentResolver resolver = mContext.getContentResolver(); 13256 // Look for any matching sticky broadcasts... 13257 for (int i = 0, N = stickyIntents.size(); i < N; i++) { 13258 Intent intent = stickyIntents.get(i); 13259 // Don't provided intents that aren't available to instant apps. 13260 if (instantApp && 13261 (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) { 13262 continue; 13263 } 13264 // If intent has scheme "content", it will need to access 13265 // provider that needs to lock mProviderMap in ActivityThread 13266 // and also it may need to wait application response, so we 13267 // cannot lock ActivityManagerService here. 13268 if (filter.match(resolver, intent, true, TAG) >= 0) { 13269 if (allSticky == null) { 13270 allSticky = new ArrayList<Intent>(); 13271 } 13272 allSticky.add(intent); 13273 } 13274 } 13275 } 13276 13277 // The first sticky in the list is returned directly back to the client. 13278 Intent sticky = allSticky != null ? allSticky.get(0) : null; 13279 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky); 13280 if (receiver == null) { 13281 return sticky; 13282 } 13283 13284 // SafetyNet logging for b/177931370. If any process other than system_server tries to 13285 // listen to this broadcast action, then log it. 13286 if (callingPid != Process.myPid()) { 13287 if (filter.hasAction("com.android.server.net.action.SNOOZE_WARNING") 13288 || filter.hasAction("com.android.server.net.action.SNOOZE_RAPID")) { 13289 EventLog.writeEvent(0x534e4554, "177931370", callingUid, ""); 13290 } 13291 } 13292 13293 synchronized (this) { 13294 IApplicationThread thread; 13295 if (callerApp != null && ((thread = callerApp.getThread()) == null 13296 || thread.asBinder() != caller.asBinder())) { 13297 // Original caller already died 13298 return null; 13299 } 13300 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 13301 if (rl == null) { 13302 rl = new ReceiverList(this, callerApp, callingPid, callingUid, 13303 userId, receiver); 13304 if (rl.app != null) { 13305 final int totalReceiversForApp = rl.app.mReceivers.numberOfReceivers(); 13306 if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) { 13307 throw new IllegalStateException("Too many receivers, total of " 13308 + totalReceiversForApp + ", registered for pid: " 13309 + rl.pid + ", callerPackage: " + callerPackage); 13310 } 13311 rl.app.mReceivers.addReceiver(rl); 13312 } else { 13313 try { 13314 receiver.asBinder().linkToDeath(rl, 0); 13315 } catch (RemoteException e) { 13316 return sticky; 13317 } 13318 rl.linkedToDeath = true; 13319 } 13320 mRegisteredReceivers.put(receiver.asBinder(), rl); 13321 } else if (rl.uid != callingUid) { 13322 throw new IllegalArgumentException( 13323 "Receiver requested to register for uid " + callingUid 13324 + " was previously registered for uid " + rl.uid 13325 + " callerPackage is " + callerPackage); 13326 } else if (rl.pid != callingPid) { 13327 throw new IllegalArgumentException( 13328 "Receiver requested to register for pid " + callingPid 13329 + " was previously registered for pid " + rl.pid 13330 + " callerPackage is " + callerPackage); 13331 } else if (rl.userId != userId) { 13332 throw new IllegalArgumentException( 13333 "Receiver requested to register for user " + userId 13334 + " was previously registered for user " + rl.userId 13335 + " callerPackage is " + callerPackage); 13336 } 13337 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId, 13338 receiverId, permission, callingUid, userId, instantApp, visibleToInstantApps, 13339 exported); 13340 if (rl.containsFilter(filter)) { 13341 Slog.w(TAG, "Receiver with filter " + filter 13342 + " already registered for pid " + rl.pid 13343 + ", callerPackage is " + callerPackage); 13344 } else { 13345 rl.add(bf); 13346 if (!bf.debugCheck()) { 13347 Slog.w(TAG, "==> For Dynamic broadcast"); 13348 } 13349 mReceiverResolver.addFilter(getPackageManagerInternal().snapshot(), bf); 13350 } 13351 13352 // Enqueue broadcasts for all existing stickies that match 13353 // this filter. 13354 if (allSticky != null) { 13355 ArrayList receivers = new ArrayList(); 13356 receivers.add(bf); 13357 13358 final int stickyCount = allSticky.size(); 13359 for (int i = 0; i < stickyCount; i++) { 13360 Intent intent = allSticky.get(i); 13361 BroadcastQueue queue = broadcastQueueForIntent(intent); 13362 BroadcastRecord r = new BroadcastRecord(queue, intent, null, 13363 null, null, -1, -1, false, null, null, null, null, OP_NONE, null, 13364 receivers, null, 0, null, null, false, true, true, -1, false, null, 13365 false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */); 13366 queue.enqueueParallelBroadcastLocked(r); 13367 queue.scheduleBroadcastsLocked(); 13368 } 13369 } 13370 13371 return sticky; 13372 } 13373 } 13374 unregisterReceiver(IIntentReceiver receiver)13375 public void unregisterReceiver(IIntentReceiver receiver) { 13376 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver); 13377 13378 final long origId = Binder.clearCallingIdentity(); 13379 try { 13380 boolean doTrim = false; 13381 13382 synchronized(this) { 13383 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 13384 if (rl != null) { 13385 final BroadcastRecord r = rl.curBroadcast; 13386 if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) { 13387 final boolean doNext = r.queue.finishReceiverLocked( 13388 r, r.resultCode, r.resultData, r.resultExtras, 13389 r.resultAbort, false); 13390 if (doNext) { 13391 doTrim = true; 13392 r.queue.processNextBroadcastLocked(/* frommsg */ false, 13393 /* skipOomAdj */ true); 13394 } 13395 } 13396 13397 if (rl.app != null) { 13398 rl.app.mReceivers.removeReceiver(rl); 13399 } 13400 removeReceiverLocked(rl); 13401 if (rl.linkedToDeath) { 13402 rl.linkedToDeath = false; 13403 rl.receiver.asBinder().unlinkToDeath(rl, 0); 13404 } 13405 } 13406 13407 // If we actually concluded any broadcasts, we might now be able 13408 // to trim the recipients' apps from our working set 13409 if (doTrim) { 13410 trimApplicationsLocked(false, OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER); 13411 return; 13412 } 13413 } 13414 13415 } finally { 13416 Binder.restoreCallingIdentity(origId); 13417 } 13418 } 13419 removeReceiverLocked(ReceiverList rl)13420 void removeReceiverLocked(ReceiverList rl) { 13421 mRegisteredReceivers.remove(rl.receiver.asBinder()); 13422 for (int i = rl.size() - 1; i >= 0; i--) { 13423 mReceiverResolver.removeFilter(rl.get(i)); 13424 } 13425 } 13426 sendPackageBroadcastLocked(int cmd, String[] packages, int userId)13427 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 13428 mProcessList.sendPackageBroadcastLocked(cmd, packages, userId); 13429 } 13430 collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users, int[] broadcastAllowList)13431 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType, 13432 int callingUid, int[] users, int[] broadcastAllowList) { 13433 // TODO: come back and remove this assumption to triage all broadcasts 13434 int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING; 13435 13436 List<ResolveInfo> receivers = null; 13437 HashSet<ComponentName> singleUserReceivers = null; 13438 boolean scannedFirstReceivers = false; 13439 for (int user : users) { 13440 // Skip users that have Shell restrictions 13441 if (callingUid == SHELL_UID 13442 && mUserController.hasUserRestriction( 13443 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) { 13444 continue; 13445 } 13446 List<ResolveInfo> newReceivers = mPackageManagerInt.queryIntentReceivers( 13447 intent, resolvedType, pmFlags, callingUid, user, true /* forSend */); 13448 if (user != UserHandle.USER_SYSTEM && newReceivers != null) { 13449 // If this is not the system user, we need to check for 13450 // any receivers that should be filtered out. 13451 for (int i = 0; i < newReceivers.size(); i++) { 13452 ResolveInfo ri = newReceivers.get(i); 13453 if ((ri.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 13454 newReceivers.remove(i); 13455 i--; 13456 } 13457 } 13458 } 13459 // Replace the alias receivers with their targets. 13460 if (newReceivers != null) { 13461 for (int i = newReceivers.size() - 1; i >= 0; i--) { 13462 final ResolveInfo ri = newReceivers.get(i); 13463 final Resolution<ResolveInfo> resolution = 13464 mComponentAliasResolver.resolveReceiver(intent, ri, resolvedType, 13465 pmFlags, user, callingUid, true /* forSend */); 13466 if (resolution == null) { 13467 // It was an alias, but the target was not found. 13468 newReceivers.remove(i); 13469 continue; 13470 } 13471 if (resolution.isAlias()) { 13472 newReceivers.set(i, resolution.getTarget()); 13473 } 13474 } 13475 } 13476 if (newReceivers != null && newReceivers.size() == 0) { 13477 newReceivers = null; 13478 } 13479 13480 if (receivers == null) { 13481 receivers = newReceivers; 13482 } else if (newReceivers != null) { 13483 // We need to concatenate the additional receivers 13484 // found with what we have do far. This would be easy, 13485 // but we also need to de-dup any receivers that are 13486 // singleUser. 13487 if (!scannedFirstReceivers) { 13488 // Collect any single user receivers we had already retrieved. 13489 scannedFirstReceivers = true; 13490 for (int i = 0; i < receivers.size(); i++) { 13491 ResolveInfo ri = receivers.get(i); 13492 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 13493 ComponentName cn = new ComponentName( 13494 ri.activityInfo.packageName, ri.activityInfo.name); 13495 if (singleUserReceivers == null) { 13496 singleUserReceivers = new HashSet<ComponentName>(); 13497 } 13498 singleUserReceivers.add(cn); 13499 } 13500 } 13501 } 13502 // Add the new results to the existing results, tracking 13503 // and de-dupping single user receivers. 13504 for (int i = 0; i < newReceivers.size(); i++) { 13505 ResolveInfo ri = newReceivers.get(i); 13506 if ((ri.activityInfo.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 13507 ComponentName cn = new ComponentName( 13508 ri.activityInfo.packageName, ri.activityInfo.name); 13509 if (singleUserReceivers == null) { 13510 singleUserReceivers = new HashSet<ComponentName>(); 13511 } 13512 if (!singleUserReceivers.contains(cn)) { 13513 singleUserReceivers.add(cn); 13514 receivers.add(ri); 13515 } 13516 } else { 13517 receivers.add(ri); 13518 } 13519 } 13520 } 13521 } 13522 if (receivers != null && broadcastAllowList != null) { 13523 for (int i = receivers.size() - 1; i >= 0; i--) { 13524 final int receiverAppId = UserHandle.getAppId( 13525 receivers.get(i).activityInfo.applicationInfo.uid); 13526 if (receiverAppId >= Process.FIRST_APPLICATION_UID 13527 && Arrays.binarySearch(broadcastAllowList, receiverAppId) < 0) { 13528 receivers.remove(i); 13529 } 13530 } 13531 } 13532 return receivers; 13533 } 13534 checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)13535 private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, 13536 String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) { 13537 if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 13538 // Don't yell about broadcasts sent via shell 13539 return; 13540 } 13541 13542 final String action = intent.getAction(); 13543 if (isProtectedBroadcast 13544 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action) 13545 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action) 13546 || Intent.ACTION_MEDIA_BUTTON.equals(action) 13547 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action) 13548 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action) 13549 || Intent.ACTION_MASTER_CLEAR.equals(action) 13550 || Intent.ACTION_FACTORY_RESET.equals(action) 13551 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 13552 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) 13553 || TelephonyManager.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action) 13554 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action) 13555 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action) 13556 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) { 13557 // Broadcast is either protected, or it's a public action that 13558 // we've relaxed, so it's fine for system internals to send. 13559 return; 13560 } 13561 13562 // This broadcast may be a problem... but there are often system components that 13563 // want to send an internal broadcast to themselves, which is annoying to have to 13564 // explicitly list each action as a protected broadcast, so we will check for that 13565 // one safe case and allow it: an explicit broadcast, only being received by something 13566 // that has protected itself. 13567 if (intent.getPackage() != null || intent.getComponent() != null) { 13568 if (receivers == null || receivers.size() == 0) { 13569 // Intent is explicit and there's no receivers. 13570 // This happens, e.g. , when a system component sends a broadcast to 13571 // its own runtime receiver, and there's no manifest receivers for it, 13572 // because this method is called twice for each broadcast, 13573 // for runtime receivers and manifest receivers and the later check would find 13574 // no receivers. 13575 return; 13576 } 13577 boolean allProtected = true; 13578 for (int i = receivers.size()-1; i >= 0; i--) { 13579 Object target = receivers.get(i); 13580 if (target instanceof ResolveInfo) { 13581 ResolveInfo ri = (ResolveInfo)target; 13582 if (ri.activityInfo.exported && ri.activityInfo.permission == null) { 13583 allProtected = false; 13584 break; 13585 } 13586 } else { 13587 BroadcastFilter bf = (BroadcastFilter)target; 13588 if (bf.requiredPermission == null) { 13589 allProtected = false; 13590 break; 13591 } 13592 } 13593 } 13594 if (allProtected) { 13595 // All safe! 13596 return; 13597 } 13598 } 13599 13600 // The vast majority of broadcasts sent from system internals 13601 // should be protected to avoid security holes, so yell loudly 13602 // to ensure we examine these cases. 13603 if (callerApp != null) { 13604 Log.wtf(TAG, "Sending non-protected broadcast " + action 13605 + " from system " + callerApp.toShortString() + " pkg " + callerPackage, 13606 new Throwable()); 13607 } else { 13608 Log.wtf(TAG, "Sending non-protected broadcast " + action 13609 + " from system uid " + UserHandle.formatUid(callingUid) 13610 + " pkg " + callerPackage, 13611 new Throwable()); 13612 } 13613 } 13614 13615 @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)13616 final int broadcastIntentLocked(ProcessRecord callerApp, 13617 String callerPackage, String callerFeatureId, Intent intent, String resolvedType, 13618 IIntentReceiver resultTo, int resultCode, String resultData, 13619 Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, 13620 String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered, 13621 boolean sticky, int callingPid, 13622 int callingUid, int realCallingUid, int realCallingPid, int userId) { 13623 return broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, intent, 13624 resolvedType, resultTo, resultCode, resultData, resultExtras, requiredPermissions, 13625 excludedPermissions, excludedPackages, appOp, bOptions, ordered, sticky, callingPid, 13626 callingUid, realCallingUid, realCallingPid, userId, 13627 false /* allowBackgroundActivityStarts */, 13628 null /* tokenNeededForBackgroundActivityStarts */, null /* broadcastAllowList */); 13629 } 13630 13631 @GuardedBy("this") broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, @Nullable 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, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken, @Nullable int[] broadcastAllowList)13632 final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, 13633 @Nullable String callerFeatureId, Intent intent, String resolvedType, 13634 IIntentReceiver resultTo, int resultCode, String resultData, 13635 Bundle resultExtras, String[] requiredPermissions, 13636 String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, 13637 boolean ordered, boolean sticky, int callingPid, int callingUid, 13638 int realCallingUid, int realCallingPid, int userId, 13639 boolean allowBackgroundActivityStarts, 13640 @Nullable IBinder backgroundActivityStartsToken, 13641 @Nullable int[] broadcastAllowList) { 13642 intent = new Intent(intent); 13643 13644 final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid); 13645 // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS 13646 if (callerInstantApp) { 13647 intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 13648 } 13649 13650 if (userId == UserHandle.USER_ALL && broadcastAllowList != null) { 13651 Slog.e(TAG, "broadcastAllowList only applies when sending to individual users. " 13652 + "Assuming restrictive whitelist."); 13653 broadcastAllowList = new int[]{}; 13654 } 13655 13656 // By default broadcasts do not go to stopped apps. 13657 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 13658 13659 // If we have not finished booting, don't allow this to launch new processes. 13660 if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 13661 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 13662 } 13663 13664 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 13665 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent 13666 + " ordered=" + ordered + " userid=" + userId); 13667 if ((resultTo != null) && !ordered) { 13668 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!"); 13669 } 13670 13671 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 13672 ALLOW_NON_FULL, "broadcast", callerPackage); 13673 13674 // Make sure that the user who is receiving this broadcast or its parent is running. 13675 // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps. 13676 if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) { 13677 if ((callingUid != SYSTEM_UID 13678 || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) 13679 && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { 13680 Slog.w(TAG, "Skipping broadcast of " + intent 13681 + ": user " + userId + " and its parent (if any) are stopped"); 13682 return ActivityManager.BROADCAST_FAILED_USER_STOPPED; 13683 } 13684 } 13685 13686 final String action = intent.getAction(); 13687 BroadcastOptions brOptions = null; 13688 if (bOptions != null) { 13689 brOptions = new BroadcastOptions(bOptions); 13690 if (brOptions.getTemporaryAppAllowlistDuration() > 0) { 13691 // See if the caller is allowed to do this. Note we are checking against 13692 // the actual real caller (not whoever provided the operation as say a 13693 // PendingIntent), because that who is actually supplied the arguments. 13694 if (checkComponentPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, 13695 realCallingPid, realCallingUid, -1, true) 13696 != PackageManager.PERMISSION_GRANTED 13697 && checkComponentPermission(START_ACTIVITIES_FROM_BACKGROUND, 13698 realCallingPid, realCallingUid, -1, true) 13699 != PackageManager.PERMISSION_GRANTED 13700 && checkComponentPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, 13701 realCallingPid, realCallingUid, -1, true) 13702 != PackageManager.PERMISSION_GRANTED) { 13703 String msg = "Permission Denial: " + intent.getAction() 13704 + " broadcast from " + callerPackage + " (pid=" + callingPid 13705 + ", uid=" + callingUid + ")" 13706 + " requires " 13707 + CHANGE_DEVICE_IDLE_TEMP_WHITELIST + " or " 13708 + START_ACTIVITIES_FROM_BACKGROUND + " or " 13709 + START_FOREGROUND_SERVICES_FROM_BACKGROUND; 13710 Slog.w(TAG, msg); 13711 throw new SecurityException(msg); 13712 } 13713 } 13714 if (brOptions.isDontSendToRestrictedApps() 13715 && !isUidActiveLOSP(callingUid) 13716 && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) { 13717 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage 13718 + " has background restrictions"); 13719 return ActivityManager.START_CANCELED; 13720 } 13721 if (brOptions.allowsBackgroundActivityStarts()) { 13722 // See if the caller is allowed to do this. Note we are checking against 13723 // the actual real caller (not whoever provided the operation as say a 13724 // PendingIntent), because that who is actually supplied the arguments. 13725 if (checkComponentPermission( 13726 android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND, 13727 realCallingPid, realCallingUid, -1, true) 13728 != PackageManager.PERMISSION_GRANTED) { 13729 String msg = "Permission Denial: " + intent.getAction() 13730 + " broadcast from " + callerPackage + " (pid=" + callingPid 13731 + ", uid=" + callingUid + ")" 13732 + " requires " 13733 + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; 13734 Slog.w(TAG, msg); 13735 throw new SecurityException(msg); 13736 } else { 13737 allowBackgroundActivityStarts = true; 13738 // We set the token to null since if it wasn't for it we'd allow anyway here 13739 backgroundActivityStartsToken = null; 13740 } 13741 } 13742 13743 if (brOptions.getIdForResponseEvent() > 0) { 13744 enforcePermission(android.Manifest.permission.ACCESS_BROADCAST_RESPONSE_STATS, 13745 callingPid, callingUid, "recordResponseEventWhileInBackground"); 13746 } 13747 } 13748 13749 // Verify that protected broadcasts are only being sent by system code, 13750 // and that system code is only sending protected broadcasts. 13751 final boolean isProtectedBroadcast; 13752 try { 13753 isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action); 13754 } catch (RemoteException e) { 13755 Slog.w(TAG, "Remote exception", e); 13756 return ActivityManager.BROADCAST_SUCCESS; 13757 } 13758 13759 final boolean isCallerSystem; 13760 switch (UserHandle.getAppId(callingUid)) { 13761 case ROOT_UID: 13762 case SYSTEM_UID: 13763 case PHONE_UID: 13764 case BLUETOOTH_UID: 13765 case NFC_UID: 13766 case SE_UID: 13767 case NETWORK_STACK_UID: 13768 isCallerSystem = true; 13769 break; 13770 default: 13771 isCallerSystem = (callerApp != null) && callerApp.isPersistent(); 13772 break; 13773 } 13774 13775 // First line security check before anything else: stop non-system apps from 13776 // sending protected broadcasts. 13777 if (!isCallerSystem) { 13778 if (isProtectedBroadcast) { 13779 String msg = "Permission Denial: not allowed to send broadcast " 13780 + action + " from pid=" 13781 + callingPid + ", uid=" + callingUid; 13782 Slog.w(TAG, msg); 13783 throw new SecurityException(msg); 13784 13785 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 13786 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { 13787 // Special case for compatibility: we don't want apps to send this, 13788 // but historically it has not been protected and apps may be using it 13789 // to poke their own app widget. So, instead of making it protected, 13790 // just limit it to the caller. 13791 if (callerPackage == null) { 13792 String msg = "Permission Denial: not allowed to send broadcast " 13793 + action + " from unknown caller."; 13794 Slog.w(TAG, msg); 13795 throw new SecurityException(msg); 13796 } else if (intent.getComponent() != null) { 13797 // They are good enough to send to an explicit component... verify 13798 // it is being sent to the calling app. 13799 if (!intent.getComponent().getPackageName().equals( 13800 callerPackage)) { 13801 String msg = "Permission Denial: not allowed to send broadcast " 13802 + action + " to " 13803 + intent.getComponent().getPackageName() + " from " 13804 + callerPackage; 13805 Slog.w(TAG, msg); 13806 throw new SecurityException(msg); 13807 } 13808 } else { 13809 // Limit broadcast to their own package. 13810 intent.setPackage(callerPackage); 13811 } 13812 } 13813 } 13814 13815 boolean timeoutExempt = false; 13816 13817 if (action != null) { 13818 if (getBackgroundLaunchBroadcasts().contains(action)) { 13819 if (DEBUG_BACKGROUND_CHECK) { 13820 Slog.i(TAG, "Broadcast action " + action + " forcing include-background"); 13821 } 13822 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 13823 } 13824 13825 if (Process.isSdkSandboxUid(realCallingUid)) { 13826 SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager( 13827 SdkSandboxManagerLocal.class); 13828 if (sdkSandboxManagerLocal == null) { 13829 throw new IllegalStateException("SdkSandboxManagerLocal not found when sending" 13830 + " a broadcast from an SDK sandbox uid."); 13831 } 13832 sdkSandboxManagerLocal.enforceAllowedToSendBroadcast(intent); 13833 } 13834 13835 switch (action) { 13836 case Intent.ACTION_MEDIA_SCANNER_SCAN_FILE: 13837 UserManagerInternal umInternal = LocalServices.getService( 13838 UserManagerInternal.class); 13839 UserInfo userInfo = umInternal.getUserInfo(userId); 13840 if (userInfo != null && userInfo.isCloneProfile()) { 13841 userId = umInternal.getProfileParentId(userId); 13842 } 13843 break; 13844 case Intent.ACTION_UID_REMOVED: 13845 case Intent.ACTION_PACKAGE_REMOVED: 13846 case Intent.ACTION_PACKAGE_CHANGED: 13847 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 13848 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 13849 case Intent.ACTION_PACKAGES_SUSPENDED: 13850 case Intent.ACTION_PACKAGES_UNSUSPENDED: 13851 // Handle special intents: if this broadcast is from the package 13852 // manager about a package being removed, we need to remove all of 13853 // its activities from the history stack. 13854 if (checkComponentPermission( 13855 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 13856 callingPid, callingUid, -1, true) 13857 != PackageManager.PERMISSION_GRANTED) { 13858 String msg = "Permission Denial: " + intent.getAction() 13859 + " broadcast from " + callerPackage + " (pid=" + callingPid 13860 + ", uid=" + callingUid + ")" 13861 + " requires " 13862 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 13863 Slog.w(TAG, msg); 13864 throw new SecurityException(msg); 13865 } 13866 switch (action) { 13867 case Intent.ACTION_UID_REMOVED: 13868 final int uid = getUidFromIntent(intent); 13869 if (uid >= 0) { 13870 mBatteryStatsService.removeUid(uid); 13871 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 13872 mAppOpsService.resetAllModes(UserHandle.getUserId(uid), 13873 intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME)); 13874 } else { 13875 mAppOpsService.uidRemoved(uid); 13876 } 13877 } 13878 break; 13879 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 13880 // If resources are unavailable just force stop all those packages 13881 // and flush the attribute cache as well. 13882 String list[] = 13883 intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 13884 if (list != null && list.length > 0) { 13885 for (int i = 0; i < list.length; i++) { 13886 forceStopPackageLocked(list[i], -1, false, true, true, 13887 false, false, userId, "storage unmount"); 13888 } 13889 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 13890 sendPackageBroadcastLocked( 13891 ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE, 13892 list, userId); 13893 } 13894 break; 13895 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 13896 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 13897 break; 13898 case Intent.ACTION_PACKAGE_REMOVED: 13899 case Intent.ACTION_PACKAGE_CHANGED: 13900 Uri data = intent.getData(); 13901 String ssp; 13902 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 13903 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action); 13904 final boolean replacing = 13905 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 13906 final boolean killProcess = 13907 !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false); 13908 final boolean fullUninstall = removed && !replacing; 13909 if (removed) { 13910 if (killProcess) { 13911 forceStopPackageLocked(ssp, UserHandle.getAppId( 13912 intent.getIntExtra(Intent.EXTRA_UID, -1)), 13913 false, true, true, false, fullUninstall, userId, 13914 removed ? "pkg removed" : "pkg changed"); 13915 getPackageManagerInternal() 13916 .onPackageProcessKilledForUninstall(ssp); 13917 } else { 13918 // Kill any app zygotes always, since they can't fork new 13919 // processes with references to the old code 13920 forceStopAppZygoteLocked(ssp, UserHandle.getAppId( 13921 intent.getIntExtra(Intent.EXTRA_UID, -1)), 13922 userId); 13923 } 13924 final int cmd = killProcess 13925 ? ApplicationThreadConstants.PACKAGE_REMOVED 13926 : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL; 13927 sendPackageBroadcastLocked(cmd, 13928 new String[] {ssp}, userId); 13929 if (fullUninstall) { 13930 mAppOpsService.packageRemoved( 13931 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp); 13932 13933 // Remove all permissions granted from/to this package 13934 mUgmInternal.removeUriPermissionsForPackage(ssp, userId, 13935 true, false); 13936 13937 mAtmInternal.removeRecentTasksByPackageName(ssp, userId); 13938 13939 mServices.forceStopPackageLocked(ssp, userId); 13940 mAtmInternal.onPackageUninstalled(ssp, userId); 13941 mBatteryStatsService.notePackageUninstalled(ssp); 13942 } 13943 } else { 13944 if (killProcess) { 13945 final int extraUid = intent.getIntExtra(Intent.EXTRA_UID, 13946 -1); 13947 synchronized (mProcLock) { 13948 mProcessList.killPackageProcessesLSP(ssp, 13949 UserHandle.getAppId(extraUid), 13950 userId, ProcessList.INVALID_ADJ, 13951 ApplicationExitInfo.REASON_USER_REQUESTED, 13952 ApplicationExitInfo.SUBREASON_PACKAGE_UPDATE, 13953 "change " + ssp); 13954 } 13955 } 13956 cleanupDisabledPackageComponentsLocked(ssp, userId, 13957 intent.getStringArrayExtra( 13958 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST)); 13959 mServices.schedulePendingServiceStartLocked(ssp, userId); 13960 } 13961 } 13962 break; 13963 case Intent.ACTION_PACKAGES_SUSPENDED: 13964 case Intent.ACTION_PACKAGES_UNSUSPENDED: 13965 final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals( 13966 intent.getAction()); 13967 final String[] packageNames = intent.getStringArrayExtra( 13968 Intent.EXTRA_CHANGED_PACKAGE_LIST); 13969 final int userIdExtra = intent.getIntExtra( 13970 Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 13971 13972 mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended, 13973 userIdExtra); 13974 break; 13975 } 13976 break; 13977 case Intent.ACTION_PACKAGE_REPLACED: 13978 { 13979 final Uri data = intent.getData(); 13980 final String ssp; 13981 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 13982 ApplicationInfo aInfo = null; 13983 try { 13984 aInfo = AppGlobals.getPackageManager() 13985 .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId); 13986 } catch (RemoteException ignore) {} 13987 if (aInfo == null) { 13988 Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:" 13989 + " ssp=" + ssp + " data=" + data); 13990 return ActivityManager.BROADCAST_SUCCESS; 13991 } 13992 updateAssociationForApp(aInfo); 13993 mAtmInternal.onPackageReplaced(aInfo); 13994 mServices.updateServiceApplicationInfoLocked(aInfo); 13995 sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED, 13996 new String[] {ssp}, userId); 13997 } 13998 break; 13999 } 14000 case Intent.ACTION_PACKAGE_ADDED: 14001 { 14002 // Special case for adding a package: by default turn on compatibility mode. 14003 Uri data = intent.getData(); 14004 String ssp; 14005 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 14006 final boolean replacing = 14007 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 14008 mAtmInternal.onPackageAdded(ssp, replacing); 14009 14010 try { 14011 ApplicationInfo ai = AppGlobals.getPackageManager(). 14012 getApplicationInfo(ssp, STOCK_PM_FLAGS, 0); 14013 mBatteryStatsService.notePackageInstalled(ssp, 14014 ai != null ? ai.longVersionCode : 0); 14015 } catch (RemoteException e) { 14016 } 14017 } 14018 break; 14019 } 14020 case Intent.ACTION_PACKAGE_DATA_CLEARED: 14021 { 14022 Uri data = intent.getData(); 14023 String ssp; 14024 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 14025 mAtmInternal.onPackageDataCleared(ssp, userId); 14026 } 14027 break; 14028 } 14029 case Intent.ACTION_TIMEZONE_CHANGED: 14030 // If this is the time zone changed action, queue up a message that will reset 14031 // the timezone of all currently running processes. This message will get 14032 // queued up before the broadcast happens. 14033 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 14034 break; 14035 case Intent.ACTION_TIME_CHANGED: 14036 // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between 14037 // the tri-state value it may contain and "unknown". 14038 // For convenience we re-use the Intent extra values. 14039 final int NO_EXTRA_VALUE_FOUND = -1; 14040 final int timeFormatPreferenceMsgValue = intent.getIntExtra( 14041 Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, 14042 NO_EXTRA_VALUE_FOUND /* defaultValue */); 14043 // Only send a message if the time preference is available. 14044 if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) { 14045 Message updateTimePreferenceMsg = 14046 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG, 14047 timeFormatPreferenceMsgValue, 0); 14048 mHandler.sendMessage(updateTimePreferenceMsg); 14049 } 14050 mBatteryStatsService.noteCurrentTimeChanged(); 14051 break; 14052 case ConnectivityManager.ACTION_CLEAR_DNS_CACHE: 14053 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 14054 break; 14055 case Proxy.PROXY_CHANGE_ACTION: 14056 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG)); 14057 break; 14058 case android.hardware.Camera.ACTION_NEW_PICTURE: 14059 case android.hardware.Camera.ACTION_NEW_VIDEO: 14060 // In N we just turned these off; in O we are turing them back on partly, 14061 // only for registered receivers. This will still address the main problem 14062 // (a spam of apps waking up when a picture is taken putting significant 14063 // memory pressure on the system at a bad point), while still allowing apps 14064 // that are already actively running to know about this happening. 14065 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 14066 break; 14067 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED: 14068 mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG); 14069 break; 14070 case "com.android.launcher.action.INSTALL_SHORTCUT": 14071 // As of O, we no longer support this broadcasts, even for pre-O apps. 14072 // Apps should now be using ShortcutManager.pinRequestShortcut(). 14073 Log.w(TAG, "Broadcast " + action 14074 + " no longer supported. It will not be delivered."); 14075 return ActivityManager.BROADCAST_SUCCESS; 14076 case Intent.ACTION_PRE_BOOT_COMPLETED: 14077 timeoutExempt = true; 14078 break; 14079 case Intent.ACTION_CLOSE_SYSTEM_DIALOGS: 14080 if (!mAtmInternal.checkCanCloseSystemDialogs(callingPid, callingUid, 14081 callerPackage)) { 14082 // Returning success seems to be the pattern here 14083 return ActivityManager.BROADCAST_SUCCESS; 14084 } 14085 break; 14086 } 14087 14088 if (Intent.ACTION_PACKAGE_ADDED.equals(action) || 14089 Intent.ACTION_PACKAGE_REMOVED.equals(action) || 14090 Intent.ACTION_PACKAGE_REPLACED.equals(action)) { 14091 final int uid = getUidFromIntent(intent); 14092 if (uid != -1) { 14093 final UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 14094 if (uidRec != null) { 14095 uidRec.updateHasInternetPermission(); 14096 } 14097 } 14098 } 14099 } 14100 14101 // Add to the sticky list if requested. 14102 if (sticky) { 14103 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY, 14104 callingPid, callingUid) 14105 != PackageManager.PERMISSION_GRANTED) { 14106 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid=" 14107 + callingPid + ", uid=" + callingUid 14108 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 14109 Slog.w(TAG, msg); 14110 throw new SecurityException(msg); 14111 } 14112 if (requiredPermissions != null && requiredPermissions.length > 0) { 14113 Slog.w(TAG, "Can't broadcast sticky intent " + intent 14114 + " and enforce permissions " + Arrays.toString(requiredPermissions)); 14115 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 14116 } 14117 if (intent.getComponent() != null) { 14118 throw new SecurityException( 14119 "Sticky broadcasts can't target a specific component"); 14120 } 14121 // We use userId directly here, since the "all" target is maintained 14122 // as a separate set of sticky broadcasts. 14123 if (userId != UserHandle.USER_ALL) { 14124 // But first, if this is not a broadcast to all users, then 14125 // make sure it doesn't conflict with an existing broadcast to 14126 // all users. 14127 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get( 14128 UserHandle.USER_ALL); 14129 if (stickies != null) { 14130 ArrayList<Intent> list = stickies.get(intent.getAction()); 14131 if (list != null) { 14132 int N = list.size(); 14133 int i; 14134 for (i=0; i<N; i++) { 14135 if (intent.filterEquals(list.get(i))) { 14136 throw new IllegalArgumentException( 14137 "Sticky broadcast " + intent + " for user " 14138 + userId + " conflicts with existing global broadcast"); 14139 } 14140 } 14141 } 14142 } 14143 } 14144 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 14145 if (stickies == null) { 14146 stickies = new ArrayMap<>(); 14147 mStickyBroadcasts.put(userId, stickies); 14148 } 14149 ArrayList<Intent> list = stickies.get(intent.getAction()); 14150 if (list == null) { 14151 list = new ArrayList<>(); 14152 stickies.put(intent.getAction(), list); 14153 } 14154 final int stickiesCount = list.size(); 14155 int i; 14156 for (i = 0; i < stickiesCount; i++) { 14157 if (intent.filterEquals(list.get(i))) { 14158 // This sticky already exists, replace it. 14159 list.set(i, new Intent(intent)); 14160 break; 14161 } 14162 } 14163 if (i >= stickiesCount) { 14164 list.add(new Intent(intent)); 14165 } 14166 } 14167 14168 int[] users; 14169 if (userId == UserHandle.USER_ALL) { 14170 // Caller wants broadcast to go to all started users. 14171 users = mUserController.getStartedUserArray(); 14172 } else { 14173 // Caller wants broadcast to go to one specific user. 14174 users = new int[] {userId}; 14175 } 14176 14177 // Figure out who all will receive this broadcast. 14178 List receivers = null; 14179 List<BroadcastFilter> registeredReceivers = null; 14180 // Need to resolve the intent to interested receivers... 14181 if ((intent.getFlags() & Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 14182 receivers = collectReceiverComponents( 14183 intent, resolvedType, callingUid, users, broadcastAllowList); 14184 } 14185 if (intent.getComponent() == null) { 14186 final PackageDataSnapshot snapshot = getPackageManagerInternal().snapshot(); 14187 if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) { 14188 // Query one target user at a time, excluding shell-restricted users 14189 for (int i = 0; i < users.length; i++) { 14190 if (mUserController.hasUserRestriction( 14191 UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) { 14192 continue; 14193 } 14194 List<BroadcastFilter> registeredReceiversForUser = 14195 mReceiverResolver.queryIntent(snapshot, intent, 14196 resolvedType, false /*defaultOnly*/, users[i]); 14197 if (registeredReceivers == null) { 14198 registeredReceivers = registeredReceiversForUser; 14199 } else if (registeredReceiversForUser != null) { 14200 registeredReceivers.addAll(registeredReceiversForUser); 14201 } 14202 } 14203 } else { 14204 registeredReceivers = mReceiverResolver.queryIntent(snapshot, intent, 14205 resolvedType, false /*defaultOnly*/, userId); 14206 } 14207 } 14208 14209 final boolean replacePending = 14210 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 14211 14212 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction() 14213 + " replacePending=" + replacePending); 14214 if (registeredReceivers != null && broadcastAllowList != null) { 14215 // if a uid whitelist was provided, remove anything in the application space that wasn't 14216 // in it. 14217 for (int i = registeredReceivers.size() - 1; i >= 0; i--) { 14218 final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid); 14219 if (owningAppId >= Process.FIRST_APPLICATION_UID 14220 && Arrays.binarySearch(broadcastAllowList, owningAppId) < 0) { 14221 registeredReceivers.remove(i); 14222 } 14223 } 14224 } 14225 14226 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 14227 if (!ordered && NR > 0) { 14228 // If we are not serializing this broadcast, then send the 14229 // registered receivers separately so they don't wait for the 14230 // components to be launched. 14231 if (isCallerSystem) { 14232 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid, 14233 isProtectedBroadcast, registeredReceivers); 14234 } 14235 final BroadcastQueue queue = broadcastQueueForIntent(intent); 14236 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, 14237 callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType, 14238 requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions, 14239 registeredReceivers, resultTo, resultCode, resultData, resultExtras, ordered, 14240 sticky, false, userId, allowBackgroundActivityStarts, 14241 backgroundActivityStartsToken, timeoutExempt); 14242 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r); 14243 final boolean replaced = replacePending 14244 && (queue.replaceParallelBroadcastLocked(r) != null); 14245 // Note: We assume resultTo is null for non-ordered broadcasts. 14246 if (!replaced) { 14247 queue.enqueueParallelBroadcastLocked(r); 14248 queue.scheduleBroadcastsLocked(); 14249 } 14250 registeredReceivers = null; 14251 NR = 0; 14252 } 14253 14254 // Merge into one list. 14255 int ir = 0; 14256 if (receivers != null) { 14257 // A special case for PACKAGE_ADDED: do not allow the package 14258 // being added to see this broadcast. This prevents them from 14259 // using this as a back door to get run as soon as they are 14260 // installed. Maybe in the future we want to have a special install 14261 // broadcast or such for apps, but we'd like to deliberately make 14262 // this decision. 14263 String skipPackages[] = null; 14264 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 14265 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 14266 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 14267 Uri data = intent.getData(); 14268 if (data != null) { 14269 String pkgName = data.getSchemeSpecificPart(); 14270 if (pkgName != null) { 14271 skipPackages = new String[] { pkgName }; 14272 } 14273 } 14274 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 14275 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 14276 } 14277 if (skipPackages != null && (skipPackages.length > 0)) { 14278 for (String skipPackage : skipPackages) { 14279 if (skipPackage != null) { 14280 int NT = receivers.size(); 14281 for (int it=0; it<NT; it++) { 14282 ResolveInfo curt = (ResolveInfo)receivers.get(it); 14283 if (curt.activityInfo.packageName.equals(skipPackage)) { 14284 receivers.remove(it); 14285 it--; 14286 NT--; 14287 } 14288 } 14289 } 14290 } 14291 } 14292 14293 int NT = receivers != null ? receivers.size() : 0; 14294 int it = 0; 14295 ResolveInfo curt = null; 14296 BroadcastFilter curr = null; 14297 while (it < NT && ir < NR) { 14298 if (curt == null) { 14299 curt = (ResolveInfo)receivers.get(it); 14300 } 14301 if (curr == null) { 14302 curr = registeredReceivers.get(ir); 14303 } 14304 if (curr.getPriority() >= curt.priority) { 14305 // Insert this broadcast record into the final list. 14306 receivers.add(it, curr); 14307 ir++; 14308 curr = null; 14309 it++; 14310 NT++; 14311 } else { 14312 // Skip to the next ResolveInfo in the final list. 14313 it++; 14314 curt = null; 14315 } 14316 } 14317 } 14318 while (ir < NR) { 14319 if (receivers == null) { 14320 receivers = new ArrayList(); 14321 } 14322 receivers.add(registeredReceivers.get(ir)); 14323 ir++; 14324 } 14325 14326 if (isCallerSystem) { 14327 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid, 14328 isProtectedBroadcast, receivers); 14329 } 14330 14331 if ((receivers != null && receivers.size() > 0) 14332 || resultTo != null) { 14333 BroadcastQueue queue = broadcastQueueForIntent(intent); 14334 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, 14335 callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType, 14336 requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions, 14337 receivers, resultTo, resultCode, resultData, resultExtras, 14338 ordered, sticky, false, userId, allowBackgroundActivityStarts, 14339 backgroundActivityStartsToken, timeoutExempt); 14340 14341 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r); 14342 14343 final BroadcastRecord oldRecord = 14344 replacePending ? queue.replaceOrderedBroadcastLocked(r) : null; 14345 if (oldRecord != null) { 14346 // Replaced, fire the result-to receiver. 14347 if (oldRecord.resultTo != null) { 14348 final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent); 14349 try { 14350 oldRecord.mIsReceiverAppRunning = true; 14351 oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo, 14352 oldRecord.intent, 14353 Activity.RESULT_CANCELED, null, null, 14354 false, false, oldRecord.userId, oldRecord.callingUid, callingUid, 14355 SystemClock.uptimeMillis() - oldRecord.enqueueTime, 0); 14356 } catch (RemoteException e) { 14357 Slog.w(TAG, "Failure [" 14358 + queue.mQueueName + "] sending broadcast result of " 14359 + intent, e); 14360 14361 } 14362 } 14363 } else { 14364 queue.enqueueOrderedBroadcastLocked(r); 14365 queue.scheduleBroadcastsLocked(); 14366 } 14367 } else { 14368 // There was nobody interested in the broadcast, but we still want to record 14369 // that it happened. 14370 if (intent.getComponent() == null && intent.getPackage() == null 14371 && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 14372 // This was an implicit broadcast... let's record it for posterity. 14373 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0); 14374 } 14375 } 14376 14377 return ActivityManager.BROADCAST_SUCCESS; 14378 } 14379 14380 /** 14381 * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1 14382 */ getUidFromIntent(Intent intent)14383 private int getUidFromIntent(Intent intent) { 14384 if (intent == null) { 14385 return -1; 14386 } 14387 final Bundle intentExtras = intent.getExtras(); 14388 return intent.hasExtra(Intent.EXTRA_UID) 14389 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 14390 } 14391 rotateBroadcastStatsIfNeededLocked()14392 final void rotateBroadcastStatsIfNeededLocked() { 14393 final long now = SystemClock.elapsedRealtime(); 14394 if (mCurBroadcastStats == null || 14395 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) { 14396 mLastBroadcastStats = mCurBroadcastStats; 14397 if (mLastBroadcastStats != null) { 14398 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime(); 14399 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis(); 14400 } 14401 mCurBroadcastStats = new BroadcastStats(); 14402 } 14403 } 14404 addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)14405 final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount, 14406 int skipCount, long dispatchTime) { 14407 rotateBroadcastStatsIfNeededLocked(); 14408 mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime); 14409 } 14410 addBackgroundCheckViolationLocked(String action, String targetPackage)14411 final void addBackgroundCheckViolationLocked(String action, String targetPackage) { 14412 rotateBroadcastStatsIfNeededLocked(); 14413 mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage); 14414 } 14415 verifyBroadcastLocked(Intent intent)14416 final Intent verifyBroadcastLocked(Intent intent) { 14417 // Refuse possible leaked file descriptors 14418 if (intent != null && intent.hasFileDescriptors() == true) { 14419 throw new IllegalArgumentException("File descriptors passed in Intent"); 14420 } 14421 14422 int flags = intent.getFlags(); 14423 14424 if (!mProcessesReady) { 14425 // if the caller really truly claims to know what they're doing, go 14426 // ahead and allow the broadcast without launching any receivers 14427 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 14428 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed. 14429 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 14430 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 14431 + " before boot completion"); 14432 throw new IllegalStateException("Cannot broadcast before boot completed"); 14433 } 14434 } 14435 14436 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 14437 throw new IllegalArgumentException( 14438 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 14439 } 14440 14441 if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 14442 switch (Binder.getCallingUid()) { 14443 case ROOT_UID: 14444 case SHELL_UID: 14445 break; 14446 default: 14447 Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID " 14448 + Binder.getCallingUid()); 14449 intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL); 14450 break; 14451 } 14452 } 14453 14454 return intent; 14455 } 14456 14457 /** 14458 * @deprecated Use {@link #broadcastIntentWithFeature} 14459 */ 14460 @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)14461 public final int broadcastIntent(IApplicationThread caller, 14462 Intent intent, String resolvedType, IIntentReceiver resultTo, 14463 int resultCode, String resultData, Bundle resultExtras, 14464 String[] requiredPermissions, int appOp, Bundle bOptions, 14465 boolean serialized, boolean sticky, int userId) { 14466 return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode, 14467 resultData, resultExtras, requiredPermissions, null, null, appOp, bOptions, 14468 serialized, sticky, userId); 14469 } 14470 14471 @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)14472 public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, 14473 Intent intent, String resolvedType, IIntentReceiver resultTo, 14474 int resultCode, String resultData, Bundle resultExtras, 14475 String[] requiredPermissions, String[] excludedPermissions, 14476 String[] excludedPackages, int appOp, Bundle bOptions, 14477 boolean serialized, boolean sticky, int userId) { 14478 enforceNotIsolatedCaller("broadcastIntent"); 14479 synchronized(this) { 14480 intent = verifyBroadcastLocked(intent); 14481 14482 final ProcessRecord callerApp = getRecordForAppLOSP(caller); 14483 final int callingPid = Binder.getCallingPid(); 14484 final int callingUid = Binder.getCallingUid(); 14485 14486 // Non-system callers can't declare that a broadcast is alarm-related. 14487 // The PendingIntent invocation case is handled in PendingIntentRecord. 14488 if (bOptions != null && callingUid != SYSTEM_UID) { 14489 if (bOptions.containsKey(BroadcastOptions.KEY_ALARM_BROADCAST)) { 14490 if (DEBUG_BROADCAST) { 14491 Slog.w(TAG, "Non-system caller " + callingUid 14492 + " may not flag broadcast as alarm-related"); 14493 } 14494 throw new SecurityException( 14495 "Non-system callers may not flag broadcasts as alarm-related"); 14496 } 14497 } 14498 14499 final long origId = Binder.clearCallingIdentity(); 14500 try { 14501 return broadcastIntentLocked(callerApp, 14502 callerApp != null ? callerApp.info.packageName : null, callingFeatureId, 14503 intent, resolvedType, resultTo, resultCode, resultData, resultExtras, 14504 requiredPermissions, excludedPermissions, excludedPackages, appOp, bOptions, 14505 serialized, sticky, callingPid, callingUid, callingUid, callingPid, userId); 14506 } finally { 14507 Binder.restoreCallingIdentity(origId); 14508 } 14509 } 14510 } 14511 14512 // Not the binder call surface broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken, @Nullable int[] broadcastAllowList)14513 int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, 14514 int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 14515 IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, 14516 String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, 14517 int userId, boolean allowBackgroundActivityStarts, 14518 @Nullable IBinder backgroundActivityStartsToken, 14519 @Nullable int[] broadcastAllowList) { 14520 synchronized(this) { 14521 intent = verifyBroadcastLocked(intent); 14522 14523 final long origId = Binder.clearCallingIdentity(); 14524 String[] requiredPermissions = requiredPermission == null ? null 14525 : new String[] {requiredPermission}; 14526 try { 14527 return broadcastIntentLocked(null, packageName, featureId, intent, resolvedType, 14528 resultTo, resultCode, resultData, resultExtras, requiredPermissions, null, 14529 null, OP_NONE, bOptions, serialized, sticky, -1, uid, realCallingUid, 14530 realCallingPid, userId, allowBackgroundActivityStarts, 14531 backgroundActivityStartsToken, broadcastAllowList); 14532 } finally { 14533 Binder.restoreCallingIdentity(origId); 14534 } 14535 } 14536 } 14537 unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)14538 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 14539 // Refuse possible leaked file descriptors 14540 if (intent != null && intent.hasFileDescriptors() == true) { 14541 throw new IllegalArgumentException("File descriptors passed in Intent"); 14542 } 14543 14544 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 14545 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null); 14546 14547 synchronized(this) { 14548 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 14549 != PackageManager.PERMISSION_GRANTED) { 14550 String msg = "Permission Denial: unbroadcastIntent() from pid=" 14551 + Binder.getCallingPid() 14552 + ", uid=" + Binder.getCallingUid() 14553 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 14554 Slog.w(TAG, msg); 14555 throw new SecurityException(msg); 14556 } 14557 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 14558 if (stickies != null) { 14559 ArrayList<Intent> list = stickies.get(intent.getAction()); 14560 if (list != null) { 14561 int N = list.size(); 14562 int i; 14563 for (i=0; i<N; i++) { 14564 if (intent.filterEquals(list.get(i))) { 14565 list.remove(i); 14566 break; 14567 } 14568 } 14569 if (list.size() <= 0) { 14570 stickies.remove(intent.getAction()); 14571 } 14572 } 14573 if (stickies.size() <= 0) { 14574 mStickyBroadcasts.remove(userId); 14575 } 14576 } 14577 } 14578 } 14579 backgroundServicesFinishedLocked(int userId)14580 void backgroundServicesFinishedLocked(int userId) { 14581 for (BroadcastQueue queue : mBroadcastQueues) { 14582 queue.backgroundServicesFinishedLocked(userId); 14583 } 14584 } 14585 finishReceiver(IBinder who, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)14586 public void finishReceiver(IBinder who, int resultCode, String resultData, 14587 Bundle resultExtras, boolean resultAbort, int flags) { 14588 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who); 14589 14590 // Refuse possible leaked file descriptors 14591 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 14592 throw new IllegalArgumentException("File descriptors passed in Bundle"); 14593 } 14594 14595 final long origId = Binder.clearCallingIdentity(); 14596 try { 14597 boolean doNext = false; 14598 BroadcastRecord r; 14599 BroadcastQueue queue; 14600 14601 synchronized(this) { 14602 if (isOnFgOffloadQueue(flags)) { 14603 queue = mFgOffloadBroadcastQueue; 14604 } else if (isOnBgOffloadQueue(flags)) { 14605 queue = mBgOffloadBroadcastQueue; 14606 } else { 14607 queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0 14608 ? mFgBroadcastQueue : mBgBroadcastQueue; 14609 } 14610 14611 r = queue.getMatchingOrderedReceiver(who); 14612 if (r != null) { 14613 doNext = r.queue.finishReceiverLocked(r, resultCode, 14614 resultData, resultExtras, resultAbort, true); 14615 } 14616 if (doNext) { 14617 r.queue.processNextBroadcastLocked(/*fromMsg=*/ false, /*skipOomAdj=*/ true); 14618 } 14619 // updateOomAdjLocked() will be done here 14620 trimApplicationsLocked(false, OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER); 14621 } 14622 14623 } finally { 14624 Binder.restoreCallingIdentity(origId); 14625 } 14626 } 14627 14628 // ========================================================= 14629 // INSTRUMENTATION 14630 // ========================================================= 14631 startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)14632 public boolean startInstrumentation(ComponentName className, 14633 String profileFile, int flags, Bundle arguments, 14634 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 14635 int userId, String abiOverride) { 14636 enforceNotIsolatedCaller("startInstrumentation"); 14637 final int callingUid = Binder.getCallingUid(); 14638 final int callingPid = Binder.getCallingPid(); 14639 userId = mUserController.handleIncomingUser(callingPid, callingUid, 14640 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 14641 // Refuse possible leaked file descriptors 14642 if (arguments != null && arguments.hasFileDescriptors()) { 14643 throw new IllegalArgumentException("File descriptors passed in Bundle"); 14644 } 14645 14646 synchronized(this) { 14647 InstrumentationInfo ii = null; 14648 ApplicationInfo ai = null; 14649 14650 boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0; 14651 14652 try { 14653 ii = mContext.getPackageManager().getInstrumentationInfo( 14654 className, STOCK_PM_FLAGS); 14655 ai = AppGlobals.getPackageManager().getApplicationInfo( 14656 ii.targetPackage, STOCK_PM_FLAGS, userId); 14657 } catch (PackageManager.NameNotFoundException e) { 14658 } catch (RemoteException e) { 14659 } 14660 if (ii == null) { 14661 reportStartInstrumentationFailureLocked(watcher, className, 14662 "Unable to find instrumentation info for: " + className); 14663 return false; 14664 } 14665 if (ai == null) { 14666 reportStartInstrumentationFailureLocked(watcher, className, 14667 "Unable to find instrumentation target package: " + ii.targetPackage); 14668 return false; 14669 } 14670 14671 if (ii.targetPackage.equals("android")) { 14672 if (!noRestart) { 14673 reportStartInstrumentationFailureLocked(watcher, className, 14674 "Cannot instrument system server without 'no-restart'"); 14675 return false; 14676 } 14677 } else if (!ai.hasCode()) { 14678 reportStartInstrumentationFailureLocked(watcher, className, 14679 "Instrumentation target has no code: " + ii.targetPackage); 14680 return false; 14681 } 14682 14683 int match = mContext.getPackageManager().checkSignatures( 14684 ii.targetPackage, ii.packageName); 14685 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 14686 if (Build.IS_DEBUGGABLE && (callingUid == Process.ROOT_UID) 14687 && (flags & INSTR_FLAG_ALWAYS_CHECK_SIGNATURE) == 0) { 14688 Slog.w(TAG, "Instrumentation test " + ii.packageName 14689 + " doesn't have a signature matching the target " + ii.targetPackage 14690 + ", which would not be allowed on the production Android builds"); 14691 } else { 14692 String msg = "Permission Denial: starting instrumentation " 14693 + className + " from pid=" 14694 + Binder.getCallingPid() 14695 + ", uid=" + Binder.getCallingUid() 14696 + " not allowed because package " + ii.packageName 14697 + " does not have a signature matching the target " 14698 + ii.targetPackage; 14699 reportStartInstrumentationFailureLocked(watcher, className, msg); 14700 throw new SecurityException(msg); 14701 } 14702 } 14703 if (!Build.IS_DEBUGGABLE && callingUid != ROOT_UID && callingUid != SHELL_UID 14704 && callingUid != SYSTEM_UID && !hasActiveInstrumentationLocked(callingPid)) { 14705 // If it's not debug build and not called from root/shell/system uid, reject it. 14706 final String msg = "Permission Denial: instrumentation test " 14707 + className + " from pid=" + callingPid + ", uid=" + callingUid 14708 + ", pkgName=" + getPackageNameByPid(callingPid) 14709 + " not allowed because it's not started from SHELL"; 14710 Slog.wtfQuiet(TAG, msg); 14711 reportStartInstrumentationFailureLocked(watcher, className, msg); 14712 throw new SecurityException(msg); 14713 } 14714 14715 boolean disableHiddenApiChecks = ai.usesNonSdkApi() 14716 || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0; 14717 boolean disableTestApiChecks = disableHiddenApiChecks 14718 || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0; 14719 14720 if (disableHiddenApiChecks || disableTestApiChecks) { 14721 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS, 14722 "disable hidden API checks"); 14723 } 14724 14725 if ((flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_SANDBOX) != 0) { 14726 return startInstrumentationOfSdkSandbox( 14727 className, 14728 profileFile, 14729 arguments, 14730 watcher, 14731 uiAutomationConnection, 14732 userId, 14733 abiOverride, 14734 ii, 14735 ai, 14736 noRestart, 14737 disableHiddenApiChecks, 14738 disableTestApiChecks); 14739 } 14740 14741 ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); 14742 activeInstr.mClass = className; 14743 String defProcess = ai.processName;; 14744 if (ii.targetProcesses == null) { 14745 activeInstr.mTargetProcesses = new String[]{ai.processName}; 14746 } else if (ii.targetProcesses.equals("*")) { 14747 activeInstr.mTargetProcesses = new String[0]; 14748 } else { 14749 activeInstr.mTargetProcesses = ii.targetProcesses.split(","); 14750 defProcess = activeInstr.mTargetProcesses[0]; 14751 } 14752 activeInstr.mTargetInfo = ai; 14753 activeInstr.mProfileFile = profileFile; 14754 activeInstr.mArguments = arguments; 14755 activeInstr.mWatcher = watcher; 14756 activeInstr.mUiAutomationConnection = uiAutomationConnection; 14757 activeInstr.mResultClass = className; 14758 activeInstr.mHasBackgroundActivityStartsPermission = checkPermission( 14759 START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid) 14760 == PackageManager.PERMISSION_GRANTED; 14761 activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission( 14762 START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid) 14763 == PackageManager.PERMISSION_GRANTED; 14764 activeInstr.mNoRestart = noRestart; 14765 14766 final long origId = Binder.clearCallingIdentity(); 14767 14768 ProcessRecord app; 14769 synchronized (mProcLock) { 14770 if (noRestart) { 14771 app = getProcessRecordLocked(ai.processName, ai.uid); 14772 } else { 14773 // Instrumentation can kill and relaunch even persistent processes 14774 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, 14775 userId, "start instr"); 14776 // Inform usage stats to make the target package active 14777 if (mUsageStatsService != null) { 14778 mUsageStatsService.reportEvent(ii.targetPackage, userId, 14779 UsageEvents.Event.SYSTEM_INTERACTION); 14780 } 14781 app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks, 14782 disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY); 14783 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 14784 } 14785 14786 app.setActiveInstrumentation(activeInstr); 14787 activeInstr.mFinished = false; 14788 activeInstr.mSourceUid = callingUid; 14789 activeInstr.mRunningProcesses.add(app); 14790 if (!mActiveInstrumentation.contains(activeInstr)) { 14791 mActiveInstrumentation.add(activeInstr); 14792 } 14793 } 14794 14795 if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) { 14796 // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with 14797 // --no-isolated-storage flag. 14798 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid, 14799 ii.packageName, AppOpsManager.MODE_ALLOWED); 14800 } 14801 Binder.restoreCallingIdentity(origId); 14802 14803 if (noRestart) { 14804 instrumentWithoutRestart(activeInstr, ai); 14805 } 14806 } 14807 14808 return true; 14809 } 14810 14811 @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)14812 private boolean startInstrumentationOfSdkSandbox( 14813 ComponentName className, 14814 String profileFile, 14815 Bundle arguments, 14816 IInstrumentationWatcher watcher, 14817 IUiAutomationConnection uiAutomationConnection, 14818 int userId, 14819 String abiOverride, 14820 InstrumentationInfo instrumentationInfo, 14821 ApplicationInfo sdkSandboxClientAppInfo, 14822 boolean noRestart, 14823 boolean disableHiddenApiChecks, 14824 boolean disableTestApiChecks) { 14825 14826 if (noRestart) { 14827 reportStartInstrumentationFailureLocked( 14828 watcher, 14829 className, 14830 "Instrumenting sdk sandbox with --no-restart flag is not supported"); 14831 return false; 14832 } 14833 14834 final ApplicationInfo sdkSandboxInfo; 14835 try { 14836 final PackageManager pm = mContext.getPackageManager(); 14837 sdkSandboxInfo = pm.getApplicationInfoAsUser(pm.getSdkSandboxPackageName(), 0, userId); 14838 } catch (NameNotFoundException e) { 14839 reportStartInstrumentationFailureLocked( 14840 watcher, className, "Can't find SdkSandbox package"); 14841 return false; 14842 } 14843 14844 final SdkSandboxManagerLocal sandboxManagerLocal = 14845 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 14846 if (sandboxManagerLocal == null) { 14847 reportStartInstrumentationFailureLocked( 14848 watcher, className, "Can't locate SdkSandboxManagerLocal"); 14849 return false; 14850 } 14851 14852 final String processName = sandboxManagerLocal.getSdkSandboxProcessNameForInstrumentation( 14853 sdkSandboxClientAppInfo); 14854 14855 ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); 14856 activeInstr.mClass = className; 14857 activeInstr.mTargetProcesses = new String[]{processName}; 14858 activeInstr.mTargetInfo = sdkSandboxInfo; 14859 activeInstr.mProfileFile = profileFile; 14860 activeInstr.mArguments = arguments; 14861 activeInstr.mWatcher = watcher; 14862 activeInstr.mUiAutomationConnection = uiAutomationConnection; 14863 activeInstr.mResultClass = className; 14864 activeInstr.mHasBackgroundActivityStartsPermission = false; 14865 activeInstr.mHasBackgroundForegroundServiceStartsPermission = false; 14866 // Instrumenting sdk sandbox without a restart is not supported 14867 activeInstr.mNoRestart = false; 14868 14869 final int callingUid = Binder.getCallingUid(); 14870 final long token = Binder.clearCallingIdentity(); 14871 try { 14872 sandboxManagerLocal.notifyInstrumentationStarted( 14873 sdkSandboxClientAppInfo.packageName, sdkSandboxClientAppInfo.uid); 14874 synchronized (mProcLock) { 14875 int sdkSandboxUid = Process.toSdkSandboxUid(sdkSandboxClientAppInfo.uid); 14876 // Kill the package sdk sandbox process belong to. At this point sdk sandbox is 14877 // already killed. 14878 forceStopPackageLocked( 14879 instrumentationInfo.targetPackage, 14880 /* appId= */ -1, 14881 /* callerWillRestart= */ true, 14882 /* purgeCache= */ false, 14883 /* doIt= */ true, 14884 /* evenPersistent= */ true, 14885 /* uninstalling= */ false, 14886 userId, 14887 "start instr"); 14888 14889 ProcessRecord app = addAppLocked( 14890 sdkSandboxInfo, 14891 processName, 14892 /* isolated= */ false, 14893 /* isSdkSandbox= */ true, 14894 sdkSandboxUid, 14895 sdkSandboxClientAppInfo.packageName, 14896 disableHiddenApiChecks, 14897 disableTestApiChecks, 14898 abiOverride, 14899 ZYGOTE_POLICY_FLAG_EMPTY); 14900 14901 app.setActiveInstrumentation(activeInstr); 14902 activeInstr.mFinished = false; 14903 activeInstr.mSourceUid = callingUid; 14904 activeInstr.mRunningProcesses.add(app); 14905 if (!mActiveInstrumentation.contains(activeInstr)) { 14906 mActiveInstrumentation.add(activeInstr); 14907 } 14908 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 14909 } 14910 } finally { 14911 Binder.restoreCallingIdentity(token); 14912 } 14913 14914 return true; 14915 } 14916 instrumentWithoutRestart(ActiveInstrumentation activeInstr, ApplicationInfo targetInfo)14917 private void instrumentWithoutRestart(ActiveInstrumentation activeInstr, 14918 ApplicationInfo targetInfo) { 14919 ProcessRecord pr; 14920 synchronized (this) { 14921 pr = getProcessRecordLocked(targetInfo.processName, targetInfo.uid); 14922 } 14923 14924 try { 14925 pr.getThread().instrumentWithoutRestart( 14926 activeInstr.mClass, 14927 activeInstr.mArguments, 14928 activeInstr.mWatcher, 14929 activeInstr.mUiAutomationConnection, 14930 targetInfo); 14931 } catch (RemoteException e) { 14932 Slog.i(TAG, "RemoteException from instrumentWithoutRestart", e); 14933 } 14934 } 14935 14936 @GuardedBy("this") hasActiveInstrumentationLocked(int pid)14937 private boolean hasActiveInstrumentationLocked(int pid) { 14938 if (pid == 0) { 14939 return false; 14940 } 14941 synchronized (mPidsSelfLocked) { 14942 ProcessRecord process = mPidsSelfLocked.get(pid); 14943 return process != null && process.getActiveInstrumentation() != null; 14944 } 14945 } 14946 getPackageNameByPid(int pid)14947 private String getPackageNameByPid(int pid) { 14948 synchronized (mPidsSelfLocked) { 14949 final ProcessRecord app = mPidsSelfLocked.get(pid); 14950 14951 if (app != null && app.info != null) { 14952 return app.info.packageName; 14953 } 14954 14955 return null; 14956 } 14957 } 14958 isCallerShell()14959 private boolean isCallerShell() { 14960 final int callingUid = Binder.getCallingUid(); 14961 return callingUid == SHELL_UID || callingUid == ROOT_UID; 14962 } 14963 14964 /** 14965 * Report errors that occur while attempting to start Instrumentation. Always writes the 14966 * error to the logs, but if somebody is watching, send the report there too. This enables 14967 * the "am" command to report errors with more information. 14968 * 14969 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 14970 * @param cn The component name of the instrumentation. 14971 * @param report The error report. 14972 */ reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)14973 private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, 14974 ComponentName cn, String report) { 14975 Slog.w(TAG, report); 14976 if (watcher != null) { 14977 Bundle results = new Bundle(); 14978 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 14979 results.putString("Error", report); 14980 mInstrumentationReporter.reportStatus(watcher, cn, -1, results); 14981 } 14982 } 14983 addInstrumentationResultsLocked(ProcessRecord app, Bundle results)14984 void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) { 14985 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 14986 if (instr == null) { 14987 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 14988 return; 14989 } 14990 14991 if (!instr.mFinished && results != null) { 14992 if (instr.mCurResults == null) { 14993 instr.mCurResults = new Bundle(results); 14994 } else { 14995 instr.mCurResults.putAll(results); 14996 } 14997 } 14998 } 14999 addInstrumentationResults(IApplicationThread target, Bundle results)15000 public void addInstrumentationResults(IApplicationThread target, Bundle results) { 15001 int userId = UserHandle.getCallingUserId(); 15002 // Refuse possible leaked file descriptors 15003 if (results != null && results.hasFileDescriptors()) { 15004 throw new IllegalArgumentException("File descriptors passed in Intent"); 15005 } 15006 15007 synchronized(this) { 15008 ProcessRecord app = getRecordForAppLOSP(target); 15009 if (app == null) { 15010 Slog.w(TAG, "addInstrumentationResults: no app for " + target); 15011 return; 15012 } 15013 final long origId = Binder.clearCallingIdentity(); 15014 try { 15015 addInstrumentationResultsLocked(app, results); 15016 } finally { 15017 Binder.restoreCallingIdentity(origId); 15018 } 15019 } 15020 } 15021 15022 @GuardedBy("this") finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)15023 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 15024 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 15025 if (instr == null) { 15026 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 15027 return; 15028 } 15029 15030 synchronized (mProcLock) { 15031 if (!instr.mFinished) { 15032 if (instr.mWatcher != null) { 15033 Bundle finalResults = instr.mCurResults; 15034 if (finalResults != null) { 15035 if (instr.mCurResults != null && results != null) { 15036 finalResults.putAll(results); 15037 } 15038 } else { 15039 finalResults = results; 15040 } 15041 mInstrumentationReporter.reportFinished(instr.mWatcher, 15042 instr.mClass, resultCode, finalResults); 15043 } 15044 15045 // Can't call out of the system process with a lock held, so post a message. 15046 if (instr.mUiAutomationConnection != null) { 15047 // Go back to the default mode of denying OP_NO_ISOLATED_STORAGE app op. 15048 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, app.uid, 15049 app.info.packageName, AppOpsManager.MODE_ERRORED); 15050 mAppOpsService.setAppOpsServiceDelegate(null); 15051 getPermissionManagerInternal().stopShellPermissionIdentityDelegation(); 15052 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG, 15053 instr.mUiAutomationConnection).sendToTarget(); 15054 } 15055 instr.mFinished = true; 15056 } 15057 15058 instr.removeProcess(app); 15059 app.setActiveInstrumentation(null); 15060 } 15061 app.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); 15062 15063 if (app.isSdkSandbox) { 15064 // For sharedUid apps this will kill all sdk sandbox processes, which is not ideal. 15065 // TODO(b/209061624): should we call ProcessList.removeProcessLocked instead? 15066 killUid(UserHandle.getAppId(app.uid), UserHandle.getUserId(app.uid), "finished instr"); 15067 final SdkSandboxManagerLocal sandboxManagerLocal = 15068 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 15069 if (sandboxManagerLocal != null) { 15070 sandboxManagerLocal.notifyInstrumentationFinished( 15071 app.sdkSandboxClientAppPackage, Process.getAppUidForSdkSandboxUid(app.uid)); 15072 } 15073 } else if (!instr.mNoRestart) { 15074 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, 15075 app.userId, 15076 "finished inst"); 15077 } 15078 } 15079 finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)15080 public void finishInstrumentation(IApplicationThread target, 15081 int resultCode, Bundle results) { 15082 int userId = UserHandle.getCallingUserId(); 15083 // Refuse possible leaked file descriptors 15084 if (results != null && results.hasFileDescriptors()) { 15085 throw new IllegalArgumentException("File descriptors passed in Intent"); 15086 } 15087 15088 synchronized(this) { 15089 ProcessRecord app = getRecordForAppLOSP(target); 15090 if (app == null) { 15091 Slog.w(TAG, "finishInstrumentation: no app for " + target); 15092 return; 15093 } 15094 final long origId = Binder.clearCallingIdentity(); 15095 finishInstrumentationLocked(app, resultCode, results); 15096 Binder.restoreCallingIdentity(origId); 15097 } 15098 } 15099 15100 @Override getFocusedRootTaskInfo()15101 public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException { 15102 return mActivityTaskManager.getFocusedRootTaskInfo(); 15103 } 15104 15105 @Override getConfiguration()15106 public Configuration getConfiguration() { 15107 return mActivityTaskManager.getConfiguration(); 15108 } 15109 15110 @Override suppressResizeConfigChanges(boolean suppress)15111 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException { 15112 mActivityTaskManager.suppressResizeConfigChanges(suppress); 15113 } 15114 15115 @Override updatePersistentConfiguration(Configuration values)15116 public void updatePersistentConfiguration(Configuration values) { 15117 updatePersistentConfigurationWithAttribution(values, 15118 Settings.getPackageNameForUid(mContext, Binder.getCallingUid()), null); 15119 } 15120 15121 @Override updatePersistentConfigurationWithAttribution(Configuration values, String callingPackage, String callingAttributionTag)15122 public void updatePersistentConfigurationWithAttribution(Configuration values, 15123 String callingPackage, String callingAttributionTag) { 15124 enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()"); 15125 enforceWriteSettingsPermission("updatePersistentConfiguration()", callingPackage, 15126 callingAttributionTag); 15127 if (values == null) { 15128 throw new NullPointerException("Configuration must not be null"); 15129 } 15130 15131 int userId = UserHandle.getCallingUserId(); 15132 15133 mActivityTaskManager.updatePersistentConfiguration(values, userId); 15134 } 15135 enforceWriteSettingsPermission(String func, String callingPackage, String callingAttributionTag)15136 private void enforceWriteSettingsPermission(String func, String callingPackage, 15137 String callingAttributionTag) { 15138 int uid = Binder.getCallingUid(); 15139 if (uid == ROOT_UID) { 15140 return; 15141 } 15142 15143 if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid, 15144 callingPackage, callingAttributionTag, false)) { 15145 return; 15146 } 15147 15148 String msg = "Permission Denial: " + func + " from pid=" 15149 + Binder.getCallingPid() 15150 + ", uid=" + uid 15151 + " requires " + android.Manifest.permission.WRITE_SETTINGS; 15152 Slog.w(TAG, msg); 15153 throw new SecurityException(msg); 15154 } 15155 15156 @Override updateConfiguration(Configuration values)15157 public boolean updateConfiguration(Configuration values) { 15158 return mActivityTaskManager.updateConfiguration(values); 15159 } 15160 15161 @Override updateMccMncConfiguration(String mcc, String mnc)15162 public boolean updateMccMncConfiguration(String mcc, String mnc) { 15163 int mccInt, mncInt; 15164 try { 15165 mccInt = Integer.parseInt(mcc); 15166 mncInt = Integer.parseInt(mnc); 15167 } catch (NumberFormatException | StringIndexOutOfBoundsException ex) { 15168 Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex); 15169 return false; 15170 } 15171 Configuration config = new Configuration(); 15172 config.mcc = mccInt; 15173 config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt; 15174 return mActivityTaskManager.updateConfiguration(config); 15175 } 15176 15177 @Override getLaunchedFromUid(IBinder activityToken)15178 public int getLaunchedFromUid(IBinder activityToken) { 15179 return ActivityClient.getInstance().getLaunchedFromUid(activityToken); 15180 } 15181 getLaunchedFromPackage(IBinder activityToken)15182 public String getLaunchedFromPackage(IBinder activityToken) { 15183 return ActivityClient.getInstance().getLaunchedFromPackage(activityToken); 15184 } 15185 15186 // ========================================================= 15187 // LIFETIME MANAGEMENT 15188 // ========================================================= 15189 15190 // Returns whether the app is receiving broadcast. 15191 // If receiving, fetch all broadcast queues which the app is 15192 // the current [or imminent] receiver on. isReceivingBroadcastLocked(ProcessRecord app, ArraySet<BroadcastQueue> receivingQueues)15193 boolean isReceivingBroadcastLocked(ProcessRecord app, 15194 ArraySet<BroadcastQueue> receivingQueues) { 15195 final ProcessReceiverRecord prr = app.mReceivers; 15196 final int numOfReceivers = prr.numberOfCurReceivers(); 15197 if (numOfReceivers > 0) { 15198 for (int i = 0; i < numOfReceivers; i++) { 15199 receivingQueues.add(prr.getCurReceiverAt(i).queue); 15200 } 15201 return true; 15202 } 15203 15204 // It's not the current receiver, but it might be starting up to become one 15205 for (BroadcastQueue queue : mBroadcastQueues) { 15206 final BroadcastRecord r = queue.mPendingBroadcast; 15207 if (r != null && r.curApp == app) { 15208 // found it; report which queue it's in 15209 receivingQueues.add(queue); 15210 } 15211 } 15212 15213 return !receivingQueues.isEmpty(); 15214 } 15215 startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)15216 Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, 15217 int targetUid, long targetVersionCode, ComponentName targetComponent, 15218 String targetProcess) { 15219 if (!mTrackingAssociations) { 15220 return null; 15221 } 15222 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 15223 = mAssociations.get(targetUid); 15224 if (components == null) { 15225 components = new ArrayMap<>(); 15226 mAssociations.put(targetUid, components); 15227 } 15228 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 15229 if (sourceUids == null) { 15230 sourceUids = new SparseArray<>(); 15231 components.put(targetComponent, sourceUids); 15232 } 15233 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 15234 if (sourceProcesses == null) { 15235 sourceProcesses = new ArrayMap<>(); 15236 sourceUids.put(sourceUid, sourceProcesses); 15237 } 15238 Association ass = sourceProcesses.get(sourceProcess); 15239 if (ass == null) { 15240 ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent, 15241 targetProcess); 15242 sourceProcesses.put(sourceProcess, ass); 15243 } 15244 ass.mCount++; 15245 ass.mNesting++; 15246 if (ass.mNesting == 1) { 15247 ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis(); 15248 ass.mLastState = sourceState; 15249 } 15250 return ass; 15251 } 15252 stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)15253 void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, 15254 long targetVersionCode, ComponentName targetComponent, String targetProcess) { 15255 if (!mTrackingAssociations) { 15256 return; 15257 } 15258 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 15259 = mAssociations.get(targetUid); 15260 if (components == null) { 15261 return; 15262 } 15263 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 15264 if (sourceUids == null) { 15265 return; 15266 } 15267 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 15268 if (sourceProcesses == null) { 15269 return; 15270 } 15271 Association ass = sourceProcesses.get(sourceProcess); 15272 if (ass == null || ass.mNesting <= 0) { 15273 return; 15274 } 15275 ass.mNesting--; 15276 if (ass.mNesting == 0) { 15277 long uptime = SystemClock.uptimeMillis(); 15278 ass.mTime += uptime - ass.mStartTime; 15279 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 15280 += uptime - ass.mLastStateUptime; 15281 ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2; 15282 } 15283 } 15284 noteUidProcessState(final int uid, final int state, final @ProcessCapability int capability)15285 void noteUidProcessState(final int uid, final int state, 15286 final @ProcessCapability int capability) { 15287 mBatteryStatsService.noteUidProcessState(uid, state); 15288 mAppOpsService.updateUidProcState(uid, state, capability); 15289 if (mTrackingAssociations) { 15290 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 15291 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 15292 = mAssociations.valueAt(i1); 15293 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 15294 SparseArray<ArrayMap<String, Association>> sourceUids 15295 = targetComponents.valueAt(i2); 15296 ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid); 15297 if (sourceProcesses != null) { 15298 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 15299 Association ass = sourceProcesses.valueAt(i4); 15300 if (ass.mNesting >= 1) { 15301 // currently associated 15302 long uptime = SystemClock.uptimeMillis(); 15303 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 15304 += uptime - ass.mLastStateUptime; 15305 ass.mLastState = state; 15306 ass.mLastStateUptime = uptime; 15307 } 15308 } 15309 } 15310 } 15311 } 15312 } 15313 } 15314 15315 /** 15316 * Returns true if things are idle enough to perform GCs. 15317 */ 15318 @GuardedBy("this") canGcNowLocked()15319 final boolean canGcNowLocked() { 15320 for (BroadcastQueue q : mBroadcastQueues) { 15321 if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isIdle()) { 15322 return false; 15323 } 15324 } 15325 return mAtmInternal.canGcNow(); 15326 } 15327 checkExcessivePowerUsage()15328 private void checkExcessivePowerUsage() { 15329 updateCpuStatsNow(); 15330 15331 final boolean monitorPhantomProcs = mSystemReady && FeatureFlagUtils.isEnabled(mContext, 15332 SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS); 15333 synchronized (mProcLock) { 15334 final boolean doCpuKills = mLastPowerCheckUptime != 0; 15335 final long curUptime = SystemClock.uptimeMillis(); 15336 final long uptimeSince = curUptime - mLastPowerCheckUptime; 15337 mLastPowerCheckUptime = curUptime; 15338 mProcessList.forEachLruProcessesLOSP(false, app -> { 15339 if (app.getThread() == null) { 15340 return; 15341 } 15342 if (app.mState.getSetProcState() >= ActivityManager.PROCESS_STATE_HOME) { 15343 int cpuLimit; 15344 long checkDur = curUptime - app.mState.getWhenUnimportant(); 15345 if (checkDur <= mConstants.POWER_CHECK_INTERVAL) { 15346 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1; 15347 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 2) 15348 || app.mState.getSetProcState() <= ActivityManager.PROCESS_STATE_HOME) { 15349 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2; 15350 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 3)) { 15351 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3; 15352 } else { 15353 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4; 15354 } 15355 15356 updateAppProcessCpuTimeLPr(uptimeSince, doCpuKills, checkDur, cpuLimit, app); 15357 15358 if (monitorPhantomProcs) { 15359 // Also check the phantom processes if there is any 15360 updatePhantomProcessCpuTimeLPr( 15361 uptimeSince, doCpuKills, checkDur, cpuLimit, app); 15362 } 15363 } 15364 }); 15365 } 15366 } 15367 15368 @GuardedBy("mProcLock") updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)15369 private void updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, 15370 final long checkDur, final int cpuLimit, final ProcessRecord app) { 15371 synchronized (mAppProfiler.mProfilerLock) { 15372 final ProcessProfileRecord profile = app.mProfile; 15373 final long curCpuTime = profile.mCurCpuTime.get(); 15374 final long lastCpuTime = profile.mLastCpuTime.get(); 15375 if (lastCpuTime > 0) { 15376 final long cpuTimeUsed = curCpuTime - lastCpuTime; 15377 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed, 15378 app.processName, app.toShortString(), cpuLimit, app)) { 15379 mHandler.post(() -> { 15380 synchronized (ActivityManagerService.this) { 15381 app.killLocked("excessive cpu " + cpuTimeUsed + " during " 15382 + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit, 15383 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 15384 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU, 15385 true); 15386 } 15387 }); 15388 profile.reportExcessiveCpu(); 15389 } 15390 } 15391 15392 profile.mLastCpuTime.set(curCpuTime); 15393 } 15394 } 15395 15396 @GuardedBy("mProcLock") updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)15397 private void updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, 15398 final long checkDur, final int cpuLimit, final ProcessRecord app) { 15399 mPhantomProcessList.forEachPhantomProcessOfApp(app, r -> { 15400 if (r.mLastCputime > 0) { 15401 final long cpuTimeUsed = r.mCurrentCputime - r.mLastCputime; 15402 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed, 15403 app.processName, r.toString(), cpuLimit, app)) { 15404 mHandler.post(() -> { 15405 synchronized (ActivityManagerService.this) { 15406 mPhantomProcessList.killPhantomProcessGroupLocked(app, r, 15407 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 15408 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU, 15409 "excessive cpu " + cpuTimeUsed + " during " 15410 + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit); 15411 } 15412 }); 15413 return false; 15414 } 15415 } 15416 r.mLastCputime = r.mCurrentCputime; 15417 return true; 15418 }); 15419 } 15420 15421 @GuardedBy("mProcLock") checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, final long cputimeUsed, final String processName, final String description, final int cpuLimit, final ProcessRecord app)15422 private boolean checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, 15423 final long cputimeUsed, final String processName, final String description, 15424 final int cpuLimit, final ProcessRecord app) { 15425 if (DEBUG_POWER && (uptimeSince > 0)) { 15426 StringBuilder sb = new StringBuilder(128); 15427 sb.append("CPU for "); 15428 sb.append(description); 15429 sb.append(": over "); 15430 TimeUtils.formatDuration(uptimeSince, sb); 15431 sb.append(" used "); 15432 TimeUtils.formatDuration(cputimeUsed, sb); 15433 sb.append(" ("); 15434 sb.append((cputimeUsed * 100.0) / uptimeSince); 15435 sb.append("%)"); 15436 Slog.i(TAG_POWER, sb.toString()); 15437 } 15438 // If the process has used too much CPU over the last duration, the 15439 // user probably doesn't want this, so kill! 15440 if (doCpuKills && uptimeSince > 0) { 15441 if (((cputimeUsed * 100) / uptimeSince) >= cpuLimit) { 15442 mBatteryStatsService.reportExcessiveCpu(app.info.uid, app.processName, 15443 uptimeSince, cputimeUsed); 15444 app.getPkgList().forEachPackageProcessStats(holder -> { 15445 final ProcessState state = holder.state; 15446 FrameworkStatsLog.write( 15447 FrameworkStatsLog.EXCESSIVE_CPU_USAGE_REPORTED, 15448 app.info.uid, 15449 processName, 15450 state != null ? state.getPackage() : app.info.packageName, 15451 holder.appVersion); 15452 }); 15453 return true; 15454 } 15455 } 15456 return false; 15457 } 15458 isEphemeralLocked(int uid)15459 private boolean isEphemeralLocked(int uid) { 15460 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid); 15461 if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid 15462 return false; 15463 } 15464 return getPackageManagerInternal().isPackageEphemeral( 15465 UserHandle.getUserId(uid), packages[0]); 15466 } 15467 15468 @GuardedBy("this") enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)15469 void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) { 15470 uid = uidRec != null ? uidRec.getUid() : uid; 15471 if (uid < 0) { 15472 throw new IllegalArgumentException("No UidRecord or uid"); 15473 } 15474 15475 final int procState = uidRec != null 15476 ? uidRec.getSetProcState() : PROCESS_STATE_NONEXISTENT; 15477 final long procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0; 15478 final int capability = uidRec != null ? uidRec.getSetCapability() : 0; 15479 final boolean ephemeral = uidRec != null ? uidRec.isEphemeral() : isEphemeralLocked(uid); 15480 15481 if (uidRec != null && uidRec.isIdle() && (change & UidRecord.CHANGE_IDLE) != 0) { 15482 mProcessList.killAppIfBgRestrictedAndCachedIdleLocked(uidRec); 15483 } 15484 15485 if (uidRec != null && !uidRec.isIdle() && (change & UidRecord.CHANGE_GONE) != 0) { 15486 // If this uid is going away, and we haven't yet reported it is gone, 15487 // then do so now. 15488 change |= UidRecord.CHANGE_IDLE; 15489 } 15490 final int enqueuedChange = mUidObserverController.enqueueUidChange( 15491 uidRec == null ? null : uidRec.pendingChange, 15492 uid, change, procState, procStateSeq, capability, ephemeral); 15493 if (uidRec != null) { 15494 uidRec.setLastReportedChange(enqueuedChange); 15495 } 15496 15497 // Directly update the power manager, since we sit on top of it and it is critical 15498 // it be kept in sync (so wake locks will be held as soon as appropriate). 15499 if (mLocalPowerManager != null) { 15500 // TODO: dispatch cached/uncached changes here, so we don't need to report 15501 // all proc state changes. 15502 if ((enqueuedChange & UidRecord.CHANGE_ACTIVE) != 0) { 15503 mLocalPowerManager.uidActive(uid); 15504 } 15505 if ((enqueuedChange & UidRecord.CHANGE_IDLE) != 0) { 15506 mLocalPowerManager.uidIdle(uid); 15507 } 15508 if ((enqueuedChange & UidRecord.CHANGE_GONE) != 0) { 15509 mLocalPowerManager.uidGone(uid); 15510 } else if ((enqueuedChange & UidRecord.CHANGE_PROCSTATE) != 0) { 15511 mLocalPowerManager.updateUidProcState(uid, procState); 15512 } 15513 } 15514 } 15515 15516 @GuardedBy(anyOf = {"this", "mProcLock"}) setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor)15517 final void setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor) { 15518 if (proc.getThread() != null) { 15519 proc.mProfile.setProcessTrackerState( 15520 proc.mState.getReportedProcState(), memFactor); 15521 } 15522 } 15523 15524 @GuardedBy("this") updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean oomAdj)15525 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 15526 int fgServiceTypes, boolean oomAdj) { 15527 final ProcessServiceRecord psr = proc.mServices; 15528 final boolean foregroundStateChanged = isForeground != psr.hasForegroundServices(); 15529 if (foregroundStateChanged 15530 || psr.getForegroundServiceTypes() != fgServiceTypes) { 15531 if (foregroundStateChanged) { 15532 // Notify internal listeners. 15533 for (int i = mForegroundServiceStateListeners.size() - 1; i >= 0; i--) { 15534 mForegroundServiceStateListeners.get(i).onForegroundServiceStateChanged( 15535 proc.info.packageName, proc.info.uid, proc.getPid(), isForeground); 15536 } 15537 } 15538 psr.setHasForegroundServices(isForeground, fgServiceTypes); 15539 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 15540 proc.info.uid); 15541 if (isForeground) { 15542 if (curProcs == null) { 15543 curProcs = new ArrayList<ProcessRecord>(); 15544 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 15545 } 15546 if (!curProcs.contains(proc)) { 15547 curProcs.add(proc); 15548 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 15549 proc.info.packageName, proc.info.uid); 15550 } 15551 } else { 15552 if (curProcs != null) { 15553 if (curProcs.remove(proc)) { 15554 mBatteryStatsService.noteEvent( 15555 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 15556 proc.info.packageName, proc.info.uid); 15557 if (curProcs.size() <= 0) { 15558 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 15559 } 15560 } 15561 } 15562 } 15563 15564 psr.setReportedForegroundServiceTypes(fgServiceTypes); 15565 ProcessChangeItem item = mProcessList.enqueueProcessChangeItemLocked( 15566 proc.getPid(), proc.info.uid); 15567 item.changes |= ProcessChangeItem.CHANGE_FOREGROUND_SERVICES; 15568 item.foregroundServiceTypes = fgServiceTypes; 15569 } 15570 if (oomAdj) { 15571 updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 15572 } 15573 } 15574 15575 // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update 15576 // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities getTopApp()15577 ProcessRecord getTopApp() { 15578 final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null; 15579 final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null; 15580 String pkg; 15581 int uid; 15582 if (r != null) { 15583 pkg = r.processName; 15584 uid = r.info.uid; 15585 } else { 15586 pkg = null; 15587 uid = -1; 15588 } 15589 // Has the UID or resumed package name changed? 15590 synchronized (mCurResumedAppLock) { 15591 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 15592 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 15593 15594 final long identity = Binder.clearCallingIdentity(); 15595 try { 15596 if (mCurResumedPackage != null) { 15597 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 15598 mCurResumedPackage, mCurResumedUid); 15599 } 15600 mCurResumedPackage = pkg; 15601 mCurResumedUid = uid; 15602 if (mCurResumedPackage != null) { 15603 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 15604 mCurResumedPackage, mCurResumedUid); 15605 } 15606 } finally { 15607 Binder.restoreCallingIdentity(identity); 15608 } 15609 } 15610 } 15611 return r; 15612 } 15613 15614 /** 15615 * Enqueue the given process into a todo list, and the caller should 15616 * call {@link #updateOomAdjPendingTargetsLocked} to kick off a pass of the oom adj update. 15617 */ 15618 @GuardedBy("this") enqueueOomAdjTargetLocked(ProcessRecord app)15619 void enqueueOomAdjTargetLocked(ProcessRecord app) { 15620 mOomAdjuster.enqueueOomAdjTargetLocked(app); 15621 } 15622 15623 /** 15624 * Remove the given process into a todo list. 15625 */ 15626 @GuardedBy("this") removeOomAdjTargetLocked(ProcessRecord app, boolean procDied)15627 void removeOomAdjTargetLocked(ProcessRecord app, boolean procDied) { 15628 mOomAdjuster.removeOomAdjTargetLocked(app, procDied); 15629 } 15630 15631 /** 15632 * Kick off an oom adj update pass for the pending targets which are enqueued via 15633 * {@link #enqueueOomAdjTargetLocked}. 15634 */ 15635 @GuardedBy("this") updateOomAdjPendingTargetsLocked(String oomAdjReason)15636 void updateOomAdjPendingTargetsLocked(String oomAdjReason) { 15637 mOomAdjuster.updateOomAdjPendingTargetsLocked(oomAdjReason); 15638 } 15639 15640 static final class ProcStatsRunnable implements Runnable { 15641 private final ActivityManagerService mService; 15642 private final ProcessStatsService mProcessStats; 15643 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)15644 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) { 15645 this.mService = service; 15646 this.mProcessStats = mProcessStats; 15647 } 15648 run()15649 @Override public void run() { 15650 mProcessStats.writeStateAsync(); 15651 } 15652 } 15653 15654 @GuardedBy("this") updateOomAdjLocked(String oomAdjReason)15655 final void updateOomAdjLocked(String oomAdjReason) { 15656 mOomAdjuster.updateOomAdjLocked(oomAdjReason); 15657 } 15658 15659 /** 15660 * Update OomAdj for a specific process and its reachable processes. 15661 * 15662 * @param app The process to update 15663 * @param oomAdjReason 15664 * @return whether updateOomAdjLocked(app) was successful. 15665 */ 15666 @GuardedBy("this") updateOomAdjLocked(ProcessRecord app, String oomAdjReason)15667 final boolean updateOomAdjLocked(ProcessRecord app, String oomAdjReason) { 15668 return mOomAdjuster.updateOomAdjLocked(app, oomAdjReason); 15669 } 15670 15671 @Override makePackageIdle(String packageName, int userId)15672 public void makePackageIdle(String packageName, int userId) { 15673 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 15674 != PackageManager.PERMISSION_GRANTED) { 15675 String msg = "Permission Denial: makePackageIdle() from pid=" 15676 + Binder.getCallingPid() 15677 + ", uid=" + Binder.getCallingUid() 15678 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 15679 Slog.w(TAG, msg); 15680 throw new SecurityException(msg); 15681 } 15682 final int callingPid = Binder.getCallingPid(); 15683 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 15684 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null); 15685 final long callingId = Binder.clearCallingIdentity(); 15686 try { 15687 IPackageManager pm = AppGlobals.getPackageManager(); 15688 int pkgUid = -1; 15689 try { 15690 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES 15691 | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM); 15692 } catch (RemoteException e) { 15693 } 15694 if (pkgUid == -1) { 15695 throw new IllegalArgumentException("Unknown package name " + packageName); 15696 } 15697 15698 synchronized (this) { 15699 try { 15700 if (mLocalPowerManager != null) { 15701 mLocalPowerManager.startUidChanges(); 15702 } 15703 final int appId = UserHandle.getAppId(pkgUid); 15704 for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; i--) { 15705 final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i); 15706 final long bgTime = uidRec.getLastBackgroundTime(); 15707 if (bgTime > 0 && !uidRec.isIdle()) { 15708 final int uid = uidRec.getUid(); 15709 if (UserHandle.getAppId(uid) == appId) { 15710 if (userId == UserHandle.USER_ALL 15711 || userId == UserHandle.getUserId(uid)) { 15712 EventLogTags.writeAmUidIdle(uid); 15713 synchronized (mProcLock) { 15714 uidRec.setIdle(true); 15715 uidRec.setSetIdle(true); 15716 } 15717 Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uid) 15718 + " from package " + packageName + " user " + userId); 15719 doStopUidLocked(uid, uidRec); 15720 } 15721 } 15722 } 15723 } 15724 } finally { 15725 if (mLocalPowerManager != null) { 15726 mLocalPowerManager.finishUidChanges(); 15727 } 15728 } 15729 } 15730 } finally { 15731 Binder.restoreCallingIdentity(callingId); 15732 } 15733 } 15734 15735 /** Make the currently active UIDs idle after a certain grace period. */ idleUids()15736 final void idleUids() { 15737 synchronized (this) { 15738 mOomAdjuster.idleUidsLocked(); 15739 } 15740 } 15741 runInBackgroundDisabled(int uid)15742 final void runInBackgroundDisabled(int uid) { 15743 synchronized (this) { 15744 UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 15745 if (uidRec != null) { 15746 // This uid is actually running... should it be considered background now? 15747 if (uidRec.isIdle()) { 15748 doStopUidLocked(uidRec.getUid(), uidRec); 15749 } 15750 } else { 15751 // This uid isn't actually running... still send a report about it being "stopped". 15752 doStopUidLocked(uid, null); 15753 } 15754 } 15755 } 15756 cameraActiveChanged(@serIdInt int uid, boolean active)15757 final void cameraActiveChanged(@UserIdInt int uid, boolean active) { 15758 synchronized (mActiveCameraUids) { 15759 final int curIndex = mActiveCameraUids.indexOf(uid); 15760 if (active) { 15761 if (curIndex < 0) { 15762 mActiveCameraUids.add(uid); 15763 } 15764 } else { 15765 if (curIndex >= 0) { 15766 mActiveCameraUids.remove(curIndex); 15767 } 15768 } 15769 } 15770 } 15771 isCameraActiveForUid(@serIdInt int uid)15772 final boolean isCameraActiveForUid(@UserIdInt int uid) { 15773 synchronized (mActiveCameraUids) { 15774 return mActiveCameraUids.indexOf(uid) >= 0; 15775 } 15776 } 15777 15778 @GuardedBy("this") doStopUidLocked(int uid, final UidRecord uidRec)15779 final void doStopUidLocked(int uid, final UidRecord uidRec) { 15780 mServices.stopInBackgroundLocked(uid); 15781 enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE | UidRecord.CHANGE_PROCSTATE); 15782 } 15783 15784 /** 15785 * Allowlists {@code targetUid} to temporarily bypass Power Save mode. 15786 */ 15787 @GuardedBy("this") tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)15788 void tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, 15789 long duration, int type, @ReasonCode int reasonCode, String reason) { 15790 if (DEBUG_ALLOWLISTS) { 15791 Slog.d(TAG, "tempAllowlistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", " 15792 + targetUid + ", " + duration + ", " + type + ")"); 15793 } 15794 15795 synchronized (mPidsSelfLocked) { 15796 final ProcessRecord pr = mPidsSelfLocked.get(callerPid); 15797 if (pr == null) { 15798 Slog.w(TAG, "tempAllowlistForPendingIntentLocked() no ProcessRecord for pid " 15799 + callerPid); 15800 return; 15801 } 15802 if (!pr.mServices.mAllowlistManager) { 15803 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid) 15804 != PackageManager.PERMISSION_GRANTED 15805 && checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callerPid, callerUid) 15806 != PackageManager.PERMISSION_GRANTED 15807 && checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callerPid, 15808 callerUid) != PackageManager.PERMISSION_GRANTED) { 15809 if (DEBUG_ALLOWLISTS) { 15810 Slog.d(TAG, "tempAllowlistForPendingIntentLocked() for target " + targetUid 15811 + ": pid " + callerPid + " is not allowed"); 15812 } 15813 return; 15814 } 15815 } 15816 } 15817 15818 tempAllowlistUidLocked(targetUid, duration, reasonCode, reason, type, callerUid); 15819 } 15820 15821 /** 15822 * Allowlists {@code targetUid} to temporarily bypass Power Save mode. 15823 */ 15824 @GuardedBy("this") tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, String reason, @TempAllowListType int type, int callingUid)15825 void tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, 15826 String reason, @TempAllowListType int type, int callingUid) { 15827 synchronized (mProcLock) { 15828 // The temp allowlist type could change according to the reasonCode. 15829 if (mLocalDeviceIdleController != null) { 15830 type = mLocalDeviceIdleController.getTempAllowListType(reasonCode, type); 15831 } 15832 if (type == TEMPORARY_ALLOW_LIST_TYPE_NONE) { 15833 return; 15834 } 15835 mPendingTempAllowlist.put(targetUid, 15836 new PendingTempAllowlist(targetUid, duration, reasonCode, reason, type, 15837 callingUid)); 15838 setUidTempAllowlistStateLSP(targetUid, true); 15839 mUiHandler.obtainMessage(PUSH_TEMP_ALLOWLIST_UI_MSG).sendToTarget(); 15840 15841 if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) { 15842 mFgsStartTempAllowList.add(targetUid, duration, 15843 new FgsTempAllowListItem(duration, reasonCode, reason, callingUid)); 15844 } 15845 } 15846 } 15847 pushTempAllowlist()15848 void pushTempAllowlist() { 15849 final int N; 15850 final PendingTempAllowlist[] list; 15851 15852 // First copy out the pending changes... we need to leave them in the map for now, 15853 // in case someone needs to check what is coming up while we don't have the lock held. 15854 synchronized (this) { 15855 synchronized (mProcLock) { 15856 N = mPendingTempAllowlist.size(); 15857 list = new PendingTempAllowlist[N]; 15858 for (int i = 0; i < N; i++) { 15859 list[i] = mPendingTempAllowlist.valueAt(i); 15860 } 15861 } 15862 } 15863 15864 // Now safely dispatch changes to device idle controller. Skip this if we're early 15865 // in boot and the controller hasn't yet been brought online: we do not apply 15866 // device idle policy anyway at this phase. 15867 if (mLocalDeviceIdleController != null) { 15868 for (int i = 0; i < N; i++) { 15869 PendingTempAllowlist ptw = list[i]; 15870 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid, 15871 ptw.duration, ptw.type, true, ptw.reasonCode, ptw.tag, 15872 ptw.callingUid); 15873 } 15874 } 15875 15876 // And now we can safely remove them from the map. 15877 synchronized (this) { 15878 synchronized (mProcLock) { 15879 for (int i = 0; i < N; i++) { 15880 PendingTempAllowlist ptw = list[i]; 15881 int index = mPendingTempAllowlist.indexOfKey(ptw.targetUid); 15882 if (index >= 0 && mPendingTempAllowlist.valueAt(index) == ptw) { 15883 mPendingTempAllowlist.removeAt(index); 15884 } 15885 } 15886 } 15887 } 15888 } 15889 15890 @GuardedBy({"this", "mProcLock"}) setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist)15891 final void setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist) { 15892 mOomAdjuster.setAppIdTempAllowlistStateLSP(uid, onAllowlist); 15893 } 15894 15895 @GuardedBy({"this", "mProcLock"}) setUidTempAllowlistStateLSP(int uid, boolean onAllowlist)15896 final void setUidTempAllowlistStateLSP(int uid, boolean onAllowlist) { 15897 mOomAdjuster.setUidTempAllowlistStateLSP(uid, onAllowlist); 15898 } 15899 trimApplications(boolean forceFullOomAdj, String oomAdjReason)15900 private void trimApplications(boolean forceFullOomAdj, String oomAdjReason) { 15901 synchronized (this) { 15902 trimApplicationsLocked(forceFullOomAdj, oomAdjReason); 15903 } 15904 } 15905 15906 @GuardedBy("this") trimApplicationsLocked(boolean forceFullOomAdj, String oomAdjReason)15907 private void trimApplicationsLocked(boolean forceFullOomAdj, String oomAdjReason) { 15908 // First remove any unused application processes whose package 15909 // has been removed. 15910 boolean didSomething = false; 15911 for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) { 15912 final ProcessRecord app = mProcessList.mRemovedProcesses.get(i); 15913 if (!app.hasActivitiesOrRecentTasks() 15914 && app.mReceivers.numberOfCurReceivers() == 0 15915 && app.mServices.numberOfRunningServices() == 0) { 15916 final IApplicationThread thread = app.getThread(); 15917 Slog.i(TAG, "Exiting empty application process " 15918 + app.toShortString() + " (" 15919 + (thread != null ? thread.asBinder() : null) 15920 + ")\n"); 15921 final int pid = app.getPid(); 15922 if (pid > 0 && pid != MY_PID) { 15923 app.killLocked("empty", 15924 ApplicationExitInfo.REASON_OTHER, 15925 ApplicationExitInfo.SUBREASON_TRIM_EMPTY, 15926 false); 15927 } else if (thread != null) { 15928 try { 15929 thread.scheduleExit(); 15930 } catch (Exception e) { 15931 // Ignore exceptions. 15932 } 15933 } 15934 didSomething = true; 15935 cleanUpApplicationRecordLocked(app, pid, false, true, -1, false /*replacingPid*/, 15936 false /* fromBinderDied */); 15937 mProcessList.mRemovedProcesses.remove(i); 15938 15939 if (app.isPersistent()) { 15940 addAppLocked(app.info, null, false, null /* ABI override */, 15941 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 15942 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_PERSISTENT); 15943 } 15944 } 15945 } 15946 15947 // Now update the oom adj for all processes. Don't skip this, since other callers 15948 // might be depending on it. 15949 if (didSomething || forceFullOomAdj) { 15950 updateOomAdjLocked(oomAdjReason); 15951 } else { 15952 // Process any pending oomAdj targets, it'll be a no-op if nothing is pending. 15953 updateOomAdjPendingTargetsLocked(oomAdjReason); 15954 } 15955 } 15956 15957 /** This method sends the specified signal to each of the persistent apps */ signalPersistentProcesses(final int sig)15958 public void signalPersistentProcesses(final int sig) throws RemoteException { 15959 if (sig != SIGNAL_USR1) { 15960 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 15961 } 15962 15963 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 15964 != PackageManager.PERMISSION_GRANTED) { 15965 throw new SecurityException("Requires permission " 15966 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 15967 } 15968 15969 synchronized (mProcLock) { 15970 mProcessList.forEachLruProcessesLOSP(false, app -> { 15971 if (app.getThread() != null && app.isPersistent()) { 15972 sendSignal(app.getPid(), sig); 15973 } 15974 }); 15975 } 15976 } 15977 profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)15978 public boolean profileControl(String process, int userId, boolean start, 15979 ProfilerInfo profilerInfo, int profileType) throws RemoteException { 15980 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 15981 // its own permission. 15982 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 15983 != PackageManager.PERMISSION_GRANTED) { 15984 throw new SecurityException("Requires permission " 15985 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 15986 } 15987 15988 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) { 15989 throw new IllegalArgumentException("null profile info or fd"); 15990 } 15991 15992 ProcessRecord proc = null; 15993 synchronized (mProcLock) { 15994 if (process != null) { 15995 proc = findProcessLOSP(process, userId, "profileControl"); 15996 } 15997 15998 if (start && (proc == null || proc.getThread() == null)) { 15999 throw new IllegalArgumentException("Unknown process: " + process); 16000 } 16001 } 16002 16003 synchronized (mAppProfiler.mProfilerLock) { 16004 return mAppProfiler.profileControlLPf(proc, start, profilerInfo, profileType); 16005 } 16006 } 16007 16008 @GuardedBy(anyOf = {"this", "mProcLock"}) findProcessLOSP(String process, int userId, String callName)16009 private ProcessRecord findProcessLOSP(String process, int userId, String callName) { 16010 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 16011 userId, true, ALLOW_FULL_ONLY, callName, null); 16012 ProcessRecord proc = null; 16013 try { 16014 int pid = Integer.parseInt(process); 16015 synchronized (mPidsSelfLocked) { 16016 proc = mPidsSelfLocked.get(pid); 16017 } 16018 } catch (NumberFormatException e) { 16019 } 16020 16021 if (proc == null) { 16022 ArrayMap<String, SparseArray<ProcessRecord>> all = 16023 mProcessList.getProcessNamesLOSP().getMap(); 16024 SparseArray<ProcessRecord> procs = all.get(process); 16025 if (procs != null && procs.size() > 0) { 16026 proc = procs.valueAt(0); 16027 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 16028 for (int i=1; i<procs.size(); i++) { 16029 ProcessRecord thisProc = procs.valueAt(i); 16030 if (thisProc.userId == userId) { 16031 proc = thisProc; 16032 break; 16033 } 16034 } 16035 } 16036 } 16037 } 16038 16039 return proc; 16040 } 16041 16042 @Override dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)16043 public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, 16044 boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) { 16045 try { 16046 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 16047 // its own permission (same as profileControl). 16048 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 16049 != PackageManager.PERMISSION_GRANTED) { 16050 throw new SecurityException("Requires permission " 16051 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 16052 } 16053 16054 if (fd == null) { 16055 throw new IllegalArgumentException("null fd"); 16056 } 16057 16058 synchronized (this) { 16059 ProcessRecord proc = findProcessLOSP(process, userId, "dumpHeap"); 16060 IApplicationThread thread; 16061 if (proc == null || (thread = proc.getThread()) == null) { 16062 throw new IllegalArgumentException("Unknown process: " + process); 16063 } 16064 16065 enforceDebuggable(proc); 16066 16067 mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 16068 16069 final RemoteCallback intermediateCallback = new RemoteCallback( 16070 new RemoteCallback.OnResultListener() { 16071 @Override 16072 public void onResult(Bundle result) { 16073 finishCallback.sendResult(result); 16074 mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 16075 } 16076 }, null); 16077 16078 thread.dumpHeap(managed, mallocInfo, runGc, path, fd, intermediateCallback); 16079 fd = null; 16080 return true; 16081 } 16082 } catch (RemoteException e) { 16083 throw new IllegalStateException("Process disappeared"); 16084 } finally { 16085 if (fd != null) { 16086 try { 16087 fd.close(); 16088 } catch (IOException e) { 16089 } 16090 } 16091 } 16092 } 16093 16094 /** 16095 * Dump the resources structure for the given process 16096 * 16097 * @param process The process to dump resource info for 16098 * @param fd The FileDescriptor to dump it into 16099 * @throws RemoteException 16100 */ dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback)16101 public boolean dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback) 16102 throws RemoteException { 16103 synchronized (this) { 16104 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_CURRENT, "dumpResources"); 16105 IApplicationThread thread; 16106 if (proc == null || (thread = proc.getThread()) == null) { 16107 throw new IllegalArgumentException("Unknown process: " + process); 16108 } 16109 thread.dumpResources(fd, callback); 16110 return true; 16111 } 16112 } 16113 16114 /** 16115 * Dump the resources structure for all processes 16116 * 16117 * @param fd The FileDescriptor to dump it into 16118 * @throws RemoteException 16119 */ dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw)16120 public void dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw) throws RemoteException { 16121 final ArrayList<ProcessRecord> processes = new ArrayList<>(); 16122 synchronized (mPidsSelfLocked) { 16123 processes.addAll(mProcessList.getLruProcessesLOSP()); 16124 } 16125 for (int i = 0, size = processes.size(); i < size; i++) { 16126 ProcessRecord app = processes.get(i); 16127 pw.println(String.format("Resources History for %s (%s)", 16128 app.processName, 16129 app.info.packageName)); 16130 pw.flush(); 16131 try { 16132 TransferPipe tp = new TransferPipe(" "); 16133 try { 16134 IApplicationThread thread = app.getThread(); 16135 if (thread != null) { 16136 app.getThread().dumpResources(tp.getWriteFd(), null); 16137 tp.go(fd.getFileDescriptor(), 2000); 16138 } else { 16139 pw.println(String.format( 16140 " Resources history for %s (%s) failed, no thread", 16141 app.processName, 16142 app.info.packageName)); 16143 } 16144 } finally { 16145 tp.kill(); 16146 } 16147 } catch (IOException e) { 16148 pw.println(" " + e.getMessage()); 16149 pw.flush(); 16150 } 16151 16152 } 16153 } 16154 16155 @Override setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)16156 public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, 16157 String reportPackage) { 16158 if (processName != null) { 16159 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 16160 "setDumpHeapDebugLimit()"); 16161 } else { 16162 synchronized (mPidsSelfLocked) { 16163 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid()); 16164 if (proc == null) { 16165 throw new SecurityException("No process found for calling pid " 16166 + Binder.getCallingPid()); 16167 } 16168 enforceDebuggable(proc); 16169 processName = proc.processName; 16170 uid = proc.uid; 16171 if (reportPackage != null && !proc.getPkgList().containsKey(reportPackage)) { 16172 throw new SecurityException("Package " + reportPackage + " is not running in " 16173 + proc); 16174 } 16175 } 16176 } 16177 mAppProfiler.setDumpHeapDebugLimit(processName, uid, maxMemSize, reportPackage); 16178 } 16179 16180 @Override dumpHeapFinished(String path)16181 public void dumpHeapFinished(String path) { 16182 mAppProfiler.dumpHeapFinished(path, Binder.getCallingPid()); 16183 } 16184 16185 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ monitor()16186 public void monitor() { 16187 synchronized (this) { } 16188 } 16189 onCoreSettingsChange(Bundle settings)16190 void onCoreSettingsChange(Bundle settings) { 16191 synchronized (mProcLock) { 16192 mProcessList.updateCoreSettingsLOSP(settings); 16193 } 16194 } 16195 16196 // Multi-user methods 16197 16198 /** 16199 * Start user, if its not already running, but don't bring it to foreground. 16200 */ 16201 @Override startUserInBackground(final int userId)16202 public boolean startUserInBackground(final int userId) { 16203 return startUserInBackgroundWithListener(userId, null); 16204 } 16205 16206 @Override startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)16207 public boolean startUserInBackgroundWithListener(final int userId, 16208 @Nullable IProgressListener unlockListener) { 16209 return mUserController.startUser(userId, /* foreground */ false, unlockListener); 16210 } 16211 16212 @Override startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)16213 public boolean startUserInForegroundWithListener(final int userId, 16214 @Nullable IProgressListener unlockListener) { 16215 // Permission check done inside UserController. 16216 return mUserController.startUser(userId, /* foreground */ true, unlockListener); 16217 } 16218 16219 /** 16220 * Unlocks the given user. 16221 * 16222 * @param userId The ID of the user to unlock. 16223 * @param token No longer used. (This parameter cannot be removed because 16224 * this method is marked with UnsupportedAppUsage, so its 16225 * signature might not be safe to change.) 16226 * @param secret The secret needed to unlock the user's credential-encrypted 16227 * storage, or null if no secret is needed. 16228 * @param listener An optional progress listener. 16229 * 16230 * @return true if the user was successfully unlocked, otherwise false. 16231 */ 16232 @Override unlockUser(int userId, @Nullable byte[] token, @Nullable byte[] secret, @Nullable IProgressListener listener)16233 public boolean unlockUser(int userId, @Nullable byte[] token, @Nullable byte[] secret, 16234 @Nullable IProgressListener listener) { 16235 return mUserController.unlockUser(userId, secret, listener); 16236 } 16237 16238 @Override switchUser(final int targetUserId)16239 public boolean switchUser(final int targetUserId) { 16240 return mUserController.switchUser(targetUserId); 16241 } 16242 16243 @Override getSwitchingFromUserMessage()16244 public String getSwitchingFromUserMessage() { 16245 return mUserController.getSwitchingFromSystemUserMessage(); 16246 } 16247 16248 @Override getSwitchingToUserMessage()16249 public String getSwitchingToUserMessage() { 16250 return mUserController.getSwitchingToSystemUserMessage(); 16251 } 16252 16253 @Override setStopUserOnSwitch(@topUserOnSwitch int value)16254 public void setStopUserOnSwitch(@StopUserOnSwitch int value) { 16255 mUserController.setStopUserOnSwitch(value); 16256 } 16257 16258 @Override stopUser(final int userId, boolean force, final IStopUserCallback callback)16259 public int stopUser(final int userId, boolean force, final IStopUserCallback callback) { 16260 return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ false, 16261 /* callback= */ callback, /* keyEvictedCallback= */ null); 16262 } 16263 16264 /** 16265 * Stops user but allow delayed locking. Delayed locking keeps user unlocked even after 16266 * stopping only if {@code config_multiuserDelayUserDataLocking} overlay is set true. 16267 * 16268 * <p>When delayed locking is not enabled through the overlay, this call becomes the same 16269 * with {@link #stopUser(int, boolean, IStopUserCallback)} call. 16270 * 16271 * @param userId User id to stop. 16272 * @param force Force stop the user even if the user is related with system user or current 16273 * user. 16274 * @param callback Callback called when user has stopped. 16275 * 16276 * @return {@link ActivityManager#USER_OP_SUCCESS} when user is stopped successfully. Returns 16277 * other {@code ActivityManager#USER_OP_*} codes for failure. 16278 * 16279 */ 16280 @Override stopUserWithDelayedLocking(final int userId, boolean force, final IStopUserCallback callback)16281 public int stopUserWithDelayedLocking(final int userId, boolean force, 16282 final IStopUserCallback callback) { 16283 return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ true, 16284 /* callback= */ callback, /* keyEvictedCallback= */ null); 16285 } 16286 16287 @Override startProfile(@serIdInt int userId)16288 public boolean startProfile(@UserIdInt int userId) { 16289 return mUserController.startProfile(userId); 16290 } 16291 16292 @Override stopProfile(@serIdInt int userId)16293 public boolean stopProfile(@UserIdInt int userId) { 16294 return mUserController.stopProfile(userId); 16295 } 16296 16297 @Override getCurrentUser()16298 public UserInfo getCurrentUser() { 16299 return mUserController.getCurrentUser(); 16300 } 16301 16302 @Override getCurrentUserId()16303 public @UserIdInt int getCurrentUserId() { 16304 return mUserController.getCurrentUserIdChecked(); 16305 } 16306 getStartedUserState(int userId)16307 String getStartedUserState(int userId) { 16308 final UserState userState = mUserController.getStartedUserState(userId); 16309 return UserState.stateToString(userState.state); 16310 } 16311 16312 @Override isUserRunning(int userId, int flags)16313 public boolean isUserRunning(int userId, int flags) { 16314 if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId()) 16315 && checkCallingPermission(INTERACT_ACROSS_USERS) 16316 != PackageManager.PERMISSION_GRANTED) { 16317 String msg = "Permission Denial: isUserRunning() from pid=" 16318 + Binder.getCallingPid() 16319 + ", uid=" + Binder.getCallingUid() 16320 + " requires " + INTERACT_ACROSS_USERS; 16321 Slog.w(TAG, msg); 16322 throw new SecurityException(msg); 16323 } 16324 return mUserController.isUserRunning(userId, flags); 16325 } 16326 16327 @Override getRunningUserIds()16328 public int[] getRunningUserIds() { 16329 if (checkCallingPermission(INTERACT_ACROSS_USERS) 16330 != PackageManager.PERMISSION_GRANTED) { 16331 String msg = "Permission Denial: isUserRunning() from pid=" 16332 + Binder.getCallingPid() 16333 + ", uid=" + Binder.getCallingUid() 16334 + " requires " + INTERACT_ACROSS_USERS; 16335 Slog.w(TAG, msg); 16336 throw new SecurityException(msg); 16337 } 16338 return mUserController.getStartedUserArray(); 16339 } 16340 16341 @Override registerUserSwitchObserver(IUserSwitchObserver observer, String name)16342 public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) { 16343 mUserController.registerUserSwitchObserver(observer, name); 16344 } 16345 16346 @Override unregisterUserSwitchObserver(IUserSwitchObserver observer)16347 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 16348 mUserController.unregisterUserSwitchObserver(observer); 16349 } 16350 getAppInfoForUser(ApplicationInfo info, int userId)16351 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 16352 if (info == null) return null; 16353 ApplicationInfo newInfo = new ApplicationInfo(info); 16354 newInfo.initForUser(userId); 16355 return newInfo; 16356 } 16357 isUserStopped(int userId)16358 public boolean isUserStopped(int userId) { 16359 return mUserController.getStartedUserState(userId) == null; 16360 } 16361 getActivityInfoForUser(ActivityInfo aInfo, int userId)16362 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 16363 if (aInfo == null 16364 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 16365 return aInfo; 16366 } 16367 16368 ActivityInfo info = new ActivityInfo(aInfo); 16369 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 16370 return info; 16371 } 16372 16373 @GuardedBy("mProcLock") processSanityChecksLPr(ProcessRecord process, IApplicationThread thread)16374 private boolean processSanityChecksLPr(ProcessRecord process, IApplicationThread thread) { 16375 if (process == null || thread == null) { 16376 return false; 16377 } 16378 16379 return Build.IS_DEBUGGABLE || process.isDebuggable(); 16380 } 16381 startBinderTracking()16382 public boolean startBinderTracking() throws RemoteException { 16383 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 16384 // permission (same as profileControl). 16385 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 16386 != PackageManager.PERMISSION_GRANTED) { 16387 throw new SecurityException("Requires permission " 16388 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 16389 } 16390 16391 synchronized (mProcLock) { 16392 mBinderTransactionTrackingEnabled = true; 16393 mProcessList.forEachLruProcessesLOSP(true, process -> { 16394 final IApplicationThread thread = process.getThread(); 16395 if (!processSanityChecksLPr(process, thread)) { 16396 return; 16397 } 16398 try { 16399 thread.startBinderTracking(); 16400 } catch (RemoteException e) { 16401 Log.v(TAG, "Process disappared"); 16402 } 16403 }); 16404 } 16405 return true; 16406 } 16407 16408 @Override stopBinderTrackingAndDump(final ParcelFileDescriptor fd)16409 public boolean stopBinderTrackingAndDump(final ParcelFileDescriptor fd) throws RemoteException { 16410 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 16411 // permission (same as profileControl). 16412 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 16413 != PackageManager.PERMISSION_GRANTED) { 16414 throw new SecurityException("Requires permission " 16415 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 16416 } 16417 16418 boolean closeFd = true; 16419 try { 16420 synchronized (mProcLock) { 16421 if (fd == null) { 16422 throw new IllegalArgumentException("null fd"); 16423 } 16424 mBinderTransactionTrackingEnabled = false; 16425 16426 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor())); 16427 pw.println("Binder transaction traces for all processes.\n"); 16428 mProcessList.forEachLruProcessesLOSP(true, process -> { 16429 final IApplicationThread thread = process.getThread(); 16430 if (!processSanityChecksLPr(process, thread)) { 16431 return; 16432 } 16433 16434 pw.println("Traces for process: " + process.processName); 16435 pw.flush(); 16436 try { 16437 TransferPipe tp = new TransferPipe(); 16438 try { 16439 thread.stopBinderTrackingAndDump(tp.getWriteFd()); 16440 tp.go(fd.getFileDescriptor()); 16441 } finally { 16442 tp.kill(); 16443 } 16444 } catch (IOException e) { 16445 pw.println("Failure while dumping IPC traces from " + process + 16446 ". Exception: " + e); 16447 pw.flush(); 16448 } catch (RemoteException e) { 16449 pw.println("Got a RemoteException while dumping IPC traces from " + 16450 process + ". Exception: " + e); 16451 pw.flush(); 16452 } 16453 }); 16454 closeFd = false; 16455 return true; 16456 } 16457 } finally { 16458 if (fd != null && closeFd) { 16459 try { 16460 fd.close(); 16461 } catch (IOException e) { 16462 } 16463 } 16464 } 16465 } 16466 16467 @Override enableBinderTracing()16468 public void enableBinderTracing() { 16469 Binder.enableTracingForUid(Binder.getCallingUid()); 16470 } 16471 16472 @VisibleForTesting 16473 public final class LocalService extends ActivityManagerInternal 16474 implements ActivityManagerLocal { 16475 16476 @Override getPendingIntentStats()16477 public List<PendingIntentStats> getPendingIntentStats() { 16478 return mPendingIntentController.dumpPendingIntentStatsForStatsd(); 16479 } 16480 16481 @Override getAppProfileStatsForDebugging(long time, int lines)16482 public Pair<String, String> getAppProfileStatsForDebugging(long time, int lines) { 16483 return mAppProfiler.getAppProfileStatsForDebugging(time, lines); 16484 } 16485 16486 @Override checkContentProviderAccess(String authority, int userId)16487 public String checkContentProviderAccess(String authority, int userId) { 16488 return mCpHelper.checkContentProviderAccess(authority, userId); 16489 } 16490 16491 @Override checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)16492 public int checkContentProviderUriPermission(Uri uri, int userId, 16493 int callingUid, int modeFlags) { 16494 return mCpHelper.checkContentProviderUriPermission(uri, userId, callingUid, modeFlags); 16495 } 16496 16497 @Override onWakefulnessChanged(int wakefulness)16498 public void onWakefulnessChanged(int wakefulness) { 16499 ActivityManagerService.this.onWakefulnessChanged(wakefulness); 16500 } 16501 16502 @Override startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)16503 public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 16504 String processName, String abiOverride, int uid, Runnable crashHandler) { 16505 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 16506 processName, abiOverride, uid, crashHandler); 16507 } 16508 16509 @Override bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, String clientAppPackage, String processName, int flags)16510 public boolean bindSdkSandboxService(Intent service, ServiceConnection conn, 16511 int clientAppUid, String clientAppPackage, String processName, int flags) 16512 throws RemoteException { 16513 if (service == null) { 16514 throw new IllegalArgumentException("intent is null"); 16515 } 16516 if (conn == null) { 16517 throw new IllegalArgumentException("connection is null"); 16518 } 16519 if (clientAppPackage == null) { 16520 throw new IllegalArgumentException("clientAppPackage is null"); 16521 } 16522 if (processName == null) { 16523 throw new IllegalArgumentException("processName is null"); 16524 } 16525 if (service.getComponent() == null) { 16526 throw new IllegalArgumentException("service must specify explicit component"); 16527 } 16528 if (!UserHandle.isApp(clientAppUid)) { 16529 throw new IllegalArgumentException("uid is not within application range"); 16530 } 16531 if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) != MODE_ALLOWED) { 16532 throw new IllegalArgumentException("uid does not belong to provided package"); 16533 } 16534 16535 Handler handler = mContext.getMainThreadHandler(); 16536 16537 final IServiceConnection sd = mContext.getServiceDispatcher(conn, handler, flags); 16538 service.prepareToLeaveProcess(mContext); 16539 return ActivityManagerService.this.bindServiceInstance( 16540 mContext.getIApplicationThread(), mContext.getActivityToken(), service, 16541 service.resolveTypeIfNeeded(mContext.getContentResolver()), sd, flags, 16542 processName, /*isSdkSandboxService*/ true, clientAppUid, clientAppPackage, 16543 mContext.getOpPackageName(), UserHandle.getUserId(clientAppUid)) != 0; 16544 } 16545 16546 @Override onUserRemoved(@serIdInt int userId)16547 public void onUserRemoved(@UserIdInt int userId) { 16548 // Clean up any ActivityTaskManager state (by telling it the user is stopped) 16549 mAtmInternal.onUserStopped(userId); 16550 // Clean up various services by removing the user 16551 mBatteryStatsService.onUserRemoved(userId); 16552 mUserController.onUserRemoved(userId); 16553 } 16554 16555 @Override killForegroundAppsForUser(@serIdInt int userId)16556 public void killForegroundAppsForUser(@UserIdInt int userId) { 16557 final ArrayList<ProcessRecord> procs = new ArrayList<>(); 16558 synchronized (mProcLock) { 16559 final int numOfProcs = mProcessList.getProcessNamesLOSP().getMap().size(); 16560 for (int ip = 0; ip < numOfProcs; ip++) { 16561 final SparseArray<ProcessRecord> apps = 16562 mProcessList.getProcessNamesLOSP().getMap().valueAt(ip); 16563 final int NA = apps.size(); 16564 for (int ia = 0; ia < NA; ia++) { 16565 final ProcessRecord app = apps.valueAt(ia); 16566 if (app.isPersistent()) { 16567 // We don't kill persistent processes. 16568 continue; 16569 } 16570 if (app.isRemoved() 16571 || (app.userId == userId && app.mState.hasForegroundActivities())) { 16572 procs.add(app); 16573 } 16574 } 16575 } 16576 } 16577 16578 final int numOfProcs = procs.size(); 16579 if (numOfProcs > 0) { 16580 synchronized (ActivityManagerService.this) { 16581 for (int i = 0; i < numOfProcs; i++) { 16582 mProcessList.removeProcessLocked(procs.get(i), false, true, 16583 ApplicationExitInfo.REASON_OTHER, 16584 ApplicationExitInfo.SUBREASON_KILL_ALL_FG, 16585 "kill all fg"); 16586 } 16587 } 16588 } 16589 } 16590 16591 @Override setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, int type, @ReasonCode int reasonCode, @Nullable String reason)16592 public void setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, 16593 long duration, int type, @ReasonCode int reasonCode, @Nullable String reason) { 16594 mPendingIntentController.setPendingIntentAllowlistDuration(target, allowlistToken, 16595 duration, type, reasonCode, reason); 16596 } 16597 16598 @Override getPendingIntentFlags(IIntentSender target)16599 public int getPendingIntentFlags(IIntentSender target) { 16600 return mPendingIntentController.getPendingIntentFlags(target); 16601 } 16602 16603 @Override getStartedUserIds()16604 public int[] getStartedUserIds() { 16605 return mUserController.getStartedUserArray(); 16606 } 16607 16608 @Override setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken, int flags)16609 public void setPendingIntentAllowBgActivityStarts(IIntentSender target, 16610 IBinder allowlistToken, int flags) { 16611 if (!(target instanceof PendingIntentRecord)) { 16612 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():" 16613 + " not a PendingIntentRecord: " + target); 16614 return; 16615 } 16616 synchronized (ActivityManagerService.this) { 16617 ((PendingIntentRecord) target).setAllowBgActivityStarts(allowlistToken, flags); 16618 } 16619 } 16620 16621 @Override clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)16622 public void clearPendingIntentAllowBgActivityStarts(IIntentSender target, 16623 IBinder allowlistToken) { 16624 if (!(target instanceof PendingIntentRecord)) { 16625 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():" 16626 + " not a PendingIntentRecord: " + target); 16627 return; 16628 } 16629 synchronized (ActivityManagerService.this) { 16630 ((PendingIntentRecord) target).clearAllowBgActivityStarts(allowlistToken); 16631 } 16632 } 16633 16634 @Override setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)16635 public void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids) { 16636 synchronized (ActivityManagerService.this) { 16637 synchronized (mProcLock) { 16638 mDeviceIdleAllowlist = allAppids; 16639 mDeviceIdleExceptIdleAllowlist = exceptIdleAppids; 16640 mAppRestrictionController.setDeviceIdleAllowlist(allAppids, exceptIdleAppids); 16641 } 16642 } 16643 } 16644 16645 @Override updateDeviceIdleTempAllowlist(@ullable int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)16646 public void updateDeviceIdleTempAllowlist(@Nullable int[] appids, int changingUid, 16647 boolean adding, long durationMs, @TempAllowListType int type, 16648 @ReasonCode int reasonCode, @Nullable String reason, int callingUid) { 16649 synchronized (ActivityManagerService.this) { 16650 synchronized (mProcLock) { 16651 if (appids != null) { 16652 mDeviceIdleTempAllowlist = appids; 16653 } 16654 if (adding) { 16655 if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) { 16656 // Note, the device idle temp-allowlist are by app-ids, but here 16657 // mFgsStartTempAllowList contains UIDs. 16658 mFgsStartTempAllowList.add(changingUid, durationMs, 16659 new FgsTempAllowListItem(durationMs, reasonCode, reason, 16660 callingUid)); 16661 } 16662 } else { 16663 mFgsStartTempAllowList.removeUid(changingUid); 16664 } 16665 setAppIdTempAllowlistStateLSP(changingUid, adding); 16666 } 16667 } 16668 } 16669 16670 @Override getUidProcessState(int uid)16671 public int getUidProcessState(int uid) { 16672 return getUidState(uid); 16673 } 16674 16675 @Override getProcessesWithPendingBindMounts(int userId)16676 public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) { 16677 return mProcessList.getProcessesWithPendingBindMounts(userId); 16678 } 16679 16680 @Override isSystemReady()16681 public boolean isSystemReady() { 16682 // no need to synchronize(this) just to read & return the value 16683 return mSystemReady; 16684 } 16685 16686 /** 16687 * Returns package name by pid. 16688 */ 16689 @Override 16690 @Nullable getPackageNameByPid(int pid)16691 public String getPackageNameByPid(int pid) { 16692 synchronized (mPidsSelfLocked) { 16693 final ProcessRecord app = mPidsSelfLocked.get(pid); 16694 16695 if (app != null && app.info != null) { 16696 return app.info.packageName; 16697 } 16698 16699 return null; 16700 } 16701 } 16702 16703 /** 16704 * Sets if the given pid has an overlay UI or not. 16705 * 16706 * @param pid The pid we are setting overlay UI for. 16707 * @param hasOverlayUi True if the process has overlay UI. 16708 * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY 16709 */ 16710 @Override setHasOverlayUi(int pid, boolean hasOverlayUi)16711 public void setHasOverlayUi(int pid, boolean hasOverlayUi) { 16712 synchronized (ActivityManagerService.this) { 16713 final ProcessRecord pr; 16714 synchronized (mPidsSelfLocked) { 16715 pr = mPidsSelfLocked.get(pid); 16716 if (pr == null) { 16717 Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid); 16718 return; 16719 } 16720 } 16721 if (pr.mState.hasOverlayUi() == hasOverlayUi) { 16722 return; 16723 } 16724 pr.mState.setHasOverlayUi(hasOverlayUi); 16725 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid); 16726 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 16727 } 16728 } 16729 16730 /** 16731 * Called after the network policy rules are updated by 16732 * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid} 16733 * and {@param procStateSeq}. 16734 */ 16735 @Override notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)16736 public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) { 16737 if (DEBUG_NETWORK) { 16738 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: " 16739 + uid + " seq: " + procStateSeq); 16740 } 16741 UidRecord record; 16742 synchronized (mProcLock) { 16743 record = mProcessList.getUidRecordLOSP(uid); 16744 if (record == null) { 16745 if (DEBUG_NETWORK) { 16746 Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid 16747 + " procStateSeq: " + procStateSeq); 16748 } 16749 return; 16750 } 16751 } 16752 synchronized (record.networkStateLock) { 16753 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 16754 if (DEBUG_NETWORK) { 16755 Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already" 16756 + " been handled for uid: " + uid); 16757 } 16758 return; 16759 } 16760 record.lastNetworkUpdatedProcStateSeq = procStateSeq; 16761 if (record.procStateSeqWaitingForNetwork != 0 16762 && procStateSeq >= record.procStateSeqWaitingForNetwork) { 16763 if (DEBUG_NETWORK) { 16764 Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid 16765 + ", procStateSeq: " + procStateSeq 16766 + ", procStateSeqWaitingForNetwork: " 16767 + record.procStateSeqWaitingForNetwork); 16768 } 16769 record.networkStateLock.notifyAll(); 16770 } 16771 } 16772 } 16773 16774 @Override onUidBlockedReasonsChanged(int uid, int blockedReasons)16775 public void onUidBlockedReasonsChanged(int uid, int blockedReasons) { 16776 synchronized (mUidNetworkBlockedReasons) { 16777 if (blockedReasons == BLOCKED_REASON_NONE) { 16778 mUidNetworkBlockedReasons.delete(uid); 16779 } else { 16780 mUidNetworkBlockedReasons.put(uid, blockedReasons); 16781 } 16782 } 16783 } 16784 16785 @Override isRuntimeRestarted()16786 public boolean isRuntimeRestarted() { 16787 return mSystemServiceManager.isRuntimeRestarted(); 16788 } 16789 16790 @Override canStartMoreUsers()16791 public boolean canStartMoreUsers() { 16792 return mUserController.canStartMoreUsers(); 16793 } 16794 16795 @Override setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)16796 public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) { 16797 mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage); 16798 } 16799 16800 @Override setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)16801 public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) { 16802 mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage); 16803 } 16804 16805 @Override getMaxRunningUsers()16806 public int getMaxRunningUsers() { 16807 return mUserController.getMaxRunningUsers(); 16808 } 16809 16810 @Override isUidActive(int uid)16811 public boolean isUidActive(int uid) { 16812 synchronized (mProcLock) { 16813 return isUidActiveLOSP(uid); 16814 } 16815 } 16816 16817 @Override getMemoryStateForProcesses()16818 public List<ProcessMemoryState> getMemoryStateForProcesses() { 16819 List<ProcessMemoryState> processMemoryStates = new ArrayList<>(); 16820 synchronized (mPidsSelfLocked) { 16821 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 16822 final ProcessRecord r = mPidsSelfLocked.valueAt(i); 16823 processMemoryStates.add(new ProcessMemoryState( 16824 r.uid, r.getPid(), r.processName, r.mState.getCurAdj(), 16825 r.mServices.hasForegroundServices())); 16826 } 16827 } 16828 return processMemoryStates; 16829 } 16830 16831 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)16832 public int handleIncomingUser(int callingPid, int callingUid, int userId, 16833 boolean allowAll, int allowMode, String name, String callerPackage) { 16834 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 16835 allowMode, name, callerPackage); 16836 } 16837 16838 @Override enforceCallingPermission(String permission, String func)16839 public void enforceCallingPermission(String permission, String func) { 16840 ActivityManagerService.this.enforceCallingPermission(permission, func); 16841 } 16842 16843 @Override getCurrentUserId()16844 public int getCurrentUserId() { 16845 return mUserController.getCurrentUserId(); 16846 } 16847 16848 @Override isUserRunning(int userId, int flags)16849 public boolean isUserRunning(int userId, int flags) { 16850 // Holding am lock isn't required to call into user controller. 16851 return mUserController.isUserRunning(userId, flags); 16852 } 16853 16854 @Override trimApplications()16855 public void trimApplications() { 16856 ActivityManagerService.this.trimApplications(true, OomAdjuster.OOM_ADJ_REASON_ACTIVITY); 16857 } 16858 killProcessesForRemovedTask(ArrayList<Object> procsToKill)16859 public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) { 16860 synchronized (ActivityManagerService.this) { 16861 for (int i = 0; i < procsToKill.size(); i++) { 16862 final WindowProcessController wpc = 16863 (WindowProcessController) procsToKill.get(i); 16864 final ProcessRecord pr = (ProcessRecord) wpc.mOwner; 16865 if (pr.mState.getSetSchedGroup() == ProcessList.SCHED_GROUP_BACKGROUND 16866 && pr.mReceivers.numberOfCurReceivers() == 0) { 16867 pr.killLocked("remove task", ApplicationExitInfo.REASON_USER_REQUESTED, 16868 ApplicationExitInfo.SUBREASON_REMOVE_TASK, true); 16869 } else { 16870 // We delay killing processes that are not in the background or running a 16871 // receiver. 16872 pr.setWaitingToKill("remove task"); 16873 } 16874 } 16875 } 16876 } 16877 16878 @Override killProcess(String processName, int uid, String reason)16879 public void killProcess(String processName, int uid, String reason) { 16880 synchronized (ActivityManagerService.this) { 16881 final ProcessRecord proc = getProcessRecordLocked(processName, uid); 16882 if (proc != null) { 16883 mProcessList.removeProcessLocked(proc, false /* callerWillRestart */, 16884 true /* allowRestart */, ApplicationExitInfo.REASON_OTHER, reason); 16885 } 16886 } 16887 } 16888 16889 @Override hasRunningActivity(int uid, @Nullable String packageName)16890 public boolean hasRunningActivity(int uid, @Nullable String packageName) { 16891 if (packageName == null) return false; 16892 16893 synchronized (mProcLock) { 16894 return mProcessList.searchEachLruProcessesLOSP(true, app -> { 16895 if (app.uid == uid 16896 && app.getWindowProcessController().hasRunningActivity(packageName)) { 16897 return Boolean.TRUE; 16898 } 16899 return null; 16900 }) != null; 16901 } 16902 } 16903 16904 @Override updateOomAdj()16905 public void updateOomAdj() { 16906 synchronized (ActivityManagerService.this) { 16907 ActivityManagerService.this.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 16908 } 16909 } 16910 16911 @Override updateCpuStats()16912 public void updateCpuStats() { 16913 ActivityManagerService.this.updateCpuStats(); 16914 } 16915 16916 @Override updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)16917 public void updateBatteryStats(ComponentName activity, int uid, int userId, 16918 boolean resumed) { 16919 ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed); 16920 } 16921 16922 @Override updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)16923 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 16924 IBinder appToken, ComponentName taskRoot) { 16925 ActivityManagerService.this.updateActivityUsageStats(activity, userId, event, 16926 appToken, taskRoot); 16927 } 16928 16929 @Override updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)16930 public void updateForegroundTimeIfOnBattery( 16931 String packageName, int uid, long cpuTimeDiff) { 16932 mBatteryStatsService.updateForegroundTimeIfOnBattery(packageName, uid, cpuTimeDiff); 16933 } 16934 16935 @Override sendForegroundProfileChanged(int userId)16936 public void sendForegroundProfileChanged(int userId) { 16937 mUserController.sendForegroundProfileChanged(userId); 16938 } 16939 16940 @Override shouldConfirmCredentials(int userId)16941 public boolean shouldConfirmCredentials(int userId) { 16942 return mUserController.shouldConfirmCredentials(userId); 16943 } 16944 16945 @Override noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)16946 public void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, 16947 String tag) { 16948 ActivityManagerService.this.noteAlarmFinish((ps != null) ? ps.getTarget() : null, 16949 workSource, sourceUid, tag); 16950 } 16951 16952 @Override noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)16953 public void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, 16954 String tag) { 16955 ActivityManagerService.this.noteAlarmStart((ps != null) ? ps.getTarget() : null, 16956 workSource, sourceUid, tag); 16957 } 16958 16959 @Override noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)16960 public void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, 16961 String sourcePkg, String tag) { 16962 ActivityManagerService.this.noteWakeupAlarm((ps != null) ? ps.getTarget() : null, 16963 workSource, sourceUid, sourcePkg, tag); 16964 } 16965 16966 @Override isAppStartModeDisabled(int uid, String packageName)16967 public boolean isAppStartModeDisabled(int uid, String packageName) { 16968 return ActivityManagerService.this.isAppStartModeDisabled(uid, packageName); 16969 } 16970 16971 @Override getCurrentProfileIds()16972 public int[] getCurrentProfileIds() { 16973 return mUserController.getCurrentProfileIds(); 16974 } 16975 16976 @Override getCurrentUser()16977 public UserInfo getCurrentUser() { 16978 return mUserController.getCurrentUser(); 16979 } 16980 16981 @Override ensureNotSpecialUser(int userId)16982 public void ensureNotSpecialUser(int userId) { 16983 mUserController.ensureNotSpecialUser(userId); 16984 } 16985 16986 @Override isCurrentProfile(int userId)16987 public boolean isCurrentProfile(int userId) { 16988 return mUserController.isCurrentProfile(userId); 16989 } 16990 16991 @Override hasStartedUserState(int userId)16992 public boolean hasStartedUserState(int userId) { 16993 return mUserController.hasStartedUserState(userId); 16994 } 16995 16996 @Override finishUserSwitch(Object uss)16997 public void finishUserSwitch(Object uss) { 16998 mUserController.finishUserSwitch((UserState) uss); 16999 } 17000 17001 @Override scheduleAppGcs()17002 public void scheduleAppGcs() { 17003 synchronized (mAppProfiler.mProfilerLock) { 17004 mAppProfiler.scheduleAppGcsLPf(); 17005 } 17006 } 17007 17008 @Override getTaskIdForActivity(IBinder token, boolean onlyRoot)17009 public int getTaskIdForActivity(IBinder token, boolean onlyRoot) { 17010 return ActivityManagerService.this.getTaskForActivity(token, onlyRoot); 17011 } 17012 17013 @Override getActivityPresentationInfo(IBinder token)17014 public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) { 17015 final ActivityClient ac = ActivityClient.getInstance(); 17016 return new ActivityPresentationInfo(ac.getTaskForActivity(token, 17017 /*onlyRoot=*/ false), ac.getDisplayId(token), 17018 mAtmInternal.getActivityName(token)); 17019 } 17020 17021 @Override setBooting(boolean booting)17022 public void setBooting(boolean booting) { 17023 mBooting = booting; 17024 } 17025 17026 @Override isBooting()17027 public boolean isBooting() { 17028 return mBooting; 17029 } 17030 17031 @Override setBooted(boolean booted)17032 public void setBooted(boolean booted) { 17033 mBooted = booted; 17034 } 17035 17036 @Override isBooted()17037 public boolean isBooted() { 17038 return mBooted; 17039 } 17040 17041 @Override finishBooting()17042 public void finishBooting() { 17043 ActivityManagerService.this.finishBooting(); 17044 } 17045 17046 @Override tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)17047 public void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, 17048 long duration, int type, @ReasonCode int reasonCode, String reason) { 17049 synchronized (ActivityManagerService.this) { 17050 ActivityManagerService.this.tempAllowlistForPendingIntentLocked( 17051 callerPid, callerUid, targetUid, duration, type, reasonCode, reason); 17052 } 17053 } 17054 17055 @Override broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken, @Nullable int[] broadcastAllowList)17056 public int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, 17057 int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 17058 IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, 17059 String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, 17060 int userId, boolean allowBackgroundActivityStarts, 17061 @Nullable IBinder backgroundActivityStartsToken, 17062 @Nullable int[] broadcastAllowList) { 17063 synchronized (ActivityManagerService.this) { 17064 return ActivityManagerService.this.broadcastIntentInPackage(packageName, featureId, 17065 uid, realCallingUid, realCallingPid, intent, resolvedType, resultTo, 17066 resultCode, resultData, resultExtras, requiredPermission, bOptions, 17067 serialized, sticky, userId, allowBackgroundActivityStarts, 17068 backgroundActivityStartsToken, broadcastAllowList); 17069 } 17070 } 17071 17072 @Override broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable Bundle bOptions)17073 public int broadcastIntent(Intent intent, 17074 IIntentReceiver resultTo, 17075 String[] requiredPermissions, 17076 boolean serialized, int userId, int[] appIdAllowList, @Nullable Bundle bOptions) { 17077 synchronized (ActivityManagerService.this) { 17078 intent = verifyBroadcastLocked(intent); 17079 17080 final int callingPid = Binder.getCallingPid(); 17081 final int callingUid = Binder.getCallingUid(); 17082 final long origId = Binder.clearCallingIdentity(); 17083 try { 17084 return ActivityManagerService.this.broadcastIntentLocked(null /*callerApp*/, 17085 null /*callerPackage*/, null /*callingFeatureId*/, intent, 17086 null /*resolvedType*/, resultTo, 0 /*resultCode*/, null /*resultData*/, 17087 null /*resultExtras*/, requiredPermissions, 17088 null /*excludedPermissions*/, null /*excludedPackages*/, 17089 AppOpsManager.OP_NONE, bOptions /*options*/, serialized, 17090 false /*sticky*/, callingPid, callingUid, callingUid, callingPid, 17091 userId, false /*allowBackgroundStarts*/, 17092 null /*tokenNeededForBackgroundActivityStarts*/, appIdAllowList); 17093 } finally { 17094 Binder.restoreCallingIdentity(origId); 17095 } 17096 } 17097 17098 } 17099 17100 @Override startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)17101 public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType, 17102 boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, 17103 int userId, boolean allowBackgroundActivityStarts, 17104 @Nullable IBinder backgroundActivityStartsToken) 17105 throws TransactionTooLargeException { 17106 synchronized(ActivityManagerService.this) { 17107 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 17108 "startServiceInPackage: " + service + " type=" + resolvedType); 17109 final long origId = Binder.clearCallingIdentity(); 17110 ComponentName res; 17111 try { 17112 res = mServices.startServiceLocked(null, service, 17113 resolvedType, -1, uid, fgRequired, callingPackage, 17114 callingFeatureId, userId, allowBackgroundActivityStarts, 17115 backgroundActivityStartsToken); 17116 } finally { 17117 Binder.restoreCallingIdentity(origId); 17118 } 17119 return res; 17120 } 17121 } 17122 17123 // The arguments here are untyped because the base ActivityManagerInternal class 17124 // doesn't have compile-time visibility into ActivityServiceConnectionHolder or 17125 // ConnectionRecord. 17126 @Override disconnectActivityFromServices(Object connectionHolder)17127 public void disconnectActivityFromServices(Object connectionHolder) { 17128 // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder 17129 final ActivityServiceConnectionsHolder holder = 17130 (ActivityServiceConnectionsHolder) connectionHolder; 17131 synchronized (ActivityManagerService.this) { 17132 synchronized (mProcLock) { 17133 holder.forEachConnection(cr -> mServices.removeConnectionLocked( 17134 (ConnectionRecord) cr, null /* skipApp */, holder /* skipAct */, 17135 false /* enqueueOomAdj */)); 17136 } 17137 } 17138 } 17139 cleanUpServices(int userId, ComponentName component, Intent baseIntent)17140 public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) { 17141 synchronized(ActivityManagerService.this) { 17142 mServices.cleanUpServices(userId, component, baseIntent); 17143 } 17144 } 17145 getActivityInfoForUser(ActivityInfo aInfo, int userId)17146 public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 17147 // Locked intentionally not held as it isn't needed for this case. 17148 return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId); 17149 } 17150 ensureBootCompleted()17151 public void ensureBootCompleted() { 17152 // Locked intentionally not held as it isn't needed for this case. 17153 ActivityManagerService.this.ensureBootCompleted(); 17154 } 17155 updateOomLevelsForDisplay(int displayId)17156 public void updateOomLevelsForDisplay(int displayId) { 17157 synchronized(ActivityManagerService.this) { 17158 if (mWindowManager != null) { 17159 mProcessList.applyDisplaySize(mWindowManager); 17160 } 17161 } 17162 } 17163 isActivityStartsLoggingEnabled()17164 public boolean isActivityStartsLoggingEnabled() { 17165 return mConstants.mFlagActivityStartsLoggingEnabled; 17166 } 17167 isBackgroundActivityStartsEnabled()17168 public boolean isBackgroundActivityStartsEnabled() { 17169 return mConstants.mFlagBackgroundActivityStartsEnabled; 17170 } 17171 reportCurKeyguardUsageEvent(boolean keyguardShowing)17172 public void reportCurKeyguardUsageEvent(boolean keyguardShowing) { 17173 ActivityManagerService.this.reportGlobalUsageEvent(keyguardShowing 17174 ? UsageEvents.Event.KEYGUARD_SHOWN 17175 : UsageEvents.Event.KEYGUARD_HIDDEN); 17176 } 17177 17178 @Override monitor()17179 public void monitor() { 17180 ActivityManagerService.this.monitor(); 17181 } 17182 17183 @Override inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason)17184 public long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason) { 17185 return ActivityManagerService.this.inputDispatchingTimedOut(pid, aboveSystem, reason); 17186 } 17187 17188 @Override inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, String reason)17189 public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName, 17190 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, 17191 boolean aboveSystem, String reason) { 17192 return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc, 17193 activityShortComponentName, aInfo, parentShortComponentName, 17194 (WindowProcessController) parentProc, aboveSystem, reason); 17195 17196 } 17197 17198 @Override inputDispatchingResumed(int pid)17199 public void inputDispatchingResumed(int pid) { 17200 final ProcessRecord proc; 17201 synchronized (mPidsSelfLocked) { 17202 proc = mPidsSelfLocked.get(pid); 17203 } 17204 if (proc != null) { 17205 mAppErrors.handleDismissAnrDialogs(proc); 17206 } 17207 } 17208 17209 @Override rescheduleAnrDialog(Object data)17210 public void rescheduleAnrDialog(Object data) { 17211 Message msg = Message.obtain(); 17212 msg.what = SHOW_NOT_RESPONDING_UI_MSG; 17213 msg.obj = (AppNotRespondingDialog.Data) data; 17214 17215 mUiHandler.sendMessageDelayed(msg, InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS); 17216 } 17217 17218 @Override broadcastGlobalConfigurationChanged(int changes, boolean initLocale)17219 public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) { 17220 synchronized (ActivityManagerService.this) { 17221 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 17222 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17223 | Intent.FLAG_RECEIVER_REPLACE_PENDING 17224 | Intent.FLAG_RECEIVER_FOREGROUND 17225 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 17226 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 17227 null, null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID, 17228 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 17229 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) { 17230 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 17231 intent.addFlags(Intent.FLAG_RECEIVER_OFFLOAD_FOREGROUND 17232 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND 17233 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 17234 if (initLocale || !mProcessesReady) { 17235 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 17236 } 17237 final BroadcastOptions bOptions = BroadcastOptions.makeBasic(); 17238 bOptions.setTemporaryAppAllowlist(mInternal.getBootTimeTempAllowListDuration(), 17239 TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED, 17240 PowerExemptionManager.REASON_LOCALE_CHANGED, ""); 17241 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 17242 null, null, OP_NONE, bOptions.toBundle(), false, false, MY_PID, 17243 SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(), 17244 UserHandle.USER_ALL); 17245 } 17246 17247 // Send a broadcast to PackageInstallers if the configuration change is interesting 17248 // for the purposes of installing additional splits. 17249 if (!initLocale && isSplitConfigurationChange(changes)) { 17250 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED); 17251 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING 17252 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 17253 17254 // Typically only app stores will have this permission. 17255 String[] permissions = 17256 new String[] { android.Manifest.permission.INSTALL_PACKAGES }; 17257 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, 17258 permissions, null, null, OP_NONE, null, false, false, MY_PID, 17259 SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(), 17260 UserHandle.USER_ALL); 17261 } 17262 } 17263 } 17264 17265 /** 17266 * Returns true if this configuration change is interesting enough to send an 17267 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast. 17268 */ isSplitConfigurationChange(int configDiff)17269 private boolean isSplitConfigurationChange(int configDiff) { 17270 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0; 17271 } 17272 17273 @Override broadcastCloseSystemDialogs(String reason)17274 public void broadcastCloseSystemDialogs(String reason) { 17275 synchronized (ActivityManagerService.this) { 17276 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 17277 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17278 | Intent.FLAG_RECEIVER_FOREGROUND); 17279 if (reason != null) { 17280 intent.putExtra("reason", reason); 17281 } 17282 17283 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 17284 null, null, OP_NONE, null, false, false, -1, SYSTEM_UID, 17285 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 17286 } 17287 } 17288 17289 @Override killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)17290 public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 17291 synchronized (ActivityManagerService.this) { 17292 ActivityManagerService.this.killAllBackgroundProcessesExcept( 17293 minTargetSdk, maxProcState); 17294 } 17295 } 17296 17297 @Override startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)17298 public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, 17299 boolean isTop, String hostingType, ComponentName hostingName) { 17300 try { 17301 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 17302 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:" 17303 + processName); 17304 } 17305 synchronized (ActivityManagerService.this) { 17306 // If the process is known as top app, set a hint so when the process is 17307 // started, the top priority can be applied immediately to avoid cpu being 17308 // preempted by other processes before attaching the process of top app. 17309 startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */, 17310 new HostingRecord(hostingType, hostingName, isTop), 17311 ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */, 17312 false /* isolated */); 17313 } 17314 } finally { 17315 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 17316 } 17317 } 17318 17319 @Override setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)17320 public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, 17321 ProfilerInfo profilerInfo, Object wmLock) { 17322 synchronized (ActivityManagerService.this) { 17323 /** 17324 * This function is called from the window manager context and needs to be executed 17325 * synchronously. To avoid deadlock, we pass a message to AMS to execute the 17326 * function and notify the passed in lock when it has been completed. 17327 */ 17328 synchronized (wmLock) { 17329 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) { 17330 setDebugApp(aInfo.processName, true, false); 17331 } 17332 17333 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) { 17334 setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName); 17335 } 17336 17337 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) { 17338 setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName); 17339 } 17340 17341 if (profilerInfo != null) { 17342 setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo, null); 17343 } 17344 wmLock.notify(); 17345 } 17346 } 17347 } 17348 17349 @Override getStorageMountMode(int pid, int uid)17350 public int getStorageMountMode(int pid, int uid) { 17351 if (uid == SHELL_UID || uid == ROOT_UID) { 17352 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17353 } 17354 synchronized (mPidsSelfLocked) { 17355 final ProcessRecord pr = mPidsSelfLocked.get(pid); 17356 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.getMountMode(); 17357 } 17358 } 17359 17360 @Override isAppForeground(int uid)17361 public boolean isAppForeground(int uid) { 17362 return ActivityManagerService.this.isAppForeground(uid); 17363 } 17364 17365 @Override isAppBad(final String processName, final int uid)17366 public boolean isAppBad(final String processName, final int uid) { 17367 return ActivityManagerService.this.isAppBad(processName, uid); 17368 } 17369 17370 @Override clearPendingBackup(int userId)17371 public void clearPendingBackup(int userId) { 17372 ActivityManagerService.this.clearPendingBackup(userId); 17373 } 17374 17375 /** 17376 * When power button is very long pressed, call this interface to do some pre-shutdown work 17377 * like persisting database etc. 17378 */ 17379 @Override prepareForPossibleShutdown()17380 public void prepareForPossibleShutdown() { 17381 ActivityManagerService.this.prepareForPossibleShutdown(); 17382 } 17383 17384 @Override hasRunningForegroundService(int uid, int foregroundServicetype)17385 public boolean hasRunningForegroundService(int uid, int foregroundServicetype) { 17386 synchronized (ActivityManagerService.this) { 17387 return mProcessList.searchEachLruProcessesLOSP(true, app -> { 17388 if (app.uid != uid) { 17389 return null; 17390 } 17391 17392 if ((app.mServices.getForegroundServiceTypes() & foregroundServicetype) != 0) { 17393 return Boolean.TRUE; 17394 } 17395 return null; 17396 }) != null; 17397 } 17398 } 17399 17400 @Override 17401 public boolean hasForegroundServiceNotification(String pkg, int userId, 17402 String channelId) { 17403 synchronized (ActivityManagerService.this) { 17404 return mServices.hasForegroundServiceNotificationLocked(pkg, userId, channelId); 17405 } 17406 } 17407 17408 @Override 17409 public ServiceNotificationPolicy applyForegroundServiceNotification( 17410 Notification notification, String tag, int id, String pkg, int userId) { 17411 synchronized (ActivityManagerService.this) { 17412 return mServices.applyForegroundServiceNotificationLocked(notification, 17413 tag, id, pkg, userId); 17414 } 17415 } 17416 17417 @Override 17418 public void onForegroundServiceNotificationUpdate(boolean shown, 17419 Notification notification, int id, String pkg, @UserIdInt int userId) { 17420 synchronized (ActivityManagerService.this) { 17421 mServices.onForegroundServiceNotificationUpdateLocked(shown, 17422 notification, id, pkg, userId); 17423 } 17424 } 17425 17426 @Override 17427 public void stopAppForUser(String pkg, @UserIdInt int userId) { 17428 ActivityManagerService.this.stopAppForUserInternal(pkg, userId); 17429 } 17430 17431 @Override 17432 public void stopForegroundServicesForChannel(String pkg, int userId, 17433 String channelId) { 17434 synchronized (ActivityManagerService.this) { 17435 mServices.stopForegroundServicesForChannelLocked(pkg, userId, channelId); 17436 } 17437 } 17438 17439 @Override 17440 public void registerProcessObserver(IProcessObserver processObserver) { 17441 ActivityManagerService.this.registerProcessObserver(processObserver); 17442 } 17443 17444 @Override 17445 public void unregisterProcessObserver(IProcessObserver processObserver) { 17446 ActivityManagerService.this.unregisterProcessObserver(processObserver); 17447 } 17448 17449 @Override 17450 public int getInstrumentationSourceUid(int uid) { 17451 synchronized (mProcLock) { 17452 for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) { 17453 ActiveInstrumentation activeInst = mActiveInstrumentation.get(i); 17454 if (!activeInst.mFinished && activeInst.mTargetInfo != null 17455 && activeInst.mTargetInfo.uid == uid) { 17456 return activeInst.mSourceUid; 17457 } 17458 } 17459 } 17460 return INVALID_UID; 17461 } 17462 17463 @Override 17464 public void setDeviceOwnerUid(int uid) { 17465 mDeviceOwnerUid = uid; 17466 } 17467 17468 @Override 17469 public boolean isDeviceOwner(int uid) { 17470 int cachedUid = mDeviceOwnerUid; 17471 return uid >= 0 && cachedUid == uid; 17472 } 17473 17474 17475 @Override 17476 public void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids) { 17477 synchronized (ActivityManagerService.this) { 17478 mProfileOwnerUids = profileOwnerUids; 17479 } 17480 } 17481 17482 @Override 17483 public boolean isProfileOwner(int uid) { 17484 synchronized (ActivityManagerService.this) { 17485 return mProfileOwnerUids != null && mProfileOwnerUids.indexOf(uid) >= 0; 17486 } 17487 } 17488 17489 @Override 17490 public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) { 17491 synchronized (ActivityManagerService.this) { 17492 mCompanionAppUidsMap.put(userId, companionAppUids); 17493 } 17494 } 17495 17496 @Override 17497 public boolean isAssociatedCompanionApp(int userId, int uid) { 17498 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId); 17499 if (allUids == null) { 17500 return false; 17501 } 17502 return allUids.contains(uid); 17503 } 17504 17505 @Override 17506 public void addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread) { 17507 final boolean isNewPending = mPendingStartActivityUids.add(uid, pid); 17508 // If the next top activity is in cached and frozen mode, WM should raise its priority 17509 // to unfreeze it. This is done by calling AMS.updateOomAdj that will lower its oom adj. 17510 // However, WM cannot hold the AMS clock here so the updateOomAdj operation is performed 17511 // in a separate thread asynchronously. Therefore WM can't guarantee AMS will unfreeze 17512 // next top activity on time. This race will fail the following binder transactions WM 17513 // sends to the activity. After this race issue between WM/ATMS and AMS is solved, this 17514 // workaround can be removed. (b/213288355) 17515 if (isNewPending) { 17516 mOomAdjuster.mCachedAppOptimizer.unfreezeProcess(pid, 17517 OomAdjuster.OOM_ADJ_REASON_ACTIVITY); 17518 } 17519 // We need to update the network rules for the app coming to the top state so that 17520 // it can access network when the device or the app is in a restricted state 17521 // (e.g. battery/data saver) but since waiting for updateOomAdj to complete and then 17522 // informing NetworkPolicyManager might get delayed, informing the state change as soon 17523 // as we know app is going to come to the top state. 17524 if (isNewPending && mNetworkPolicyUidObserver != null) { 17525 try { 17526 final long procStateSeq = mProcessList.getNextProcStateSeq(); 17527 mNetworkPolicyUidObserver.onUidStateChanged(uid, PROCESS_STATE_TOP, 17528 procStateSeq, PROCESS_CAPABILITY_ALL); 17529 if (thread != null && shouldWaitForNetworkRulesUpdate(uid)) { 17530 thread.setNetworkBlockSeq(procStateSeq); 17531 } 17532 } catch (RemoteException e) { 17533 Slog.d(TAG, "Error calling setNetworkBlockSeq", e); 17534 } 17535 } 17536 } 17537 17538 private boolean shouldWaitForNetworkRulesUpdate(int uid) { 17539 synchronized (mUidNetworkBlockedReasons) { 17540 // TODO: We can reuse this data in 17541 // ProcessList#incrementProcStateSeqAndNotifyAppsLOSP instead of calling into 17542 // NetworkManagementService. 17543 final int uidBlockedReasons = mUidNetworkBlockedReasons.get( 17544 uid, BLOCKED_REASON_NONE); 17545 // We should only inform the uid to block if it is currently blocked but will be 17546 // unblocked once it comes to the TOP state. 17547 return uidBlockedReasons != BLOCKED_REASON_NONE 17548 && updateBlockedReasonsWithProcState(uidBlockedReasons, PROCESS_STATE_TOP) 17549 == BLOCKED_REASON_NONE; 17550 } 17551 } 17552 17553 @Override 17554 public void deletePendingTopUid(int uid, long nowElapsed) { 17555 mPendingStartActivityUids.delete(uid, nowElapsed); 17556 } 17557 17558 @Override 17559 public boolean isPendingTopUid(int uid) { 17560 return mPendingStartActivityUids.isPendingTopUid(uid); 17561 } 17562 17563 @Override 17564 public Intent getIntentForIntentSender(IIntentSender sender) { 17565 return ActivityManagerService.this.getIntentForIntentSender(sender); 17566 } 17567 17568 @Override 17569 public PendingIntent getPendingIntentActivityAsApp( 17570 int requestCode, @NonNull Intent intent, int flags, Bundle options, 17571 String ownerPkg, int ownerUid) { 17572 return getPendingIntentActivityAsApp(requestCode, new Intent[] { intent }, flags, 17573 options, ownerPkg, ownerUid); 17574 } 17575 17576 @Override 17577 public PendingIntent getPendingIntentActivityAsApp( 17578 int requestCode, @NonNull Intent[] intents, int flags, Bundle options, 17579 String ownerPkg, int ownerUid) { 17580 // system callers must explicitly set mutability state 17581 final boolean flagImmutableSet = (flags & PendingIntent.FLAG_IMMUTABLE) != 0; 17582 final boolean flagMutableSet = (flags & PendingIntent.FLAG_MUTABLE) != 0; 17583 if (flagImmutableSet == flagMutableSet) { 17584 throw new IllegalArgumentException( 17585 "Must set exactly one of FLAG_IMMUTABLE or FLAG_MUTABLE"); 17586 } 17587 17588 final Context context = ActivityManagerService.this.mContext; 17589 final ContentResolver resolver = context.getContentResolver(); 17590 final int len = intents.length; 17591 final String[] resolvedTypes = new String[len]; 17592 for (int i = 0; i < len; i++) { 17593 final Intent intent = intents[i]; 17594 resolvedTypes[i] = intent.resolveTypeIfNeeded(resolver); 17595 intent.migrateExtraStreamToClipData(context); 17596 intent.prepareToLeaveProcess(context); 17597 } 17598 IIntentSender target = 17599 ActivityManagerService.this.getIntentSenderWithFeatureAsApp( 17600 INTENT_SENDER_ACTIVITY, ownerPkg, 17601 context.getAttributionTag(), null, null, requestCode, 17602 intents, 17603 resolvedTypes, 17604 flags, options, UserHandle.getUserId(ownerUid), ownerUid); 17605 return target != null ? new PendingIntent(target) : null; 17606 } 17607 17608 @Override 17609 public long getBootTimeTempAllowListDuration() { 17610 // Do not lock ActivityManagerService.this here, this API is called by 17611 // PackageManagerService. 17612 return mConstants.mBootTimeTempAllowlistDuration; 17613 } 17614 17615 @Override 17616 public void registerAnrController(AnrController controller) { 17617 mActivityTaskManager.registerAnrController(controller); 17618 } 17619 17620 @Override 17621 public void unregisterAnrController(AnrController controller) { 17622 mActivityTaskManager.unregisterAnrController(controller); 17623 } 17624 17625 @Override 17626 public boolean canStartForegroundService(int pid, int uid, @NonNull String packageName) { 17627 synchronized (ActivityManagerService.this) { 17628 return mServices.canStartForegroundServiceLocked(pid, uid, packageName); 17629 } 17630 } 17631 17632 @Override 17633 public void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs) { 17634 mFgsWhileInUseTempAllowList.add(uid, durationMs, ""); 17635 } 17636 17637 @Override 17638 public boolean isTempAllowlistedForFgsWhileInUse(int uid) { 17639 return mFgsWhileInUseTempAllowList.isAllowed(uid); 17640 } 17641 17642 @Override 17643 public boolean canAllowWhileInUsePermissionInFgs(int pid, int uid, 17644 @NonNull String packageName) { 17645 synchronized (ActivityManagerService.this) { 17646 return mServices.canAllowWhileInUsePermissionInFgsLocked(pid, uid, packageName); 17647 } 17648 } 17649 17650 @Override 17651 public @TempAllowListType int getPushMessagingOverQuotaBehavior() { 17652 synchronized (ActivityManagerService.this) { 17653 return mConstants.mPushMessagingOverQuotaBehavior; 17654 } 17655 } 17656 17657 @Override 17658 public int getServiceStartForegroundTimeout() { 17659 return mConstants.mServiceStartForegroundTimeoutMs; 17660 } 17661 17662 @Override 17663 public int getUidCapability(int uid) { 17664 synchronized (ActivityManagerService.this) { 17665 UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 17666 if (uidRecord == null) { 17667 throw new IllegalArgumentException("uid record for " + uid + " not found"); 17668 } 17669 return uidRecord.getCurCapability(); 17670 } 17671 } 17672 17673 /** 17674 * @return The PID list of the isolated process with packages matching the given uid. 17675 */ 17676 @Nullable 17677 public List<Integer> getIsolatedProcesses(int uid) { 17678 synchronized (ActivityManagerService.this) { 17679 return mProcessList.getIsolatedProcessesLocked(uid); 17680 } 17681 } 17682 17683 /** @see ActivityManagerService#sendIntentSender */ 17684 @Override 17685 public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, 17686 Intent intent, String resolvedType, 17687 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 17688 return ActivityManagerService.this.sendIntentSender(target, allowlistToken, code, 17689 intent, resolvedType, finishedReceiver, requiredPermission, options); 17690 } 17691 17692 @Override 17693 public void setVoiceInteractionManagerProvider( 17694 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) { 17695 ActivityManagerService.this.setVoiceInteractionManagerProvider(provider); 17696 } 17697 17698 @Override 17699 public void setStopUserOnSwitch(int value) { 17700 ActivityManagerService.this.setStopUserOnSwitch(value); 17701 } 17702 17703 @Override 17704 public @RestrictionLevel int getRestrictionLevel(int uid) { 17705 return mAppRestrictionController.getRestrictionLevel(uid); 17706 } 17707 17708 @Override 17709 public @RestrictionLevel int getRestrictionLevel(String pkg, @UserIdInt int userId) { 17710 return mAppRestrictionController.getRestrictionLevel(pkg, userId); 17711 } 17712 17713 @Override 17714 public boolean isBgAutoRestrictedBucketFeatureFlagEnabled() { 17715 return mAppRestrictionController.isBgAutoRestrictedBucketFeatureFlagEnabled(); 17716 } 17717 17718 @Override 17719 public void addAppBackgroundRestrictionListener( 17720 @NonNull ActivityManagerInternal.AppBackgroundRestrictionListener listener) { 17721 mAppRestrictionController.addAppBackgroundRestrictionListener(listener); 17722 } 17723 17724 @Override 17725 public void addForegroundServiceStateListener( 17726 @NonNull ForegroundServiceStateListener listener) { 17727 synchronized (ActivityManagerService.this) { 17728 mForegroundServiceStateListeners.add(listener); 17729 } 17730 } 17731 17732 @Override 17733 public void addBroadcastEventListener(@NonNull BroadcastEventListener listener) { 17734 // It's a CopyOnWriteArrayList, so no lock is needed. 17735 mBroadcastEventListeners.add(listener); 17736 } 17737 17738 @Override 17739 public void addBindServiceEventListener(@NonNull BindServiceEventListener listener) { 17740 // It's a CopyOnWriteArrayList, so no lock is needed. 17741 mBindServiceEventListeners.add(listener); 17742 } 17743 17744 @Override 17745 public void restart() { 17746 ActivityManagerService.this.restart(); 17747 } 17748 17749 @Override 17750 public void registerNetworkPolicyUidObserver(@NonNull IUidObserver observer, 17751 int which, int cutpoint, @NonNull String callingPackage) { 17752 mNetworkPolicyUidObserver = observer; 17753 mUidObserverController.register(observer, which, cutpoint, callingPackage, 17754 Binder.getCallingUid()); 17755 } 17756 } 17757 17758 long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) { 17759 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 17760 throw new SecurityException("Requires permission " + FILTER_EVENTS); 17761 } 17762 ProcessRecord proc; 17763 synchronized (mPidsSelfLocked) { 17764 proc = mPidsSelfLocked.get(pid); 17765 } 17766 final long timeoutMillis = proc != null ? proc.getInputDispatchingTimeoutMillis() : 17767 DEFAULT_DISPATCHING_TIMEOUT_MILLIS; 17768 17769 if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, reason)) { 17770 return 0; 17771 } 17772 17773 return timeoutMillis; 17774 } 17775 17776 /** 17777 * Handle input dispatching timeouts. 17778 * @return whether input dispatching should be aborted or not. 17779 */ 17780 boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, 17781 ApplicationInfo aInfo, String parentShortComponentName, 17782 WindowProcessController parentProcess, boolean aboveSystem, String reason) { 17783 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 17784 throw new SecurityException("Requires permission " + FILTER_EVENTS); 17785 } 17786 17787 final String annotation; 17788 if (reason == null) { 17789 annotation = "Input dispatching timed out"; 17790 } else { 17791 annotation = "Input dispatching timed out (" + reason + ")"; 17792 } 17793 17794 if (proc != null) { 17795 synchronized (this) { 17796 if (proc.isDebugging()) { 17797 return false; 17798 } 17799 17800 if (proc.getActiveInstrumentation() != null) { 17801 Bundle info = new Bundle(); 17802 info.putString("shortMsg", "keyDispatchingTimedOut"); 17803 info.putString("longMsg", annotation); 17804 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 17805 return true; 17806 } 17807 } 17808 mAnrHelper.appNotResponding(proc, activityShortComponentName, aInfo, 17809 parentShortComponentName, parentProcess, aboveSystem, annotation); 17810 } 17811 17812 return true; 17813 } 17814 17815 /** 17816 * Called by app main thread to wait for the network policy rules to get updated. 17817 * 17818 * @param procStateSeq The sequence number indicating the process state change that the main 17819 * thread is interested in. 17820 */ 17821 @Override 17822 public void waitForNetworkStateUpdate(long procStateSeq) { 17823 final int callingUid = Binder.getCallingUid(); 17824 if (DEBUG_NETWORK) { 17825 Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq); 17826 } 17827 UidRecord record; 17828 synchronized (mProcLock) { 17829 record = mProcessList.getUidRecordLOSP(callingUid); 17830 if (record == null) { 17831 return; 17832 } 17833 } 17834 synchronized (record.networkStateLock) { 17835 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 17836 if (DEBUG_NETWORK) { 17837 Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. " 17838 + procStateSeq + ", so no need to wait. Uid: " 17839 + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: " 17840 + record.lastNetworkUpdatedProcStateSeq); 17841 } 17842 return; 17843 } 17844 try { 17845 if (DEBUG_NETWORK) { 17846 Slog.d(TAG_NETWORK, "Starting to wait for the network rules update." 17847 + " Uid: " + callingUid + " procStateSeq: " + procStateSeq); 17848 } 17849 final long startTime = SystemClock.uptimeMillis(); 17850 record.procStateSeqWaitingForNetwork = procStateSeq; 17851 record.networkStateLock.wait(mConstants.mNetworkAccessTimeoutMs); 17852 record.procStateSeqWaitingForNetwork = 0; 17853 final long totalTime = SystemClock.uptimeMillis() - startTime; 17854 if (totalTime >= mConstants.mNetworkAccessTimeoutMs || DEBUG_NETWORK) { 17855 Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: " 17856 + totalTime + ". Uid: " + callingUid + " procStateSeq: " 17857 + procStateSeq + " UidRec: " + record 17858 + " validateUidRec: " 17859 + mUidObserverController.getValidateUidRecord(callingUid)); 17860 } 17861 } catch (InterruptedException e) { 17862 Thread.currentThread().interrupt(); 17863 } 17864 } 17865 } 17866 17867 @Override 17868 public void waitForBroadcastIdle() { 17869 waitForBroadcastIdle(/* printWriter= */ null); 17870 } 17871 17872 public void waitForBroadcastIdle(@Nullable PrintWriter pw) { 17873 enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()"); 17874 while (true) { 17875 boolean idle = true; 17876 synchronized (this) { 17877 for (BroadcastQueue queue : mBroadcastQueues) { 17878 if (!queue.isIdle()) { 17879 final String msg = "Waiting for queue " + queue + " to become idle..."; 17880 if (pw != null) { 17881 pw.println(msg); 17882 pw.println(queue.describeState()); 17883 pw.flush(); 17884 } 17885 Slog.v(TAG, msg); 17886 queue.cancelDeferrals(); 17887 idle = false; 17888 } 17889 } 17890 } 17891 17892 if (idle) { 17893 final String msg = "All broadcast queues are idle!"; 17894 if (pw != null) { 17895 pw.println(msg); 17896 pw.flush(); 17897 } 17898 Slog.v(TAG, msg); 17899 return; 17900 } else { 17901 SystemClock.sleep(1000); 17902 } 17903 } 17904 } 17905 17906 @Override 17907 @ReasonCode 17908 public int getBackgroundRestrictionExemptionReason(int uid) { 17909 enforceCallingPermission(android.Manifest.permission.DEVICE_POWER, 17910 "getBackgroundRestrictionExemptionReason()"); 17911 return mAppRestrictionController.getBackgroundRestrictionExemptionReason(uid); 17912 } 17913 17914 /** 17915 * Force the settings cache to be loaded 17916 */ 17917 void refreshSettingsCache() { 17918 mCoreSettingsObserver.onChange(true); 17919 } 17920 17921 /** 17922 * Kill processes for the user with id userId and that depend on the package named packageName 17923 */ 17924 @Override 17925 public void killPackageDependents(String packageName, int userId) { 17926 enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()"); 17927 if (packageName == null) { 17928 throw new NullPointerException( 17929 "Cannot kill the dependents of a package without its name."); 17930 } 17931 17932 final long callingId = Binder.clearCallingIdentity(); 17933 IPackageManager pm = AppGlobals.getPackageManager(); 17934 int pkgUid = -1; 17935 try { 17936 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 17937 } catch (RemoteException e) { 17938 } 17939 if (userId != UserHandle.USER_ALL && pkgUid == -1) { 17940 throw new IllegalArgumentException( 17941 "Cannot kill dependents of non-existing package " + packageName); 17942 } 17943 try { 17944 synchronized(this) { 17945 synchronized (mProcLock) { 17946 mProcessList.killPackageProcessesLSP(packageName, UserHandle.getAppId(pkgUid), 17947 userId, ProcessList.FOREGROUND_APP_ADJ, 17948 ApplicationExitInfo.REASON_DEPENDENCY_DIED, 17949 ApplicationExitInfo.SUBREASON_UNKNOWN, 17950 "dep: " + packageName); 17951 } 17952 } 17953 } finally { 17954 Binder.restoreCallingIdentity(callingId); 17955 } 17956 } 17957 17958 @Override 17959 public int restartUserInBackground(final int userId) { 17960 return mUserController.restartUser(userId, /* foreground */ false); 17961 } 17962 17963 @Override 17964 public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) { 17965 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 17966 "scheduleApplicationInfoChanged()"); 17967 17968 final long origId = Binder.clearCallingIdentity(); 17969 try { 17970 final boolean updateFrameworkRes = packageNames.contains("android"); 17971 synchronized (mProcLock) { 17972 updateApplicationInfoLOSP(packageNames, updateFrameworkRes, userId); 17973 } 17974 17975 AppWidgetManagerInternal widgets = LocalServices.getService( 17976 AppWidgetManagerInternal.class); 17977 if (widgets != null) { 17978 widgets.applyResourceOverlaysToWidgets(new HashSet<>(packageNames), userId, 17979 updateFrameworkRes); 17980 } 17981 } finally { 17982 Binder.restoreCallingIdentity(origId); 17983 } 17984 } 17985 17986 /** 17987 * Synchronously update the system ActivityThread, bypassing any deferred threading so any 17988 * resources and overlaid values are available immediately. 17989 */ 17990 public void updateSystemUiContext() { 17991 final PackageManagerInternal packageManagerInternal = getPackageManagerInternal(); 17992 17993 ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android", 17994 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM); 17995 ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai); 17996 } 17997 17998 @GuardedBy(anyOf = {"this", "mProcLock"}) 17999 private void updateApplicationInfoLOSP(@NonNull List<String> packagesToUpdate, 18000 boolean updateFrameworkRes, int userId) { 18001 if (updateFrameworkRes) { 18002 ParsingPackageUtils.readConfigUseRoundIcon(null); 18003 } 18004 18005 mProcessList.updateApplicationInfoLOSP(packagesToUpdate, userId, updateFrameworkRes); 18006 18007 if (updateFrameworkRes) { 18008 // Update system server components that need to know about changed overlays. Because the 18009 // overlay is applied in ActivityThread, we need to serialize through its thread too. 18010 final Executor executor = ActivityThread.currentActivityThread().getExecutor(); 18011 final DisplayManagerInternal display = 18012 LocalServices.getService(DisplayManagerInternal.class); 18013 if (display != null) { 18014 executor.execute(display::onOverlayChanged); 18015 } 18016 if (mWindowManager != null) { 18017 executor.execute(mWindowManager::onOverlayChanged); 18018 } 18019 } 18020 } 18021 18022 /** 18023 * Update the binder call heavy hitter watcher per the new configuration 18024 */ 18025 void scheduleUpdateBinderHeavyHitterWatcherConfig() { 18026 // There are two sets of configs: the default watcher and the auto sampler, 18027 // the default one takes precedence. System would kick off auto sampler when there is 18028 // an anomaly (i.e., consecutive ANRs), but it'll be stopped automatically after a while. 18029 mHandler.post(() -> { 18030 final boolean enabled; 18031 final int batchSize; 18032 final float threshold; 18033 final BinderCallHeavyHitterListener listener; 18034 synchronized (mProcLock) { 18035 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 18036 // Default watcher takes precedence, ignore the auto sampler. 18037 mHandler.removeMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG); 18038 // Set the watcher with the default watcher's config 18039 enabled = true; 18040 batchSize = mConstants.BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE; 18041 threshold = mConstants.BINDER_HEAVY_HITTER_WATCHER_THRESHOLD; 18042 listener = (a, b, c, d) -> mHandler.post( 18043 () -> handleBinderHeavyHitters(a, b, c, d)); 18044 } else if (mHandler.hasMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG)) { 18045 // There is an ongoing auto sampler session, update it 18046 enabled = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED; 18047 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE; 18048 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD; 18049 listener = (a, b, c, d) -> mHandler.post( 18050 () -> handleBinderHeavyHitters(a, b, c, d)); 18051 } else { 18052 // Stop it 18053 enabled = false; 18054 batchSize = 0; 18055 threshold = 0.0f; 18056 listener = null; 18057 } 18058 } 18059 Binder.setHeavyHitterWatcherConfig(enabled, batchSize, threshold, listener); 18060 }); 18061 } 18062 18063 /** 18064 * Kick off the watcher to run for given timeout, it could be throttled however. 18065 */ 18066 void scheduleBinderHeavyHitterAutoSampler() { 18067 mHandler.post(() -> { 18068 final int batchSize; 18069 final float threshold; 18070 final long now; 18071 synchronized (mProcLock) { 18072 if (!mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED) { 18073 // It's configured OFF 18074 return; 18075 } 18076 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 18077 // If the default watcher is active already, don't start the auto sampler 18078 return; 18079 } 18080 now = SystemClock.uptimeMillis(); 18081 if (mLastBinderHeavyHitterAutoSamplerStart 18082 + BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS > now) { 18083 // Too frequent, throttle it 18084 return; 18085 } 18086 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE; 18087 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD; 18088 } 18089 // No lock is needed because we are accessing these variables in handle thread only. 18090 mLastBinderHeavyHitterAutoSamplerStart = now; 18091 // Start the watcher with the auto sampler's config. 18092 Binder.setHeavyHitterWatcherConfig(true, batchSize, threshold, 18093 (a, b, c, d) -> mHandler.post(() -> handleBinderHeavyHitters(a, b, c, d))); 18094 // Schedule to stop it after given timeout. 18095 mHandler.sendMessageDelayed(mHandler.obtainMessage( 18096 BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG), 18097 BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS); 18098 }); 18099 } 18100 18101 /** 18102 * Stop the binder heavy hitter auto sampler after given timeout. 18103 */ 18104 private void handleBinderHeavyHitterAutoSamplerTimeOut() { 18105 synchronized (mProcLock) { 18106 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 18107 // The default watcher is ON, don't bother to stop it. 18108 return; 18109 } 18110 } 18111 Binder.setHeavyHitterWatcherConfig(false, 0, 0.0f, null); 18112 } 18113 18114 /** 18115 * Handle the heavy hitters 18116 */ 18117 private void handleBinderHeavyHitters(@NonNull final List<HeavyHitterContainer> hitters, 18118 final int totalBinderCalls, final float threshold, final long timeSpan) { 18119 final int size = hitters.size(); 18120 if (size == 0) { 18121 return; 18122 } 18123 // Simply log it for now 18124 final String pfmt = "%.1f%%"; 18125 final BinderTransactionNameResolver resolver = new BinderTransactionNameResolver(); 18126 final StringBuilder sb = new StringBuilder("Excessive incoming binder calls(>") 18127 .append(String.format(pfmt, threshold * 100)) 18128 .append(',').append(totalBinderCalls) 18129 .append(',').append(timeSpan) 18130 .append("ms): "); 18131 for (int i = 0; i < size; i++) { 18132 if (i > 0) { 18133 sb.append(", "); 18134 } 18135 final HeavyHitterContainer container = hitters.get(i); 18136 sb.append('[').append(container.mUid) 18137 .append(',').append(container.mClass.getName()) 18138 .append(',').append(resolver.getMethodName(container.mClass, container.mCode)) 18139 .append(',').append(container.mCode) 18140 .append(',').append(String.format(pfmt, container.mFrequency * 100)) 18141 .append(']'); 18142 } 18143 Slog.w(TAG, sb.toString()); 18144 } 18145 18146 /** 18147 * Attach an agent to the specified process (proces name or PID) 18148 */ 18149 public void attachAgent(String process, String path) { 18150 try { 18151 synchronized (mProcLock) { 18152 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_SYSTEM, 18153 "attachAgent"); 18154 IApplicationThread thread; 18155 if (proc == null || (thread = proc.getThread()) == null) { 18156 throw new IllegalArgumentException("Unknown process: " + process); 18157 } 18158 18159 enforceDebuggable(proc); 18160 18161 thread.attachAgent(path); 18162 } 18163 } catch (RemoteException e) { 18164 throw new IllegalStateException("Process disappeared"); 18165 } 18166 } 18167 18168 /** 18169 * When power button is very long pressed, call this interface to do some pre-shutdown work 18170 * like persisting database etc. 18171 */ 18172 public void prepareForPossibleShutdown() { 18173 if (mUsageStatsService != null) { 18174 mUsageStatsService.prepareForPossibleShutdown(); 18175 } 18176 } 18177 18178 @VisibleForTesting 18179 public static class Injector { 18180 private NetworkManagementInternal mNmi; 18181 private Context mContext; 18182 18183 public Injector(Context context) { 18184 mContext = context; 18185 } 18186 18187 public Context getContext() { 18188 return mContext; 18189 } 18190 18191 public AppOpsService getAppOpsService(File file, Handler handler) { 18192 return new AppOpsService(file, handler, getContext()); 18193 } 18194 18195 public Handler getUiHandler(ActivityManagerService service) { 18196 return service.new UiHandler(); 18197 } 18198 18199 public boolean isNetworkRestrictedForUid(int uid) { 18200 if (ensureHasNetworkManagementInternal()) { 18201 return mNmi.isNetworkRestrictedForUid(uid); 18202 } 18203 return false; 18204 } 18205 18206 /** 18207 * Return the process list instance 18208 */ 18209 public ProcessList getProcessList(ActivityManagerService service) { 18210 return new ProcessList(); 18211 } 18212 18213 private boolean ensureHasNetworkManagementInternal() { 18214 if (mNmi == null) { 18215 mNmi = LocalServices.getService(NetworkManagementInternal.class); 18216 } 18217 return mNmi != null; 18218 } 18219 } 18220 18221 @Override 18222 public void startDelegateShellPermissionIdentity(int delegateUid, 18223 @Nullable String[] permissions) { 18224 if (UserHandle.getCallingAppId() != Process.SHELL_UID 18225 && UserHandle.getCallingAppId() != Process.ROOT_UID) { 18226 throw new SecurityException("Only the shell can delegate its permissions"); 18227 } 18228 18229 // We allow delegation only to one instrumentation started from the shell 18230 synchronized (mProcLock) { 18231 // If the delegate is already set up for the target UID, nothing to do. 18232 if (mAppOpsService.getAppOpsServiceDelegate() != null) { 18233 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) { 18234 throw new IllegalStateException("Bad shell delegate state"); 18235 } 18236 final ShellDelegate delegate = (ShellDelegate) mAppOpsService 18237 .getAppOpsServiceDelegate(); 18238 if (delegate.getDelegateUid() != delegateUid) { 18239 throw new SecurityException("Shell can delegate permissions only " 18240 + "to one instrumentation at a time"); 18241 } 18242 } 18243 18244 final int instrCount = mActiveInstrumentation.size(); 18245 for (int i = 0; i < instrCount; i++) { 18246 final ActiveInstrumentation instr = mActiveInstrumentation.get(i); 18247 if (instr.mTargetInfo.uid != delegateUid) { 18248 continue; 18249 } 18250 // If instrumentation started from the shell the connection is not null 18251 if (instr.mUiAutomationConnection == null) { 18252 throw new SecurityException("Shell can delegate its permissions" + 18253 " only to an instrumentation started from the shell"); 18254 } 18255 18256 // Hook them up... 18257 final ShellDelegate shellDelegate = new ShellDelegate(delegateUid, 18258 permissions); 18259 mAppOpsService.setAppOpsServiceDelegate(shellDelegate); 18260 final String packageName = instr.mTargetInfo.packageName; 18261 final List<String> permissionNames = permissions != null ? 18262 Arrays.asList(permissions) : null; 18263 getPermissionManagerInternal().startShellPermissionIdentityDelegation( 18264 delegateUid, packageName, permissionNames); 18265 return; 18266 } 18267 } 18268 } 18269 18270 @Override 18271 public void stopDelegateShellPermissionIdentity() { 18272 if (UserHandle.getCallingAppId() != Process.SHELL_UID 18273 && UserHandle.getCallingAppId() != Process.ROOT_UID) { 18274 throw new SecurityException("Only the shell can delegate its permissions"); 18275 } 18276 synchronized (mProcLock) { 18277 mAppOpsService.setAppOpsServiceDelegate(null); 18278 getPermissionManagerInternal().stopShellPermissionIdentityDelegation(); 18279 } 18280 } 18281 18282 @Override 18283 public List<String> getDelegatedShellPermissions() { 18284 if (UserHandle.getCallingAppId() != Process.SHELL_UID 18285 && UserHandle.getCallingAppId() != Process.ROOT_UID) { 18286 throw new SecurityException("Only the shell can get delegated permissions"); 18287 } 18288 synchronized (mProcLock) { 18289 return getPermissionManagerInternal().getDelegatedShellPermissions(); 18290 } 18291 } 18292 18293 private class ShellDelegate implements CheckOpsDelegate { 18294 private final int mTargetUid; 18295 @Nullable 18296 private final String[] mPermissions; 18297 18298 ShellDelegate(int targetUid, @Nullable String[] permissions) { 18299 mTargetUid = targetUid; 18300 mPermissions = permissions; 18301 } 18302 18303 int getDelegateUid() { 18304 return mTargetUid; 18305 } 18306 18307 @Override 18308 public int checkOperation(int code, int uid, String packageName, 18309 String attributionTag, boolean raw, 18310 QuintFunction<Integer, Integer, String, String, Boolean, Integer> superImpl) { 18311 if (uid == mTargetUid && isTargetOp(code)) { 18312 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid), 18313 Process.SHELL_UID); 18314 final long identity = Binder.clearCallingIdentity(); 18315 try { 18316 return superImpl.apply(code, shellUid, "com.android.shell", null, raw); 18317 } finally { 18318 Binder.restoreCallingIdentity(identity); 18319 } 18320 } 18321 return superImpl.apply(code, uid, packageName, attributionTag, raw); 18322 } 18323 18324 @Override 18325 public int checkAudioOperation(int code, int usage, int uid, String packageName, 18326 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) { 18327 if (uid == mTargetUid && isTargetOp(code)) { 18328 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid), 18329 Process.SHELL_UID); 18330 final long identity = Binder.clearCallingIdentity(); 18331 try { 18332 return superImpl.apply(code, usage, shellUid, "com.android.shell"); 18333 } finally { 18334 Binder.restoreCallingIdentity(identity); 18335 } 18336 } 18337 return superImpl.apply(code, usage, uid, packageName); 18338 } 18339 18340 @Override 18341 public SyncNotedAppOp noteOperation(int code, int uid, @Nullable String packageName, 18342 @Nullable String featureId, boolean shouldCollectAsyncNotedOp, 18343 @Nullable String message, boolean shouldCollectMessage, 18344 @NonNull HeptFunction<Integer, Integer, String, String, Boolean, String, Boolean, 18345 SyncNotedAppOp> superImpl) { 18346 if (uid == mTargetUid && isTargetOp(code)) { 18347 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid), 18348 Process.SHELL_UID); 18349 final long identity = Binder.clearCallingIdentity(); 18350 try { 18351 return superImpl.apply(code, shellUid, "com.android.shell", featureId, 18352 shouldCollectAsyncNotedOp, message, shouldCollectMessage); 18353 } finally { 18354 Binder.restoreCallingIdentity(identity); 18355 } 18356 } 18357 return superImpl.apply(code, uid, packageName, featureId, shouldCollectAsyncNotedOp, 18358 message, shouldCollectMessage); 18359 } 18360 18361 @Override 18362 public SyncNotedAppOp noteProxyOperation(int code, 18363 @NonNull AttributionSource attributionSource, boolean shouldCollectAsyncNotedOp, 18364 @Nullable String message, boolean shouldCollectMessage, boolean skiProxyOperation, 18365 @NonNull HexFunction<Integer, AttributionSource, Boolean, String, Boolean, 18366 Boolean, SyncNotedAppOp> superImpl) { 18367 if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) { 18368 final int shellUid = UserHandle.getUid(UserHandle.getUserId( 18369 attributionSource.getUid()), Process.SHELL_UID); 18370 final long identity = Binder.clearCallingIdentity(); 18371 try { 18372 return superImpl.apply(code, new AttributionSource(shellUid, 18373 "com.android.shell", attributionSource.getAttributionTag(), 18374 attributionSource.getToken(), attributionSource.getNext()), 18375 shouldCollectAsyncNotedOp, message, shouldCollectMessage, 18376 skiProxyOperation); 18377 } finally { 18378 Binder.restoreCallingIdentity(identity); 18379 } 18380 } 18381 return superImpl.apply(code, attributionSource, shouldCollectAsyncNotedOp, 18382 message, shouldCollectMessage, skiProxyOperation); 18383 } 18384 18385 @Override 18386 public SyncNotedAppOp startOperation(IBinder token, int code, int uid, 18387 @Nullable String packageName, @Nullable String attributionTag, 18388 boolean startIfModeDefault, boolean shouldCollectAsyncNotedOp, 18389 @Nullable String message, boolean shouldCollectMessage, 18390 @AttributionFlags int attributionFlags, int attributionChainId, 18391 @NonNull UndecFunction<IBinder, Integer, Integer, String, String, Boolean, 18392 Boolean, String, Boolean, Integer, Integer, SyncNotedAppOp> superImpl) { 18393 if (uid == mTargetUid && isTargetOp(code)) { 18394 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid), 18395 Process.SHELL_UID); 18396 final long identity = Binder.clearCallingIdentity(); 18397 try { 18398 return superImpl.apply(token, code, shellUid, "com.android.shell", 18399 attributionTag, startIfModeDefault, shouldCollectAsyncNotedOp, message, 18400 shouldCollectMessage, attributionFlags, attributionChainId); 18401 } finally { 18402 Binder.restoreCallingIdentity(identity); 18403 } 18404 } 18405 return superImpl.apply(token, code, uid, packageName, attributionTag, 18406 startIfModeDefault, shouldCollectAsyncNotedOp, message, shouldCollectMessage, 18407 attributionFlags, attributionChainId); 18408 } 18409 18410 @Override 18411 public SyncNotedAppOp startProxyOperation(@NonNull IBinder clientId, int code, 18412 @NonNull AttributionSource attributionSource, boolean startIfModeDefault, 18413 boolean shouldCollectAsyncNotedOp, String message, boolean shouldCollectMessage, 18414 boolean skipProxyOperation, @AttributionFlags int proxyAttributionFlags, 18415 @AttributionFlags int proxiedAttributionFlags, int attributionChainId, 18416 @NonNull UndecFunction<IBinder, Integer, AttributionSource, 18417 Boolean, Boolean, String, Boolean, Boolean, Integer, Integer, Integer, 18418 SyncNotedAppOp> superImpl) { 18419 if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) { 18420 final int shellUid = UserHandle.getUid(UserHandle.getUserId( 18421 attributionSource.getUid()), Process.SHELL_UID); 18422 final long identity = Binder.clearCallingIdentity(); 18423 try { 18424 return superImpl.apply(clientId, code, new AttributionSource(shellUid, 18425 "com.android.shell", attributionSource.getAttributionTag(), 18426 attributionSource.getToken(), attributionSource.getNext()), 18427 startIfModeDefault, shouldCollectAsyncNotedOp, message, 18428 shouldCollectMessage, skipProxyOperation, proxyAttributionFlags, 18429 proxiedAttributionFlags, attributionChainId); 18430 } finally { 18431 Binder.restoreCallingIdentity(identity); 18432 } 18433 } 18434 return superImpl.apply(clientId, code, attributionSource, startIfModeDefault, 18435 shouldCollectAsyncNotedOp, message, shouldCollectMessage, skipProxyOperation, 18436 proxyAttributionFlags, proxiedAttributionFlags, attributionChainId); 18437 } 18438 18439 @Override 18440 public void finishProxyOperation(@NonNull IBinder clientId, int code, 18441 @NonNull AttributionSource attributionSource, boolean skipProxyOperation, 18442 @NonNull QuadFunction<IBinder, Integer, AttributionSource, Boolean, 18443 Void> superImpl) { 18444 if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) { 18445 final int shellUid = UserHandle.getUid(UserHandle.getUserId( 18446 attributionSource.getUid()), Process.SHELL_UID); 18447 final long identity = Binder.clearCallingIdentity(); 18448 try { 18449 superImpl.apply(clientId, code, new AttributionSource(shellUid, 18450 "com.android.shell", attributionSource.getAttributionTag(), 18451 attributionSource.getToken(), attributionSource.getNext()), 18452 skipProxyOperation); 18453 } finally { 18454 Binder.restoreCallingIdentity(identity); 18455 } 18456 } 18457 superImpl.apply(clientId, code, attributionSource, skipProxyOperation); 18458 } 18459 18460 private boolean isTargetOp(int code) { 18461 // null permissions means all ops are targeted 18462 if (mPermissions == null) { 18463 return true; 18464 } 18465 // no permission for the op means the op is targeted 18466 final String permission = AppOpsManager.opToPermission(code); 18467 if (permission == null) { 18468 return true; 18469 } 18470 return isTargetPermission(permission); 18471 } 18472 18473 private boolean isTargetPermission(@NonNull String permission) { 18474 // null permissions means all permissions are targeted 18475 return (mPermissions == null || ArrayUtils.contains(mPermissions, permission)); 18476 } 18477 } 18478 18479 /** 18480 * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would 18481 * cause a watchdog kill. 18482 */ 18483 void maybeTriggerWatchdog() { 18484 final String key = "debug.trigger.watchdog"; 18485 if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) { 18486 Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!"); 18487 18488 // Clear the property; otherwise the system would hang again after a watchdog restart. 18489 SystemProperties.set(key, ""); 18490 synchronized (ActivityManagerService.this) { 18491 try { 18492 // Arbitrary long sleep for watchdog to catch. 18493 Thread.sleep(60 * 60 * 1000); 18494 } catch (InterruptedException e) { 18495 } 18496 } 18497 } 18498 } 18499 18500 private boolean isOnFgOffloadQueue(int flags) { 18501 return ((flags & Intent.FLAG_RECEIVER_OFFLOAD_FOREGROUND) != 0); 18502 } 18503 18504 private boolean isOnBgOffloadQueue(int flags) { 18505 return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0)); 18506 } 18507 18508 @Override 18509 public ParcelFileDescriptor getLifeMonitor() { 18510 if (!isCallerShell()) { 18511 throw new SecurityException("Only shell can call it"); 18512 } 18513 synchronized (mProcLock) { 18514 try { 18515 if (mLifeMonitorFds == null) { 18516 mLifeMonitorFds = ParcelFileDescriptor.createPipe(); 18517 } 18518 // The returned FD will be closed, but we want to keep our reader open, 18519 // so return a dup instead. 18520 return mLifeMonitorFds[0].dup(); 18521 } catch (IOException e) { 18522 Slog.w(TAG, "Unable to create pipe", e); 18523 return null; 18524 } 18525 } 18526 } 18527 18528 @Override 18529 public void setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken) { 18530 final int callingUid = Binder.getCallingUid(); 18531 final int userId = UserHandle.getCallingUserId(); 18532 if (getPackageManagerInternal().getPackageUid(activity.getPackageName(), 18533 /*flags=*/ 0, userId) != callingUid) { 18534 throw new SecurityException("Calling uid " + callingUid + " cannot set locusId" 18535 + "for package " + activity.getPackageName()); 18536 } 18537 mActivityTaskManager.setLocusId(locusId, appToken); 18538 if (mUsageStatsService != null) { 18539 mUsageStatsService.reportLocusUpdate(activity, userId, locusId, appToken); 18540 } 18541 } 18542 18543 @Override 18544 public boolean isAppFreezerSupported() { 18545 final long token = Binder.clearCallingIdentity(); 18546 18547 try { 18548 return mOomAdjuster.mCachedAppOptimizer.isFreezerSupported(); 18549 } finally { 18550 Binder.restoreCallingIdentity(token); 18551 } 18552 } 18553 18554 @Override 18555 public boolean isAppFreezerEnabled() { 18556 return mOomAdjuster.mCachedAppOptimizer.useFreezer(); 18557 } 18558 18559 /** 18560 * Resets the state of the {@link com.android.server.am.AppErrors} instance. 18561 * This is intended for testing within the CTS only and is protected by 18562 * android.permission.RESET_APP_ERRORS. 18563 */ 18564 @Override 18565 public void resetAppErrors() { 18566 enforceCallingPermission(Manifest.permission.RESET_APP_ERRORS, "resetAppErrors"); 18567 mAppErrors.resetState(); 18568 } 18569 18570 @Override 18571 public boolean enableAppFreezer(boolean enable) { 18572 int callerUid = Binder.getCallingUid(); 18573 18574 // Only system can toggle the freezer state 18575 if (callerUid == SYSTEM_UID || Build.IS_DEBUGGABLE) { 18576 return mOomAdjuster.mCachedAppOptimizer.enableFreezer(enable); 18577 } else { 18578 throw new SecurityException("Caller uid " + callerUid + " cannot set freezer state "); 18579 } 18580 } 18581 18582 /** 18583 * Suppress or reenable the rate limit on foreground service notification deferral. 18584 * @param enable false to suppress rate-limit policy; true to reenable it. 18585 */ 18586 @Override 18587 public boolean enableFgsNotificationRateLimit(boolean enable) { 18588 enforceCallingPermission(permission.WRITE_DEVICE_CONFIG, 18589 "enableFgsNotificationRateLimit"); 18590 synchronized (this) { 18591 return mServices.enableFgsNotificationRateLimitLocked(enable); 18592 } 18593 } 18594 18595 /** 18596 * Holds the AM lock for the specified amount of milliseconds. 18597 * Intended for use by the tests that need to imitate lock contention. 18598 * The token should be obtained by 18599 * {@link android.content.pm.PackageManager#getHoldLockToken()}. 18600 */ 18601 @Override 18602 public void holdLock(IBinder token, int durationMs) { 18603 getTestUtilityServiceLocked().verifyHoldLockToken(token); 18604 18605 synchronized (this) { 18606 SystemClock.sleep(durationMs); 18607 } 18608 } 18609 18610 static void traceBegin(long traceTag, String methodName, String subInfo) { 18611 if (Trace.isTagEnabled(traceTag)) { 18612 Trace.traceBegin(traceTag, methodName + subInfo); 18613 } 18614 } 18615 } 18616