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.START_ACTIVITIES_FROM_BACKGROUND; 25 import static android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND; 26 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS; 27 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_ISOLATED_STORAGE; 28 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_TEST_API_CHECKS; 29 import static android.app.ActivityManager.INSTR_FLAG_NO_RESTART; 30 import static android.app.ActivityManager.INTENT_SENDER_ACTIVITY; 31 import static android.app.ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 32 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT; 33 import static android.app.ActivityManager.PROCESS_STATE_TOP; 34 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY; 35 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL; 36 import static android.app.AppOpsManager.OP_NONE; 37 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 38 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES; 39 import static android.content.pm.PackageManager.MATCH_ALL; 40 import static android.content.pm.PackageManager.MATCH_ANY_USER; 41 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 42 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 43 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 44 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 45 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 46 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 47 import static android.os.FactoryTest.FACTORY_TEST_OFF; 48 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL; 49 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH; 50 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL; 51 import static android.os.IServiceManager.DUMP_FLAG_PROTO; 52 import static android.os.InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS; 53 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALLOW_LISTED; 54 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED; 55 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_NONE; 56 import static android.os.Process.BLUETOOTH_UID; 57 import static android.os.Process.FIRST_APPLICATION_UID; 58 import static android.os.Process.INVALID_UID; 59 import static android.os.Process.NETWORK_STACK_UID; 60 import static android.os.Process.NFC_UID; 61 import static android.os.Process.PHONE_UID; 62 import static android.os.Process.PROC_OUT_LONG; 63 import static android.os.Process.PROC_SPACE_TERM; 64 import static android.os.Process.ROOT_UID; 65 import static android.os.Process.SCHED_FIFO; 66 import static android.os.Process.SCHED_RESET_ON_FORK; 67 import static android.os.Process.SE_UID; 68 import static android.os.Process.SHELL_UID; 69 import static android.os.Process.SIGNAL_USR1; 70 import static android.os.Process.SYSTEM_UID; 71 import static android.os.Process.THREAD_PRIORITY_FOREGROUND; 72 import static android.os.Process.THREAD_PRIORITY_TOP_APP_BOOST; 73 import static android.os.Process.ZYGOTE_POLICY_FLAG_BATCH_LAUNCH; 74 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY; 75 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE; 76 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS; 77 import static android.os.Process.ZYGOTE_PROCESS; 78 import static android.os.Process.getTotalMemory; 79 import static android.os.Process.isThreadInProcess; 80 import static android.os.Process.killProcess; 81 import static android.os.Process.killProcessQuiet; 82 import static android.os.Process.myPid; 83 import static android.os.Process.myUid; 84 import static android.os.Process.readProcFile; 85 import static android.os.Process.removeAllProcessGroups; 86 import static android.os.Process.sendSignal; 87 import static android.os.Process.setThreadPriority; 88 import static android.os.Process.setThreadScheduler; 89 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES; 90 import static android.provider.Settings.Global.DEBUG_APP; 91 import static android.provider.Settings.Global.NETWORK_ACCESS_TIMEOUT_MS; 92 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER; 93 import static android.text.format.DateUtils.DAY_IN_MILLIS; 94 95 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_CONFIGURATION; 96 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL; 97 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALLOWLISTS; 98 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR; 99 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK; 100 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP; 101 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; 102 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND; 103 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; 104 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 105 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK; 106 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ; 107 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER; 108 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES; 109 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE; 110 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP; 111 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; 112 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP; 113 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU; 114 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; 115 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK; 116 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ; 117 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER; 118 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES; 119 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE; 120 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS; 121 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 122 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 123 import static com.android.server.am.MemoryStatUtil.hasMemcg; 124 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 125 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP; 126 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH; 127 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION; 128 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK; 129 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH; 130 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD; 131 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD; 132 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD; 133 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD; 134 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD; 135 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD; 136 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD; 137 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD; 138 import static com.android.server.wm.ActivityTaskManagerService.DUMP_TOP_RESUMED_ACTIVITY; 139 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE; 140 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString; 141 142 import android.Manifest; 143 import android.Manifest.permission; 144 import android.annotation.NonNull; 145 import android.annotation.Nullable; 146 import android.annotation.UserIdInt; 147 import android.app.Activity; 148 import android.app.ActivityClient; 149 import android.app.ActivityManager; 150 import android.app.ActivityManager.PendingIntentInfo; 151 import android.app.ActivityManager.ProcessCapability; 152 import android.app.ActivityManager.RunningTaskInfo; 153 import android.app.ActivityManagerInternal; 154 import android.app.ActivityTaskManager.RootTaskInfo; 155 import android.app.ActivityThread; 156 import android.app.AnrController; 157 import android.app.AppGlobals; 158 import android.app.AppOpsManager; 159 import android.app.AppOpsManager.AttributionFlags; 160 import android.app.AppOpsManagerInternal.CheckOpsDelegate; 161 import android.app.ApplicationErrorReport; 162 import android.app.ApplicationExitInfo; 163 import android.app.ApplicationThreadConstants; 164 import android.app.BroadcastOptions; 165 import android.app.ContentProviderHolder; 166 import android.app.IActivityController; 167 import android.app.IActivityManager; 168 import android.app.IApplicationThread; 169 import android.app.IInstrumentationWatcher; 170 import android.app.INotificationManager; 171 import android.app.IProcessObserver; 172 import android.app.IServiceConnection; 173 import android.app.IStopUserCallback; 174 import android.app.ITaskStackListener; 175 import android.app.IUiAutomationConnection; 176 import android.app.IUidObserver; 177 import android.app.IUserSwitchObserver; 178 import android.app.Instrumentation; 179 import android.app.Notification; 180 import android.app.NotificationManager; 181 import android.app.PendingIntent; 182 import android.app.ProcessMemoryState; 183 import android.app.ProfilerInfo; 184 import android.app.PropertyInvalidatedCache; 185 import android.app.RemoteServiceException; 186 import android.app.SyncNotedAppOp; 187 import android.app.WaitResult; 188 import android.app.backup.BackupManager.OperationType; 189 import android.app.backup.IBackupManager; 190 import android.app.job.JobParameters; 191 import android.app.usage.UsageEvents; 192 import android.app.usage.UsageEvents.Event; 193 import android.app.usage.UsageStatsManager; 194 import android.app.usage.UsageStatsManagerInternal; 195 import android.appwidget.AppWidgetManager; 196 import android.appwidget.AppWidgetManagerInternal; 197 import android.content.AttributionSource; 198 import android.content.AutofillOptions; 199 import android.content.BroadcastReceiver; 200 import android.content.ComponentCallbacks2; 201 import android.content.ComponentName; 202 import android.content.ContentCaptureOptions; 203 import android.content.ContentProvider; 204 import android.content.ContentResolver; 205 import android.content.Context; 206 import android.content.IIntentReceiver; 207 import android.content.IIntentSender; 208 import android.content.Intent; 209 import android.content.IntentFilter; 210 import android.content.LocusId; 211 import android.content.pm.ActivityInfo; 212 import android.content.pm.ActivityPresentationInfo; 213 import android.content.pm.ApplicationInfo; 214 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy; 215 import android.content.pm.IPackageDataObserver; 216 import android.content.pm.IPackageManager; 217 import android.content.pm.IncrementalStatesInfo; 218 import android.content.pm.InstrumentationInfo; 219 import android.content.pm.PackageInfo; 220 import android.content.pm.PackageManager; 221 import android.content.pm.PackageManager.NameNotFoundException; 222 import android.content.pm.PackageManagerInternal; 223 import android.content.pm.ParceledListSlice; 224 import android.content.pm.PermissionInfo; 225 import android.content.pm.ProcessInfo; 226 import android.content.pm.ProviderInfo; 227 import android.content.pm.ProviderInfoList; 228 import android.content.pm.ResolveInfo; 229 import android.content.pm.SELinuxUtil; 230 import android.content.pm.ServiceInfo; 231 import android.content.pm.TestUtilityService; 232 import android.content.pm.UserInfo; 233 import android.content.pm.parsing.ParsingPackageUtils; 234 import android.content.res.CompatibilityInfo; 235 import android.content.res.Configuration; 236 import android.content.res.Resources; 237 import android.database.ContentObserver; 238 import android.graphics.Rect; 239 import android.hardware.display.DisplayManagerInternal; 240 import android.media.audiofx.AudioEffect; 241 import android.net.ConnectivityManager; 242 import android.net.Proxy; 243 import android.net.Uri; 244 import android.os.AppZygote; 245 import android.os.BatteryStats; 246 import android.os.Binder; 247 import android.os.BinderProxy; 248 import android.os.BugreportParams; 249 import android.os.Build; 250 import android.os.Bundle; 251 import android.os.Debug; 252 import android.os.DropBoxManager; 253 import android.os.FactoryTest; 254 import android.os.FileUtils; 255 import android.os.Handler; 256 import android.os.IBinder; 257 import android.os.IDeviceIdentifiersPolicyService; 258 import android.os.IPermissionController; 259 import android.os.IProcessInfoService; 260 import android.os.IProgressListener; 261 import android.os.Looper; 262 import android.os.Message; 263 import android.os.Parcel; 264 import android.os.ParcelFileDescriptor; 265 import android.os.PowerExemptionManager; 266 import android.os.PowerExemptionManager.ReasonCode; 267 import android.os.PowerExemptionManager.TempAllowListType; 268 import android.os.PowerManager; 269 import android.os.PowerManager.ServiceType; 270 import android.os.PowerManagerInternal; 271 import android.os.Process; 272 import android.os.RemoteCallback; 273 import android.os.RemoteException; 274 import android.os.ResultReceiver; 275 import android.os.ServiceManager; 276 import android.os.SharedMemory; 277 import android.os.ShellCallback; 278 import android.os.StrictMode; 279 import android.os.SystemClock; 280 import android.os.SystemProperties; 281 import android.os.Trace; 282 import android.os.TransactionTooLargeException; 283 import android.os.UserHandle; 284 import android.os.UserManager; 285 import android.os.WorkSource; 286 import android.os.incremental.IIncrementalService; 287 import android.os.incremental.IncrementalManager; 288 import android.os.incremental.IncrementalMetrics; 289 import android.os.storage.IStorageManager; 290 import android.os.storage.StorageManager; 291 import android.provider.DeviceConfig; 292 import android.provider.Settings; 293 import android.server.ServerProtoEnums; 294 import android.sysprop.InitProperties; 295 import android.sysprop.VoldProperties; 296 import android.telephony.TelephonyManager; 297 import android.text.TextUtils; 298 import android.text.format.DateUtils; 299 import android.text.style.SuggestionSpan; 300 import android.util.ArrayMap; 301 import android.util.ArraySet; 302 import android.util.EventLog; 303 import android.util.IntArray; 304 import android.util.Log; 305 import android.util.Pair; 306 import android.util.PrintWriterPrinter; 307 import android.util.Slog; 308 import android.util.SparseArray; 309 import android.util.SparseIntArray; 310 import android.util.TimeUtils; 311 import android.util.proto.ProtoOutputStream; 312 import android.util.proto.ProtoUtils; 313 import android.view.Gravity; 314 import android.view.LayoutInflater; 315 import android.view.View; 316 import android.view.WindowManager; 317 import android.view.autofill.AutofillManagerInternal; 318 319 import com.android.internal.annotations.CompositeRWLock; 320 import com.android.internal.annotations.GuardedBy; 321 import com.android.internal.annotations.VisibleForTesting; 322 import com.android.internal.app.IAppOpsActiveCallback; 323 import com.android.internal.app.IAppOpsCallback; 324 import com.android.internal.app.IAppOpsService; 325 import com.android.internal.app.ProcessMap; 326 import com.android.internal.app.SystemUserHomeActivity; 327 import com.android.internal.app.procstats.ProcessState; 328 import com.android.internal.app.procstats.ProcessStats; 329 import com.android.internal.content.PackageHelper; 330 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 331 import com.android.internal.notification.SystemNotificationChannels; 332 import com.android.internal.os.BackgroundThread; 333 import com.android.internal.os.BatteryStatsImpl; 334 import com.android.internal.os.BinderCallHeavyHitterWatcher.BinderCallHeavyHitterListener; 335 import com.android.internal.os.BinderCallHeavyHitterWatcher.HeavyHitterContainer; 336 import com.android.internal.os.BinderInternal; 337 import com.android.internal.os.BinderTransactionNameResolver; 338 import com.android.internal.os.ByteTransferPipe; 339 import com.android.internal.os.IResultReceiver; 340 import com.android.internal.os.ProcessCpuTracker; 341 import com.android.internal.os.TransferPipe; 342 import com.android.internal.os.Zygote; 343 import com.android.internal.policy.AttributeCache; 344 import com.android.internal.protolog.common.ProtoLog; 345 import com.android.internal.util.ArrayUtils; 346 import com.android.internal.util.DumpUtils; 347 import com.android.internal.util.FastPrintWriter; 348 import com.android.internal.util.FrameworkStatsLog; 349 import com.android.internal.util.MemInfoReader; 350 import com.android.internal.util.Preconditions; 351 import com.android.internal.util.function.DecFunction; 352 import com.android.internal.util.function.HeptFunction; 353 import com.android.internal.util.function.HexFunction; 354 import com.android.internal.util.function.QuadFunction; 355 import com.android.internal.util.function.QuintFunction; 356 import com.android.internal.util.function.TriFunction; 357 import com.android.internal.util.function.UndecFunction; 358 import com.android.server.AlarmManagerInternal; 359 import com.android.server.DeviceIdleInternal; 360 import com.android.server.DisplayThread; 361 import com.android.server.IntentResolver; 362 import com.android.server.IoThread; 363 import com.android.server.LocalManagerRegistry; 364 import com.android.server.LocalServices; 365 import com.android.server.LockGuard; 366 import com.android.server.NetworkManagementInternal; 367 import com.android.server.PackageWatchdog; 368 import com.android.server.ServiceThread; 369 import com.android.server.SystemConfig; 370 import com.android.server.SystemService; 371 import com.android.server.SystemServiceManager; 372 import com.android.server.ThreadPriorityBooster; 373 import com.android.server.UserspaceRebootLogger; 374 import com.android.server.Watchdog; 375 import com.android.server.am.LowMemDetector.MemFactor; 376 import com.android.server.appop.AppOpsService; 377 import com.android.server.compat.PlatformCompat; 378 import com.android.server.contentcapture.ContentCaptureManagerInternal; 379 import com.android.server.firewall.IntentFirewall; 380 import com.android.server.graphics.fonts.FontManagerInternal; 381 import com.android.server.job.JobSchedulerInternal; 382 import com.android.server.os.NativeTombstoneManager; 383 import com.android.server.pm.Installer; 384 import com.android.server.pm.parsing.pkg.AndroidPackage; 385 import com.android.server.pm.permission.PermissionManagerServiceInternal; 386 import com.android.server.uri.GrantUri; 387 import com.android.server.uri.NeededUriGrants; 388 import com.android.server.uri.UriGrantsManagerInternal; 389 import com.android.server.utils.PriorityDump; 390 import com.android.server.utils.TimingsTraceAndSlog; 391 import com.android.server.vr.VrManagerInternal; 392 import com.android.server.wm.ActivityMetricsLaunchObserver; 393 import com.android.server.wm.ActivityServiceConnectionsHolder; 394 import com.android.server.wm.ActivityTaskManagerInternal; 395 import com.android.server.wm.ActivityTaskManagerService; 396 import com.android.server.wm.WindowManagerInternal; 397 import com.android.server.wm.WindowManagerService; 398 import com.android.server.wm.WindowProcessController; 399 400 import dalvik.system.VMRuntime; 401 402 import libcore.util.EmptyArray; 403 404 import java.io.File; 405 import java.io.FileDescriptor; 406 import java.io.FileNotFoundException; 407 import java.io.FileOutputStream; 408 import java.io.IOException; 409 import java.io.InputStreamReader; 410 import java.io.PrintWriter; 411 import java.io.StringWriter; 412 import java.nio.charset.StandardCharsets; 413 import java.text.SimpleDateFormat; 414 import java.util.ArrayList; 415 import java.util.Arrays; 416 import java.util.Collections; 417 import java.util.Comparator; 418 import java.util.Date; 419 import java.util.HashMap; 420 import java.util.HashSet; 421 import java.util.Iterator; 422 import java.util.LinkedList; 423 import java.util.List; 424 import java.util.Locale; 425 import java.util.Map; 426 import java.util.Set; 427 import java.util.UUID; 428 import java.util.concurrent.Executor; 429 import java.util.concurrent.atomic.AtomicInteger; 430 431 public class ActivityManagerService extends IActivityManager.Stub 432 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock { 433 434 private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED = 435 "persist.sys.device_provisioned"; 436 437 static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM; 438 static final String TAG_BACKUP = TAG + POSTFIX_BACKUP; 439 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 440 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 441 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION; 442 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; 443 static final String TAG_LRU = TAG + POSTFIX_LRU; 444 static final String TAG_MU = TAG + POSTFIX_MU; 445 static final String TAG_NETWORK = TAG + POSTFIX_NETWORK; 446 static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ; 447 private static final String TAG_POWER = TAG + POSTFIX_POWER; 448 static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES; 449 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 450 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 451 static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS; 452 453 // Mock "pretend we're idle now" broadcast action to the job scheduler; declared 454 // here so that while the job scheduler can depend on AMS, the other way around 455 // need not be the case. 456 public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE"; 457 458 private static final String INTENT_BUGREPORT_REQUESTED = 459 "com.android.internal.intent.action.BUGREPORT_REQUESTED"; 460 private static final String SHELL_APP_PACKAGE = "com.android.shell"; 461 462 // The flags that are set for all calls we make to the package manager. 463 public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 464 465 static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed"; 466 467 public static final String ANR_TRACE_DIR = "/data/anr"; 468 469 // Maximum number of receivers an app can register. 470 private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000; 471 472 // How long we wait for a launched process to attach to the activity manager 473 // before we decide it's never going to come up for real. 474 static final int PROC_START_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 475 // How long we wait to kill an application zygote, after the last process using 476 // it has gone away. 477 static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000; 478 479 // How long we wait for a launched process to attach to the activity manager 480 // before we decide it's never going to come up for real, when the process was 481 // started with a wrapper for instrumentation (such as Valgrind) because it 482 // could take much longer than usual. 483 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 484 485 // How long we allow a receiver to run before giving up on it. 486 static final int BROADCAST_FG_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 487 static final int BROADCAST_BG_TIMEOUT = 60 * 1000 * Build.HW_TIMEOUT_MULTIPLIER; 488 489 public static final int MY_PID = myPid(); 490 491 static final String[] EMPTY_STRING_ARRAY = new String[0]; 492 493 // How many bytes to write into the dropbox log before truncating 494 static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024; 495 // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count 496 // as one line, but close enough for now. 497 static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100; 498 499 // Necessary ApplicationInfo flags to mark an app as persistent 500 static final int PERSISTENT_MASK = 501 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT; 502 503 // Intent sent when remote bugreport collection has been completed 504 private static final String INTENT_REMOTE_BUGREPORT_FINISHED = 505 "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED"; 506 507 // If set, we will push process association information in to procstats. 508 static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true; 509 510 /** 511 * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}. 512 */ 513 private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec 514 515 // The minimum memory growth threshold (in KB) for low RAM devices. 516 private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB 517 518 /** 519 * The number of binder proxies we need to have before we start warning and 520 * dumping debug info. 521 */ 522 private static final int BINDER_PROXY_HIGH_WATERMARK = 6000; 523 524 /** 525 * Low watermark that needs to be met before we consider dumping info again, 526 * after already hitting the high watermark. 527 */ 528 private static final int BINDER_PROXY_LOW_WATERMARK = 5500; 529 530 // Max character limit for a notification title. If the notification title is larger than this 531 // the notification will not be legible to the user. 532 private static final int MAX_BUGREPORT_TITLE_SIZE = 50; 533 private static final int MAX_BUGREPORT_DESCRIPTION_SIZE = 150; 534 535 private static final int NATIVE_DUMP_TIMEOUT_MS = 536 2000 * Build.HW_TIMEOUT_MULTIPLIER; // 2 seconds; 537 private static final int JAVA_DUMP_MINIMUM_SIZE = 100; // 100 bytes. 538 539 OomAdjuster mOomAdjuster; 540 541 static final String EXTRA_TITLE = "android.intent.extra.TITLE"; 542 static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION"; 543 static final String EXTRA_BUGREPORT_TYPE = "android.intent.extra.BUGREPORT_TYPE"; 544 545 /** 546 * The maximum number of bytes that {@link #setProcessStateSummary} accepts. 547 * 548 * @see {@link android.app.ActivityManager#setProcessStateSummary(byte[])} 549 */ 550 static final int MAX_STATE_DATA_SIZE = 128; 551 552 /** All system services */ 553 SystemServiceManager mSystemServiceManager; 554 555 private Installer mInstaller; 556 557 final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter(); 558 559 @CompositeRWLock({"this", "mProcLock"}) 560 final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>(); 561 562 public final IntentFirewall mIntentFirewall; 563 564 public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler(); 565 566 /** 567 * The global lock for AMS, it's de-facto the ActivityManagerService object as of now. 568 */ 569 final ActivityManagerGlobalLock mGlobalLock = ActivityManagerService.this; 570 571 /** 572 * Whether or not to enable the {@link #mProcLock}. If {@code false}, the {@link #mProcLock} 573 * will be equivalent to the {@link #mGlobalLock}. 574 */ 575 private static final boolean ENABLE_PROC_LOCK = true; 576 577 /** 578 * The lock for process management. 579 * 580 * <p> 581 * This lock is widely used in conjunction with the {@link #mGlobalLock} at present, 582 * where it'll require any of the locks to read from a data class, and both of the locks 583 * to write into that data class. 584 * 585 * For the naming convention of function suffixes: 586 * <ul> 587 * <li>-LOSP: Locked with any Of global am Service or Process lock</li> 588 * <li>-LSP: Locked with both of global am Service and Process lock</li> 589 * <li>-Locked: Locked with global am service lock alone</li> 590 * <li>-LPr: Locked with Process lock alone</li> 591 * </ul> 592 * For the simplicity, the getters/setters of the fields in data classes usually don't end with 593 * the above suffixes even if they're guarded by the locks here. 594 * </p> 595 * 596 * <p> 597 * In terms of locking order, it should be right below to the {@link #mGlobalLock}, 598 * and above everything else which used to be underneath the {@link #mGlobalLock}. 599 * As of today, the core components(services/providers/broadcasts) are still guarded by 600 * the {@link #mGlobalLock} alone, so be cautious, avoid from acquiring the {@link #mGlobalLock} 601 * while holding this lock. 602 * </p> 603 * 604 */ 605 final ActivityManagerGlobalLock mProcLock = ENABLE_PROC_LOCK 606 ? new ActivityManagerProcLock() : mGlobalLock; 607 608 // Whether we should use SCHED_FIFO for UI and RenderThreads. 609 final boolean mUseFifoUiScheduling; 610 611 // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED. 612 // For simplicity, since we statically declare the size of the array of BroadcastQueues, 613 // we still create this new offload queue, but never ever put anything on it. 614 final boolean mEnableOffloadQueue; 615 616 final BroadcastQueue mFgBroadcastQueue; 617 final BroadcastQueue mBgBroadcastQueue; 618 final BroadcastQueue mOffloadBroadcastQueue; 619 // Convenient for easy iteration over the queues. Foreground is first 620 // so that dispatch of foreground broadcasts gets precedence. 621 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[3]; 622 623 @GuardedBy("this") 624 BroadcastStats mLastBroadcastStats; 625 626 @GuardedBy("this") 627 BroadcastStats mCurBroadcastStats; 628 629 TraceErrorLogger mTraceErrorLogger; 630 broadcastQueueForIntent(Intent intent)631 BroadcastQueue broadcastQueueForIntent(Intent intent) { 632 if (isOnOffloadQueue(intent.getFlags())) { 633 if (DEBUG_BROADCAST_BACKGROUND) { 634 Slog.i(TAG_BROADCAST, 635 "Broadcast intent " + intent + " on offload queue"); 636 } 637 return mOffloadBroadcastQueue; 638 } 639 640 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 641 if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST, 642 "Broadcast intent " + intent + " on " 643 + (isFg ? "foreground" : "background") + " queue"); 644 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 645 } 646 647 /** 648 * The package name of the DeviceOwner. This package is not permitted to have its data cleared. 649 * <p>Not actually used</p> 650 */ 651 private volatile String mDeviceOwnerName; 652 653 private volatile int mDeviceOwnerUid = INVALID_UID; 654 655 /** 656 * Map userId to its companion app uids. 657 */ 658 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>(); 659 660 /** 661 * The profile owner UIDs. 662 */ 663 private ArraySet<Integer> mProfileOwnerUids = null; 664 665 final UserController mUserController; 666 @VisibleForTesting 667 public final PendingIntentController mPendingIntentController; 668 669 final AppErrors mAppErrors; 670 final PackageWatchdog mPackageWatchdog; 671 672 /** 673 * Indicates the maximum time spent waiting for the network rules to get updated. 674 */ 675 @VisibleForTesting 676 long mWaitForNetworkTimeoutMs; 677 678 /** 679 * Uids of apps with current active camera sessions. Access synchronized on 680 * the IntArray instance itself, and no other locks must be acquired while that 681 * one is held. 682 */ 683 @GuardedBy("mActiveCameraUids") 684 final IntArray mActiveCameraUids = new IntArray(4); 685 686 /** 687 * Helper class which strips out priority and proto arguments then calls the dump function with 688 * the appropriate arguments. If priority arguments are omitted, function calls the legacy 689 * dump command. 690 * If priority arguments are omitted all sections are dumped, otherwise sections are dumped 691 * according to their priority. 692 */ 693 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() { 694 @Override 695 public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args, 696 boolean asProto) { 697 if (asProto) return; 698 doDump(fd, pw, new String[]{"activities"}, asProto); 699 doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto); 700 } 701 702 @Override 703 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 704 doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto); 705 } 706 707 @Override 708 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 709 doDump(fd, pw, args, asProto); 710 } 711 }; 712 713 private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster( 714 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY); 715 boostPriorityForLockedSection()716 static void boostPriorityForLockedSection() { 717 sThreadPriorityBooster.boost(); 718 } 719 resetPriorityAfterLockedSection()720 static void resetPriorityAfterLockedSection() { 721 sThreadPriorityBooster.reset(); 722 } 723 724 private static ThreadPriorityBooster sProcThreadPriorityBooster = new ThreadPriorityBooster( 725 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_PROC); 726 boostPriorityForProcLockedSection()727 static void boostPriorityForProcLockedSection() { 728 if (ENABLE_PROC_LOCK) { 729 sProcThreadPriorityBooster.boost(); 730 } else { 731 sThreadPriorityBooster.boost(); 732 } 733 } 734 resetPriorityAfterProcLockedSection()735 static void resetPriorityAfterProcLockedSection() { 736 if (ENABLE_PROC_LOCK) { 737 sProcThreadPriorityBooster.reset(); 738 } else { 739 sThreadPriorityBooster.reset(); 740 } 741 } 742 743 /** 744 * Process management. 745 */ 746 final ProcessList mProcessList; 747 748 /** 749 * The list of phantom processes. 750 * @see PhantomProcessRecord 751 */ 752 final PhantomProcessList mPhantomProcessList; 753 754 /** 755 * Tracking long-term execution of processes to look for abuse and other 756 * bad app behavior. 757 */ 758 final ProcessStatsService mProcessStats; 759 760 /** 761 * Non-persistent appId allowlist for background restrictions 762 */ 763 @CompositeRWLock({"this", "mProcLock"}) 764 private int[] mBackgroundAppIdAllowlist = new int[] { 765 BLUETOOTH_UID 766 }; 767 768 /** 769 * Broadcast actions that will always be deliverable to unlaunched/background apps 770 */ 771 @GuardedBy("this") 772 private ArraySet<String> mBackgroundLaunchBroadcasts; 773 774 /** 775 * When an app has restrictions on the other apps that can have associations with it, 776 * it appears here with a set of the allowed apps and also track debuggability of the app. 777 */ 778 @GuardedBy("this") 779 private ArrayMap<String, PackageAssociationInfo> mAllowedAssociations; 780 781 /** 782 * Tracks association information for a particular package along with debuggability. 783 * <p> Associations for a package A are allowed to package B if B is part of the 784 * allowed associations for A or if A is debuggable. 785 */ 786 private final class PackageAssociationInfo { 787 private final String mSourcePackage; 788 private final ArraySet<String> mAllowedPackageAssociations; 789 private boolean mIsDebuggable; 790 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)791 PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, 792 boolean isDebuggable) { 793 mSourcePackage = sourcePackage; 794 mAllowedPackageAssociations = allowedPackages; 795 mIsDebuggable = isDebuggable; 796 } 797 798 /** 799 * Returns true if {@code mSourcePackage} is allowed association with 800 * {@code targetPackage}. 801 */ isPackageAssociationAllowed(String targetPackage)802 boolean isPackageAssociationAllowed(String targetPackage) { 803 return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage); 804 } 805 isDebuggable()806 boolean isDebuggable() { 807 return mIsDebuggable; 808 } 809 setDebuggable(boolean isDebuggable)810 void setDebuggable(boolean isDebuggable) { 811 mIsDebuggable = isDebuggable; 812 } 813 getAllowedPackageAssociations()814 ArraySet<String> getAllowedPackageAssociations() { 815 return mAllowedPackageAssociations; 816 } 817 } 818 819 /** 820 * These are the currently running processes for which we have a ProcessInfo. 821 * Note: needs to be static since the permission checking call chain is static. This 822 * all probably should be refactored into a separate permission checking object. 823 */ 824 @GuardedBy("sActiveProcessInfoSelfLocked") 825 static final SparseArray<ProcessInfo> sActiveProcessInfoSelfLocked = new SparseArray<>(); 826 827 /** 828 * All of the processes we currently have running organized by pid. 829 * The keys are the pid running the application. 830 * 831 * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock! 832 */ 833 final PidMap mPidsSelfLocked = new PidMap(); 834 static final class PidMap { 835 private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>(); 836 get(int pid)837 ProcessRecord get(int pid) { 838 return mPidMap.get(pid); 839 } 840 size()841 int size() { 842 return mPidMap.size(); 843 } 844 valueAt(int index)845 ProcessRecord valueAt(int index) { 846 return mPidMap.valueAt(index); 847 } 848 keyAt(int index)849 int keyAt(int index) { 850 return mPidMap.keyAt(index); 851 } 852 indexOfKey(int key)853 int indexOfKey(int key) { 854 return mPidMap.indexOfKey(key); 855 } 856 doAddInternal(int pid, ProcessRecord app)857 void doAddInternal(int pid, ProcessRecord app) { 858 mPidMap.put(pid, app); 859 } 860 doRemoveInternal(int pid, ProcessRecord app)861 boolean doRemoveInternal(int pid, ProcessRecord app) { 862 final ProcessRecord existingApp = mPidMap.get(pid); 863 if (existingApp != null && existingApp.getStartSeq() == app.getStartSeq()) { 864 mPidMap.remove(pid); 865 return true; 866 } 867 return false; 868 } 869 doRemoveIfNoThreadInternal(int pid, ProcessRecord app)870 boolean doRemoveIfNoThreadInternal(int pid, ProcessRecord app) { 871 if (app == null || app.getThread() != null) { 872 return false; 873 } 874 return doRemoveInternal(pid, app); 875 } 876 } 877 878 private final PendingStartActivityUids mPendingStartActivityUids; 879 880 /** 881 * Puts the process record in the map. 882 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 883 * method. 884 */ 885 @GuardedBy("this") addPidLocked(ProcessRecord app)886 void addPidLocked(ProcessRecord app) { 887 final int pid = app.getPid(); 888 synchronized (mPidsSelfLocked) { 889 mPidsSelfLocked.doAddInternal(pid, app); 890 } 891 synchronized (sActiveProcessInfoSelfLocked) { 892 if (app.processInfo != null) { 893 sActiveProcessInfoSelfLocked.put(pid, app.processInfo); 894 } else { 895 sActiveProcessInfoSelfLocked.remove(pid); 896 } 897 } 898 mAtmInternal.onProcessMapped(pid, app.getWindowProcessController()); 899 } 900 901 /** 902 * Removes the process record from the map. 903 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 904 * method. 905 */ 906 @GuardedBy("this") removePidLocked(int pid, ProcessRecord app)907 void removePidLocked(int pid, ProcessRecord app) { 908 final boolean removed; 909 synchronized (mPidsSelfLocked) { 910 removed = mPidsSelfLocked.doRemoveInternal(pid, app); 911 } 912 if (removed) { 913 synchronized (sActiveProcessInfoSelfLocked) { 914 sActiveProcessInfoSelfLocked.remove(pid); 915 } 916 mAtmInternal.onProcessUnMapped(pid); 917 } 918 } 919 920 /** 921 * Removes the process record from the map if it doesn't have a thread. 922 * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this 923 * method. 924 */ 925 @GuardedBy("this") removePidIfNoThreadLocked(ProcessRecord app)926 private boolean removePidIfNoThreadLocked(ProcessRecord app) { 927 final boolean removed; 928 final int pid = app.getPid(); 929 synchronized (mPidsSelfLocked) { 930 removed = mPidsSelfLocked.doRemoveIfNoThreadInternal(pid, app); 931 } 932 if (removed) { 933 synchronized (sActiveProcessInfoSelfLocked) { 934 sActiveProcessInfoSelfLocked.remove(pid); 935 } 936 mAtmInternal.onProcessUnMapped(pid); 937 } 938 return removed; 939 } 940 941 /** 942 * All of the processes that have been forced to be important. The key 943 * is the pid of the caller who requested it (we hold a death 944 * link on it). 945 */ 946 abstract class ImportanceToken implements IBinder.DeathRecipient { 947 final int pid; 948 final IBinder token; 949 final String reason; 950 ImportanceToken(int _pid, IBinder _token, String _reason)951 ImportanceToken(int _pid, IBinder _token, String _reason) { 952 pid = _pid; 953 token = _token; 954 reason = _reason; 955 } 956 957 @Override toString()958 public String toString() { 959 return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this)) 960 + " " + reason + " " + pid + " " + token + " }"; 961 } 962 dumpDebug(ProtoOutputStream proto, long fieldId)963 void dumpDebug(ProtoOutputStream proto, long fieldId) { 964 final long pToken = proto.start(fieldId); 965 proto.write(ImportanceTokenProto.PID, pid); 966 if (token != null) { 967 proto.write(ImportanceTokenProto.TOKEN, token.toString()); 968 } 969 proto.write(ImportanceTokenProto.REASON, reason); 970 proto.end(pToken); 971 } 972 } 973 @GuardedBy("this") 974 final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>(); 975 976 /** 977 * List of records for processes that someone had tried to start before the 978 * system was ready. We don't start them at that point, but ensure they 979 * are started by the time booting is complete. 980 */ 981 @GuardedBy("this") 982 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 983 984 /** 985 * List of persistent applications that are in the process 986 * of being started. 987 */ 988 @GuardedBy("this") 989 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 990 991 private final ActivityMetricsLaunchObserver mActivityLaunchObserver = 992 new ActivityMetricsLaunchObserver() { 993 @Override 994 public void onActivityLaunched(byte[] activity, int temperature) { 995 mAppProfiler.onActivityLaunched(); 996 } 997 998 // The other observer methods are unused 999 @Override 1000 public void onIntentStarted(Intent intent, long timestampNs) { 1001 } 1002 1003 @Override 1004 public void onIntentFailed() { 1005 } 1006 1007 @Override 1008 public void onActivityLaunchCancelled(byte[] abortingActivity) { 1009 } 1010 1011 @Override 1012 public void onActivityLaunchFinished(byte[] finalActivity, long timestampNs) { 1013 } 1014 1015 @Override 1016 public void onReportFullyDrawn(byte[] finalActivity, long timestampNs) { 1017 } 1018 }; 1019 1020 private volatile boolean mBinderTransactionTrackingEnabled = false; 1021 1022 /** 1023 * Fingerprints (hashCode()) of stack traces that we've 1024 * already logged DropBox entries for. Guarded by itself. If 1025 * something (rogue user app) forces this over 1026 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 1027 */ 1028 @GuardedBy("mAlreadyLoggedViolatedStacks") 1029 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 1030 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 1031 1032 /** 1033 * Keeps track of all IIntentReceivers that have been registered for broadcasts. 1034 * Hash keys are the receiver IBinder, hash value is a ReceiverList. 1035 */ 1036 @GuardedBy("this") 1037 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>(); 1038 1039 /** 1040 * Resolver for broadcast intents to registered receivers. 1041 * Holds BroadcastFilter (subclass of IntentFilter). 1042 */ 1043 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 1044 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 1045 @Override 1046 protected boolean allowFilterResult( 1047 BroadcastFilter filter, List<BroadcastFilter> dest) { 1048 IBinder target = filter.receiverList.receiver.asBinder(); 1049 for (int i = dest.size() - 1; i >= 0; i--) { 1050 if (dest.get(i).receiverList.receiver.asBinder() == target) { 1051 return false; 1052 } 1053 } 1054 return true; 1055 } 1056 1057 @Override 1058 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 1059 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 1060 || userId == filter.owningUserId) { 1061 return super.newResult(filter, match, userId); 1062 } 1063 return null; 1064 } 1065 1066 @Override 1067 protected IntentFilter getIntentFilter(@NonNull BroadcastFilter input) { 1068 return input; 1069 } 1070 1071 @Override 1072 protected BroadcastFilter[] newArray(int size) { 1073 return new BroadcastFilter[size]; 1074 } 1075 1076 @Override 1077 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 1078 return packageName.equals(filter.packageName); 1079 } 1080 }; 1081 1082 /** 1083 * State of all active sticky broadcasts per user. Keys are the action of the 1084 * sticky Intent, values are an ArrayList of all broadcasted intents with 1085 * that action (which should usually be one). The SparseArray is keyed 1086 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 1087 * for stickies that are sent to all users. 1088 */ 1089 @GuardedBy("this") 1090 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts = 1091 new SparseArray<ArrayMap<String, ArrayList<Intent>>>(); 1092 1093 final ActiveServices mServices; 1094 1095 final static class Association { 1096 final int mSourceUid; 1097 final String mSourceProcess; 1098 final int mTargetUid; 1099 final ComponentName mTargetComponent; 1100 final String mTargetProcess; 1101 1102 int mCount; 1103 long mTime; 1104 1105 int mNesting; 1106 long mStartTime; 1107 1108 // states of the source process when the bind occurred. 1109 int mLastState = ActivityManager.MAX_PROCESS_STATE + 1; 1110 long mLastStateUptime; 1111 long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE 1112 - ActivityManager.MIN_PROCESS_STATE+1]; 1113 Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1114 Association(int sourceUid, String sourceProcess, int targetUid, 1115 ComponentName targetComponent, String targetProcess) { 1116 mSourceUid = sourceUid; 1117 mSourceProcess = sourceProcess; 1118 mTargetUid = targetUid; 1119 mTargetComponent = targetComponent; 1120 mTargetProcess = targetProcess; 1121 } 1122 } 1123 1124 /** 1125 * When service association tracking is enabled, this is all of the associations we 1126 * have seen. Mapping is target uid -> target component -> source uid -> source process name 1127 * -> association data. 1128 */ 1129 @GuardedBy("this") 1130 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>> 1131 mAssociations = new SparseArray<>(); 1132 boolean mTrackingAssociations; 1133 1134 /** 1135 * Backup/restore process management 1136 */ 1137 @GuardedBy("this") 1138 final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>(); 1139 1140 final ContentProviderHelper mCpHelper; 1141 1142 CoreSettingsObserver mCoreSettingsObserver; 1143 1144 /** 1145 * All information we have collected about the runtime performance of 1146 * any user id that can impact battery performance. 1147 */ 1148 final BatteryStatsService mBatteryStatsService; 1149 1150 /** 1151 * Information about component usage 1152 */ 1153 volatile UsageStatsManagerInternal mUsageStatsService; 1154 1155 /** 1156 * Access to DeviceIdleController service. 1157 */ 1158 DeviceIdleInternal mLocalDeviceIdleController; 1159 1160 /** 1161 * Power-save allowlisted app-ids (not including except-idle-allowlisted ones). 1162 */ 1163 @CompositeRWLock({"this", "mProcLock"}) 1164 int[] mDeviceIdleAllowlist = new int[0]; 1165 1166 /** 1167 * Power-save allowlisted app-ids (including except-idle-allowlisted ones). 1168 */ 1169 @CompositeRWLock({"this", "mProcLock"}) 1170 int[] mDeviceIdleExceptIdleAllowlist = new int[0]; 1171 1172 /** 1173 * Set of app ids that are temporarily allowed to escape bg check due to high-pri message 1174 */ 1175 @CompositeRWLock({"this", "mProcLock"}) 1176 int[] mDeviceIdleTempAllowlist = new int[0]; 1177 1178 static final class PendingTempAllowlist { 1179 final int targetUid; 1180 final long duration; 1181 final String tag; 1182 final int type; 1183 final @ReasonCode int reasonCode; 1184 final int callingUid; 1185 PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, int type, int callingUid)1186 PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, 1187 int type, int callingUid) { 1188 this.targetUid = targetUid; 1189 this.duration = duration; 1190 this.tag = tag; 1191 this.type = type; 1192 this.reasonCode = reasonCode; 1193 this.callingUid = callingUid; 1194 } 1195 dumpDebug(ProtoOutputStream proto, long fieldId)1196 void dumpDebug(ProtoOutputStream proto, long fieldId) { 1197 final long token = proto.start(fieldId); 1198 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID, 1199 targetUid); 1200 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS, 1201 duration); 1202 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag); 1203 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TYPE, type); 1204 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.REASON_CODE, 1205 reasonCode); 1206 proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.CALLING_UID, 1207 callingUid); 1208 proto.end(token); 1209 } 1210 } 1211 1212 @CompositeRWLock({"this", "mProcLock"}) 1213 final PendingTempAllowlists mPendingTempAllowlist = new PendingTempAllowlists(this); 1214 1215 public static final class FgsTempAllowListItem { 1216 final long mDuration; 1217 final @PowerExemptionManager.ReasonCode int mReasonCode; 1218 final String mReason; 1219 final int mCallingUid; 1220 FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, String reason, int callingUid)1221 FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, 1222 String reason, int callingUid) { 1223 mDuration = duration; 1224 mReasonCode = reasonCode; 1225 mReason = reason; 1226 mCallingUid = callingUid; 1227 } 1228 dump(PrintWriter pw)1229 void dump(PrintWriter pw) { 1230 pw.print(" duration=" + mDuration + 1231 " callingUid=" + UserHandle.formatUid(mCallingUid) + 1232 " reasonCode=" + PowerExemptionManager.reasonCodeToString(mReasonCode) + 1233 " reason=" + mReason); 1234 } 1235 } 1236 1237 /** 1238 * The temp-allowlist that is allowed to start FGS from background. 1239 */ 1240 @CompositeRWLock({"this", "mProcLock"}) 1241 final FgsTempAllowList<FgsTempAllowListItem> mFgsStartTempAllowList = 1242 new FgsTempAllowList(); 1243 1244 static final FgsTempAllowListItem FAKE_TEMP_ALLOW_LIST_ITEM = new FgsTempAllowListItem( 1245 Long.MAX_VALUE, REASON_SYSTEM_ALLOW_LISTED, "", INVALID_UID); 1246 1247 /* 1248 * List of uids that are allowed to have while-in-use permission when FGS is started from 1249 * background. 1250 */ 1251 private final FgsTempAllowList<String> mFgsWhileInUseTempAllowList = 1252 new FgsTempAllowList(); 1253 1254 /** 1255 * Information about and control over application operations 1256 */ 1257 final AppOpsService mAppOpsService; 1258 private AppOpsManager mAppOpsManager; 1259 1260 /** 1261 * List of initialization arguments to pass to all processes when binding applications to them. 1262 * For example, references to the commonly used services. 1263 */ 1264 ArrayMap<String, IBinder> mAppBindArgs; 1265 ArrayMap<String, IBinder> mIsolatedAppBindArgs; 1266 1267 volatile boolean mProcessesReady = false; 1268 volatile boolean mSystemReady = false; 1269 volatile boolean mOnBattery = false; 1270 final int mFactoryTest; 1271 volatile boolean mBooting = false; 1272 1273 @GuardedBy("this") boolean mCallFinishBooting = false; 1274 @GuardedBy("this") boolean mBootAnimationComplete = false; 1275 1276 final Context mContext; 1277 1278 /** 1279 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can 1280 * change at runtime. Use mContext for non-UI purposes. 1281 */ 1282 final Context mUiContext; 1283 1284 /** 1285 * Last time (in uptime) at which we checked for power usage. 1286 */ 1287 @GuardedBy("mProcLock") 1288 long mLastPowerCheckUptime; 1289 1290 /** 1291 * For some direct access we need to power manager. 1292 */ 1293 PowerManagerInternal mLocalPowerManager; 1294 1295 /** 1296 * State of external calls telling us if the device is awake or asleep. 1297 */ 1298 AtomicInteger mWakefulness = new AtomicInteger(PowerManagerInternal.WAKEFULNESS_AWAKE); 1299 1300 /** 1301 * The uptime of the last time we performed idle maintenance. 1302 */ 1303 @GuardedBy("mProcLock") 1304 long mLastIdleTime = SystemClock.uptimeMillis(); 1305 1306 /** 1307 * For reporting to battery stats the current top application. 1308 * 1309 * <p>It has its own lock to avoid from the need of double locking if using the global 1310 * ActivityManagerService lock and proc lock to guard it.</p> 1311 */ 1312 @GuardedBy("mCurResumedAppLock") 1313 private String mCurResumedPackage = null; 1314 1315 @GuardedBy("mCurResumedAppLock") 1316 private int mCurResumedUid = -1; 1317 1318 /** 1319 * Dedicated lock for {@link #mCurResumedPackage} and {@link #mCurResumedUid}. 1320 */ 1321 private final Object mCurResumedAppLock = new Object(); 1322 1323 /** 1324 * For reporting to battery stats the apps currently running foreground 1325 * service. The ProcessMap is package/uid tuples; each of these contain 1326 * an array of the currently foreground processes. 1327 */ 1328 @GuardedBy("this") 1329 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1330 = new ProcessMap<ArrayList<ProcessRecord>>(); 1331 1332 /** 1333 * Set if the systemServer made a call to enterSafeMode. 1334 */ 1335 @GuardedBy("this") 1336 boolean mSafeMode; 1337 1338 @GuardedBy("this") 1339 private String mDebugApp = null; 1340 1341 @GuardedBy("this") 1342 private boolean mWaitForDebugger = false; 1343 1344 @GuardedBy("this") 1345 private boolean mDebugTransient = false; 1346 1347 @GuardedBy("this") 1348 private String mOrigDebugApp = null; 1349 1350 @GuardedBy("this") 1351 private boolean mOrigWaitForDebugger = false; 1352 1353 @GuardedBy("this") 1354 boolean mAlwaysFinishActivities = false; 1355 1356 @GuardedBy("mProcLock") 1357 private String mTrackAllocationApp = null; 1358 1359 @GuardedBy("this") 1360 String mNativeDebuggingApp = null; 1361 1362 final Injector mInjector; 1363 1364 static final class ProcessChangeItem { 1365 static final int CHANGE_ACTIVITIES = 1<<0; 1366 static final int CHANGE_FOREGROUND_SERVICES = 1<<1; 1367 static final int CHANGE_CAPABILITY = 1<<2; 1368 int changes; 1369 int uid; 1370 int pid; 1371 int processState; 1372 int capability; 1373 boolean foregroundActivities; 1374 int foregroundServiceTypes; 1375 } 1376 1377 @GuardedBy("mOomAdjObserverLock") 1378 OomAdjObserver mCurOomAdjObserver; 1379 1380 @GuardedBy("mOomAdjObserverLock") 1381 int mCurOomAdjUid; 1382 1383 /** 1384 * Dedicated lock for {@link #mCurOomAdjObserver} and {@link #mCurOomAdjUid}. 1385 */ 1386 final Object mOomAdjObserverLock = new Object(); 1387 1388 interface OomAdjObserver { onOomAdjMessage(String msg)1389 void onOomAdjMessage(String msg); 1390 } 1391 1392 final AnrHelper mAnrHelper = new AnrHelper(this); 1393 1394 /** Set to true after the system has finished booting. */ 1395 volatile boolean mBooted = false; 1396 1397 /** 1398 * Current boot phase. 1399 */ 1400 int mBootPhase; 1401 1402 @VisibleForTesting 1403 public WindowManagerService mWindowManager; 1404 WindowManagerInternal mWmInternal; 1405 @VisibleForTesting 1406 public ActivityTaskManagerService mActivityTaskManager; 1407 @VisibleForTesting 1408 public ActivityTaskManagerInternal mAtmInternal; 1409 UriGrantsManagerInternal mUgmInternal; 1410 @VisibleForTesting 1411 public final ActivityManagerInternal mInternal; 1412 final ActivityThread mSystemThread; 1413 1414 final UidObserverController mUidObserverController; 1415 1416 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1417 final ProcessRecord mApp; 1418 final int mPid; 1419 final IApplicationThread mAppThread; 1420 AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1421 AppDeathRecipient(ProcessRecord app, int pid, 1422 IApplicationThread thread) { 1423 if (DEBUG_ALL) Slog.v( 1424 TAG, "New death recipient " + this 1425 + " for thread " + thread.asBinder()); 1426 mApp = app; 1427 mPid = pid; 1428 mAppThread = thread; 1429 } 1430 1431 @Override binderDied()1432 public void binderDied() { 1433 if (DEBUG_ALL) Slog.v( 1434 TAG, "Death received in " + this 1435 + " for thread " + mAppThread.asBinder()); 1436 synchronized(ActivityManagerService.this) { 1437 appDiedLocked(mApp, mPid, mAppThread, true, null); 1438 } 1439 } 1440 } 1441 1442 static final int SHOW_ERROR_UI_MSG = 1; 1443 static final int SHOW_NOT_RESPONDING_UI_MSG = 2; 1444 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1445 static final int WAIT_FOR_DEBUGGER_UI_MSG = 6; 1446 static final int SERVICE_TIMEOUT_MSG = 12; 1447 static final int UPDATE_TIME_ZONE = 13; 1448 static final int PROC_START_TIMEOUT_MSG = 20; 1449 static final int KILL_APPLICATION_MSG = 22; 1450 static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26; 1451 static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27; 1452 static final int CLEAR_DNS_CACHE_MSG = 28; 1453 static final int UPDATE_HTTP_PROXY_MSG = 29; 1454 static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31; 1455 static final int DISPATCH_PROCESS_DIED_UI_MSG = 32; 1456 static final int REPORT_MEM_USAGE_MSG = 33; 1457 static final int UPDATE_TIME_PREFERENCE_MSG = 41; 1458 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49; 1459 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50; 1460 static final int ABORT_DUMPHEAP_MSG = 51; 1461 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56; 1462 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57; 1463 static final int IDLE_UIDS_MSG = 58; 1464 static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63; 1465 static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66; 1466 static final int PUSH_TEMP_ALLOWLIST_UI_MSG = 68; 1467 static final int SERVICE_FOREGROUND_CRASH_MSG = 69; 1468 static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70; 1469 static final int KILL_APP_ZYGOTE_MSG = 71; 1470 static final int BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG = 72; 1471 static final int WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG = 73; 1472 1473 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1474 1475 static final String SERVICE_RECORD_KEY = "servicerecord"; 1476 1477 /** 1478 * Flag whether the current user is a "monkey", i.e. whether 1479 * the UI is driven by a UI automation tool. 1480 */ 1481 private volatile boolean mUserIsMonkey; 1482 1483 @VisibleForTesting 1484 public final ServiceThread mHandlerThread; 1485 final MainHandler mHandler; 1486 final Handler mUiHandler; 1487 final ServiceThread mProcStartHandlerThread; 1488 final Handler mProcStartHandler; 1489 1490 ActivityManagerConstants mConstants; 1491 1492 // Encapsulates the global setting "hidden_api_blacklist_exemptions" 1493 final HiddenApiSettings mHiddenApiBlacklist; 1494 1495 private final PlatformCompat mPlatformCompat; 1496 1497 PackageManagerInternal mPackageManagerInt; 1498 PermissionManagerServiceInternal mPermissionManagerInt; 1499 private TestUtilityService mTestUtilityService; 1500 1501 /** 1502 * Whether to force background check on all apps (for battery saver) or not. 1503 */ 1504 @CompositeRWLock({"this", "mProcLock"}) 1505 private boolean mForceBackgroundCheck; 1506 1507 private static String sTheRealBuildSerial = Build.UNKNOWN; 1508 1509 @GuardedBy("mProcLock") 1510 private ParcelFileDescriptor[] mLifeMonitorFds; 1511 1512 static final HostingRecord sNullHostingRecord = new HostingRecord(null); 1513 /** 1514 * Used to notify activity lifecycle events. 1515 */ 1516 @Nullable volatile ContentCaptureManagerInternal mContentCaptureService; 1517 1518 /* 1519 * The default duration for the binder heavy hitter auto sampler 1520 */ 1521 private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS = 300000L; 1522 1523 /** 1524 * The default throttling duration for the binder heavy hitter auto sampler 1525 */ 1526 private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS = 3600000L; 1527 1528 /** 1529 * The last time when the binder heavy hitter auto sampler started. 1530 */ 1531 @GuardedBy("mProcLock") 1532 private long mLastBinderHeavyHitterAutoSamplerStart = 0L; 1533 1534 final AppProfiler mAppProfiler; 1535 1536 private static final int INDEX_NATIVE_PSS = 0; 1537 private static final int INDEX_NATIVE_SWAP_PSS = 1; 1538 private static final int INDEX_NATIVE_RSS = 2; 1539 private static final int INDEX_DALVIK_PSS = 3; 1540 private static final int INDEX_DALVIK_SWAP_PSS = 4; 1541 private static final int INDEX_DALVIK_RSS = 5; 1542 private static final int INDEX_OTHER_PSS = 6; 1543 private static final int INDEX_OTHER_SWAP_PSS = 7; 1544 private static final int INDEX_OTHER_RSS = 8; 1545 private static final int INDEX_TOTAL_PSS = 9; 1546 private static final int INDEX_TOTAL_SWAP_PSS = 10; 1547 private static final int INDEX_TOTAL_RSS = 11; 1548 private static final int INDEX_TOTAL_NATIVE_PSS = 12; 1549 private static final int INDEX_TOTAL_MEMTRACK_GRAPHICS = 13; 1550 private static final int INDEX_TOTAL_MEMTRACK_GL = 14; 1551 private static final int INDEX_LAST = 15; 1552 1553 final class UiHandler extends Handler { UiHandler()1554 public UiHandler() { 1555 super(com.android.server.UiThread.get().getLooper(), null, true); 1556 } 1557 1558 @Override handleMessage(Message msg)1559 public void handleMessage(Message msg) { 1560 switch (msg.what) { 1561 case SHOW_ERROR_UI_MSG: { 1562 mAppErrors.handleShowAppErrorUi(msg); 1563 ensureBootCompleted(); 1564 } break; 1565 case SHOW_NOT_RESPONDING_UI_MSG: { 1566 mAppErrors.handleShowAnrUi(msg); 1567 ensureBootCompleted(); 1568 } break; 1569 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: { 1570 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1571 synchronized (mProcLock) { 1572 ProcessRecord proc = (ProcessRecord) data.get("app"); 1573 if (proc == null) { 1574 Slog.e(TAG, "App not found when showing strict mode dialog."); 1575 break; 1576 } 1577 if (proc.mErrorState.getDialogController().hasViolationDialogs()) { 1578 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1579 return; 1580 } 1581 AppErrorResult res = (AppErrorResult) data.get("result"); 1582 if (mAtmInternal.showStrictModeViolationDialog()) { 1583 proc.mErrorState.getDialogController().showViolationDialogs(res); 1584 } else { 1585 // The device is asleep, so just pretend that the user 1586 // saw a crash dialog and hit "force quit". 1587 res.set(0); 1588 } 1589 } 1590 ensureBootCompleted(); 1591 } break; 1592 case WAIT_FOR_DEBUGGER_UI_MSG: { 1593 synchronized (mProcLock) { 1594 ProcessRecord app = (ProcessRecord) msg.obj; 1595 if (msg.arg1 != 0) { 1596 if (!app.hasWaitedForDebugger()) { 1597 app.mErrorState.getDialogController().showDebugWaitingDialogs(); 1598 app.setWaitedForDebugger(true); 1599 } 1600 } else { 1601 app.mErrorState.getDialogController().clearWaitingDialog(); 1602 } 1603 } 1604 } break; 1605 case DISPATCH_PROCESSES_CHANGED_UI_MSG: { 1606 mProcessList.dispatchProcessesChanged(); 1607 break; 1608 } 1609 case DISPATCH_PROCESS_DIED_UI_MSG: { 1610 if (false) { // DO NOT SUBMIT WITH TRUE 1611 maybeTriggerWatchdog(); 1612 } 1613 final int pid = msg.arg1; 1614 final int uid = msg.arg2; 1615 mProcessList.dispatchProcessDied(pid, uid); 1616 break; 1617 } 1618 case DISPATCH_OOM_ADJ_OBSERVER_MSG: { 1619 dispatchOomAdjObserver((String) msg.obj); 1620 } break; 1621 case PUSH_TEMP_ALLOWLIST_UI_MSG: { 1622 pushTempAllowlist(); 1623 } break; 1624 } 1625 } 1626 } 1627 1628 final class MainHandler extends Handler { MainHandler(Looper looper)1629 public MainHandler(Looper looper) { 1630 super(looper, null, true); 1631 } 1632 1633 @Override handleMessage(Message msg)1634 public void handleMessage(Message msg) { 1635 switch (msg.what) { 1636 case GC_BACKGROUND_PROCESSES_MSG: { 1637 synchronized (ActivityManagerService.this) { 1638 mAppProfiler.performAppGcsIfAppropriateLocked(); 1639 } 1640 } break; 1641 case SERVICE_TIMEOUT_MSG: { 1642 mServices.serviceTimeout((ProcessRecord) msg.obj); 1643 } break; 1644 case SERVICE_FOREGROUND_TIMEOUT_MSG: { 1645 mServices.serviceForegroundTimeout((ServiceRecord) msg.obj); 1646 } break; 1647 case SERVICE_FOREGROUND_CRASH_MSG: { 1648 mServices.serviceForegroundCrash((ProcessRecord) msg.obj, 1649 msg.getData().getCharSequence(SERVICE_RECORD_KEY)); 1650 } break; 1651 case UPDATE_TIME_ZONE: { 1652 synchronized (mProcLock) { 1653 mProcessList.forEachLruProcessesLOSP(false, app -> { 1654 final IApplicationThread thread = app.getThread(); 1655 if (thread != null) { 1656 try { 1657 thread.updateTimeZone(); 1658 } catch (RemoteException ex) { 1659 Slog.w(TAG, "Failed to update time zone for: " 1660 + app.info.processName); 1661 } 1662 } 1663 }); 1664 } 1665 } break; 1666 case CLEAR_DNS_CACHE_MSG: { 1667 synchronized (mProcLock) { 1668 mProcessList.clearAllDnsCacheLOSP(); 1669 } 1670 } break; 1671 case UPDATE_HTTP_PROXY_MSG: { 1672 mProcessList.setAllHttpProxy(); 1673 } break; 1674 case PROC_START_TIMEOUT_MSG: { 1675 ProcessRecord app = (ProcessRecord) msg.obj; 1676 synchronized (ActivityManagerService.this) { 1677 processStartTimedOutLocked(app); 1678 } 1679 } break; 1680 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: { 1681 ProcessRecord app = (ProcessRecord) msg.obj; 1682 synchronized (ActivityManagerService.this) { 1683 mCpHelper.processContentProviderPublishTimedOutLocked(app); 1684 } 1685 } break; 1686 case KILL_APPLICATION_MSG: { 1687 synchronized (ActivityManagerService.this) { 1688 final int appId = msg.arg1; 1689 final int userId = msg.arg2; 1690 Bundle bundle = (Bundle) msg.obj; 1691 String pkg = bundle.getString("pkg"); 1692 String reason = bundle.getString("reason"); 1693 forceStopPackageLocked(pkg, appId, false, false, true, false, 1694 false, userId, reason); 1695 } 1696 } break; 1697 1698 case KILL_APP_ZYGOTE_MSG: { 1699 synchronized (ActivityManagerService.this) { 1700 final AppZygote appZygote = (AppZygote) msg.obj; 1701 mProcessList.killAppZygoteIfNeededLocked(appZygote, false /* force */); 1702 } 1703 } break; 1704 case CHECK_EXCESSIVE_POWER_USE_MSG: { 1705 checkExcessivePowerUsage(); 1706 removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG); 1707 Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 1708 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 1709 } break; 1710 case REPORT_MEM_USAGE_MSG: { 1711 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>) msg.obj; 1712 Thread thread = new Thread() { 1713 @Override public void run() { 1714 mAppProfiler.reportMemUsage(memInfos); 1715 } 1716 }; 1717 thread.start(); 1718 break; 1719 } 1720 case UPDATE_TIME_PREFERENCE_MSG: { 1721 // The user's time format preference might have changed. 1722 // For convenience we re-use the Intent extra values. 1723 synchronized (mProcLock) { 1724 mProcessList.updateAllTimePrefsLOSP(msg.arg1); 1725 } 1726 break; 1727 } 1728 case NOTIFY_CLEARTEXT_NETWORK_MSG: { 1729 final int uid = msg.arg1; 1730 final byte[] firstPacket = (byte[]) msg.obj; 1731 1732 synchronized (mProcLock) { 1733 synchronized (mPidsSelfLocked) { 1734 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 1735 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 1736 final IApplicationThread thread = p.getThread(); 1737 if (p.uid == uid && thread != null) { 1738 try { 1739 thread.notifyCleartextNetwork(firstPacket); 1740 } catch (RemoteException ignored) { 1741 } 1742 } 1743 } 1744 } 1745 } 1746 } break; 1747 case POST_DUMP_HEAP_NOTIFICATION_MSG: { 1748 mAppProfiler.handlePostDumpHeapNotification(); 1749 } break; 1750 case ABORT_DUMPHEAP_MSG: { 1751 mAppProfiler.handleAbortDumpHeap((String) msg.obj); 1752 } break; 1753 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: { 1754 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj; 1755 try { 1756 connection.shutdown(); 1757 } catch (RemoteException e) { 1758 Slog.w(TAG, "Error shutting down UiAutomationConnection"); 1759 } 1760 // Only a UiAutomation can set this flag and now that 1761 // it is finished we make sure it is reset to its default. 1762 mUserIsMonkey = false; 1763 } break; 1764 case IDLE_UIDS_MSG: { 1765 idleUids(); 1766 } break; 1767 case HANDLE_TRUST_STORAGE_UPDATE_MSG: { 1768 synchronized (mProcLock) { 1769 mProcessList.handleAllTrustStorageUpdateLOSP(); 1770 } 1771 } break; 1772 case BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG: { 1773 handleBinderHeavyHitterAutoSamplerTimeOut(); 1774 } break; 1775 case WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG: { 1776 synchronized (ActivityManagerService.this) { 1777 ((ContentProviderRecord) msg.obj).onProviderPublishStatusLocked(false); 1778 } 1779 } break; 1780 } 1781 } 1782 } 1783 1784 setSystemProcess()1785 public void setSystemProcess() { 1786 try { 1787 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, 1788 DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); 1789 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 1790 ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false, 1791 DUMP_FLAG_PRIORITY_HIGH); 1792 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 1793 ServiceManager.addService("dbinfo", new DbBinder(this)); 1794 mAppProfiler.setCpuInfoService(); 1795 ServiceManager.addService("permission", new PermissionController(this)); 1796 ServiceManager.addService("processinfo", new ProcessInfoService(this)); 1797 ServiceManager.addService("cacheinfo", new CacheBinder(this)); 1798 1799 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 1800 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); 1801 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 1802 1803 synchronized (this) { 1804 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName, 1805 false, 1806 0, 1807 new HostingRecord("system")); 1808 app.setPersistent(true); 1809 app.setPid(MY_PID); 1810 app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ); 1811 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 1812 addPidLocked(app); 1813 updateLruProcessLocked(app, false, null); 1814 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 1815 } 1816 } catch (PackageManager.NameNotFoundException e) { 1817 throw new RuntimeException( 1818 "Unable to find android system package", e); 1819 } 1820 1821 // Start watching app ops after we and the package manager are up and running. 1822 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null, 1823 new IAppOpsCallback.Stub() { 1824 @Override public void opChanged(int op, int uid, String packageName) { 1825 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) { 1826 if (getAppOpsManager().checkOpNoThrow(op, uid, packageName) 1827 != AppOpsManager.MODE_ALLOWED) { 1828 runInBackgroundDisabled(uid); 1829 } 1830 } 1831 } 1832 }); 1833 1834 final int[] cameraOp = {AppOpsManager.OP_CAMERA}; 1835 mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() { 1836 @Override 1837 public void opActiveChanged(int op, int uid, String packageName, String attributionTag, 1838 boolean active, @AttributionFlags int attributionFlags, 1839 int attributionChainId) { 1840 cameraActiveChanged(uid, active); 1841 } 1842 }); 1843 } 1844 setWindowManager(WindowManagerService wm)1845 public void setWindowManager(WindowManagerService wm) { 1846 synchronized (this) { 1847 mWindowManager = wm; 1848 mWmInternal = LocalServices.getService(WindowManagerInternal.class); 1849 mActivityTaskManager.setWindowManager(wm); 1850 } 1851 } 1852 1853 /** 1854 * @param usageStatsManager shouldn't be null 1855 */ setUsageStatsManager(@onNull UsageStatsManagerInternal usageStatsManager)1856 public void setUsageStatsManager(@NonNull UsageStatsManagerInternal usageStatsManager) { 1857 mUsageStatsService = usageStatsManager; 1858 mActivityTaskManager.setUsageStatsManager(usageStatsManager); 1859 } 1860 1861 /** 1862 * Sets the internal content capture manager service. 1863 * 1864 * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock. 1865 */ setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)1866 public void setContentCaptureManager( 1867 @Nullable ContentCaptureManagerInternal contentCaptureManager) { 1868 mContentCaptureService = contentCaptureManager; 1869 } 1870 startObservingNativeCrashes()1871 public void startObservingNativeCrashes() { 1872 final NativeCrashListener ncl = new NativeCrashListener(this); 1873 ncl.start(); 1874 } 1875 1876 /** 1877 * Sets a policy for handling app ops. 1878 * 1879 * @param appOpsPolicy The policy. 1880 */ setAppOpsPolicy(@ullable CheckOpsDelegate appOpsPolicy)1881 public void setAppOpsPolicy(@Nullable CheckOpsDelegate appOpsPolicy) { 1882 mAppOpsService.setAppOpsPolicy(appOpsPolicy); 1883 } 1884 getAppOpsService()1885 public IAppOpsService getAppOpsService() { 1886 return mAppOpsService; 1887 } 1888 1889 static class MemBinder extends Binder { 1890 ActivityManagerService mActivityManagerService; 1891 private final PriorityDump.PriorityDumper mPriorityDumper = 1892 new PriorityDump.PriorityDumper() { 1893 @Override 1894 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, 1895 boolean asProto) { 1896 dump(fd, pw, new String[] {"-a"}, asProto); 1897 } 1898 1899 @Override 1900 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) { 1901 mActivityManagerService.dumpApplicationMemoryUsage( 1902 fd, pw, " ", args, false, null, asProto); 1903 } 1904 }; 1905 MemBinder(ActivityManagerService activityManagerService)1906 MemBinder(ActivityManagerService activityManagerService) { 1907 mActivityManagerService = activityManagerService; 1908 } 1909 1910 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)1911 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1912 try { 1913 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 1914 1915 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 1916 "meminfo", pw)) return; 1917 PriorityDump.dump(mPriorityDumper, fd, pw, args); 1918 } finally { 1919 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 1920 } 1921 } 1922 } 1923 1924 static class GraphicsBinder extends Binder { 1925 ActivityManagerService mActivityManagerService; GraphicsBinder(ActivityManagerService activityManagerService)1926 GraphicsBinder(ActivityManagerService activityManagerService) { 1927 mActivityManagerService = activityManagerService; 1928 } 1929 1930 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)1931 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1932 try { 1933 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 1934 1935 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 1936 "gfxinfo", pw)) return; 1937 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 1938 } finally { 1939 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 1940 } 1941 } 1942 } 1943 1944 static class DbBinder extends Binder { 1945 ActivityManagerService mActivityManagerService; DbBinder(ActivityManagerService activityManagerService)1946 DbBinder(ActivityManagerService activityManagerService) { 1947 mActivityManagerService = activityManagerService; 1948 } 1949 1950 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)1951 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1952 try { 1953 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 1954 1955 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 1956 "dbinfo", pw)) return; 1957 mActivityManagerService.dumpDbInfo(fd, pw, args); 1958 } finally { 1959 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 1960 } 1961 } 1962 } 1963 1964 static class CacheBinder extends Binder { 1965 ActivityManagerService mActivityManagerService; 1966 CacheBinder(ActivityManagerService activityManagerService)1967 CacheBinder(ActivityManagerService activityManagerService) { 1968 mActivityManagerService = activityManagerService; 1969 } 1970 1971 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)1972 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1973 try { 1974 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 1975 1976 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 1977 "cacheinfo", pw)) { 1978 return; 1979 } 1980 1981 mActivityManagerService.dumpBinderCacheContents(fd, pw, args); 1982 } finally { 1983 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 1984 } 1985 } 1986 } 1987 1988 public static final class Lifecycle extends SystemService { 1989 private final ActivityManagerService mService; 1990 private static ActivityTaskManagerService sAtm; 1991 Lifecycle(Context context)1992 public Lifecycle(Context context) { 1993 super(context); 1994 mService = new ActivityManagerService(context, sAtm); 1995 } 1996 startService( SystemServiceManager ssm, ActivityTaskManagerService atm)1997 public static ActivityManagerService startService( 1998 SystemServiceManager ssm, ActivityTaskManagerService atm) { 1999 sAtm = atm; 2000 return ssm.startService(ActivityManagerService.Lifecycle.class).getService(); 2001 } 2002 2003 @Override onStart()2004 public void onStart() { 2005 mService.start(); 2006 } 2007 2008 @Override onBootPhase(int phase)2009 public void onBootPhase(int phase) { 2010 mService.mBootPhase = phase; 2011 if (phase == PHASE_SYSTEM_SERVICES_READY) { 2012 mService.mBatteryStatsService.systemServicesReady(); 2013 mService.mServices.systemServicesReady(); 2014 } else if (phase == PHASE_ACTIVITY_MANAGER_READY) { 2015 mService.startBroadcastObservers(); 2016 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { 2017 mService.mPackageWatchdog.onPackagesReady(); 2018 } 2019 } 2020 2021 @Override onUserStopped(@onNull TargetUser user)2022 public void onUserStopped(@NonNull TargetUser user) { 2023 mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier()); 2024 } 2025 getService()2026 public ActivityManagerService getService() { 2027 return mService; 2028 } 2029 } 2030 maybeLogUserspaceRebootEvent()2031 private void maybeLogUserspaceRebootEvent() { 2032 if (!UserspaceRebootLogger.shouldLogUserspaceRebootEvent()) { 2033 return; 2034 } 2035 final int userId = mUserController.getCurrentUserId(); 2036 if (userId != UserHandle.USER_SYSTEM) { 2037 // Only log for user0. 2038 return; 2039 } 2040 // TODO(b/148767783): should we check all profiles under user0? 2041 UserspaceRebootLogger.logEventAsync(StorageManager.isUserKeyUnlocked(userId), 2042 BackgroundThread.getExecutor()); 2043 } 2044 2045 /** 2046 * Encapsulates global settings related to hidden API enforcement behaviour, including tracking 2047 * the latest value via a content observer. 2048 */ 2049 static class HiddenApiSettings extends ContentObserver 2050 implements DeviceConfig.OnPropertiesChangedListener { 2051 2052 private final Context mContext; 2053 private boolean mBlacklistDisabled; 2054 private String mExemptionsStr; 2055 private List<String> mExemptions = Collections.emptyList(); 2056 private int mLogSampleRate = -1; 2057 private int mStatslogSampleRate = -1; 2058 @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT; 2059 2060 /** 2061 * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in 2062 * the range 0 to 0x10000 inclusive. 2063 * 2064 * @hide 2065 */ 2066 public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE = 2067 "hidden_api_access_log_sampling_rate"; 2068 2069 /** 2070 * Sampling rate for hidden API access event logging with statslog, as an integer in the 2071 * range 0 to 0x10000 inclusive. 2072 * 2073 * @hide 2074 */ 2075 public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE = 2076 "hidden_api_access_statslog_sampling_rate"; 2077 onPropertiesChanged(DeviceConfig.Properties properties)2078 public void onPropertiesChanged(DeviceConfig.Properties properties) { 2079 int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0x0); 2080 if (logSampleRate < 0 || logSampleRate > 0x10000) { 2081 logSampleRate = -1; 2082 } 2083 if (logSampleRate != -1 && logSampleRate != mLogSampleRate) { 2084 mLogSampleRate = logSampleRate; 2085 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate); 2086 } 2087 2088 int statslogSampleRate = 2089 properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0); 2090 if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) { 2091 statslogSampleRate = -1; 2092 } 2093 if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) { 2094 mStatslogSampleRate = statslogSampleRate; 2095 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate); 2096 } 2097 } 2098 HiddenApiSettings(Handler handler, Context context)2099 public HiddenApiSettings(Handler handler, Context context) { 2100 super(handler); 2101 mContext = context; 2102 } 2103 registerObserver()2104 public void registerObserver() { 2105 mContext.getContentResolver().registerContentObserver( 2106 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS), 2107 false, 2108 this); 2109 mContext.getContentResolver().registerContentObserver( 2110 Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY), 2111 false, 2112 this); 2113 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT, 2114 mContext.getMainExecutor(), this); 2115 update(); 2116 } 2117 update()2118 private void update() { 2119 String exemptions = Settings.Global.getString(mContext.getContentResolver(), 2120 Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS); 2121 if (!TextUtils.equals(exemptions, mExemptionsStr)) { 2122 mExemptionsStr = exemptions; 2123 if ("*".equals(exemptions)) { 2124 mBlacklistDisabled = true; 2125 mExemptions = Collections.emptyList(); 2126 } else { 2127 mBlacklistDisabled = false; 2128 mExemptions = TextUtils.isEmpty(exemptions) 2129 ? Collections.emptyList() 2130 : Arrays.asList(exemptions.split(",")); 2131 } 2132 if (!ZYGOTE_PROCESS.setApiDenylistExemptions(mExemptions)) { 2133 Slog.e(TAG, "Failed to set API blacklist exemptions!"); 2134 // leave mExemptionsStr as is, so we don't try to send the same list again. 2135 mExemptions = Collections.emptyList(); 2136 } 2137 } 2138 mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY); 2139 } 2140 getValidEnforcementPolicy(String settingsKey)2141 private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) { 2142 int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey, 2143 ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT); 2144 if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) { 2145 return policy; 2146 } else { 2147 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT; 2148 } 2149 } 2150 isDisabled()2151 boolean isDisabled() { 2152 return mBlacklistDisabled; 2153 } 2154 getPolicy()2155 @HiddenApiEnforcementPolicy int getPolicy() { 2156 return mPolicy; 2157 } 2158 onChange(boolean selfChange)2159 public void onChange(boolean selfChange) { 2160 update(); 2161 } 2162 } 2163 getAppOpsManager()2164 AppOpsManager getAppOpsManager() { 2165 if (mAppOpsManager == null) { 2166 mAppOpsManager = mContext.getSystemService(AppOpsManager.class); 2167 } 2168 return mAppOpsManager; 2169 } 2170 2171 /** 2172 * Provides the basic functionality for activity task related tests when a handler thread is 2173 * given to initialize the dependency members. 2174 */ 2175 @VisibleForTesting ActivityManagerService(Injector injector, ServiceThread handlerThread)2176 public ActivityManagerService(Injector injector, ServiceThread handlerThread) { 2177 final boolean hasHandlerThread = handlerThread != null; 2178 mInjector = injector; 2179 mContext = mInjector.getContext(); 2180 mUiContext = null; 2181 mAppErrors = null; 2182 mPackageWatchdog = null; 2183 mAppOpsService = mInjector.getAppOpsService(null /* file */, null /* handler */); 2184 mBatteryStatsService = null; 2185 mHandler = hasHandlerThread ? new MainHandler(handlerThread.getLooper()) : null; 2186 mHandlerThread = handlerThread; 2187 mConstants = hasHandlerThread 2188 ? new ActivityManagerConstants(mContext, this, mHandler) : null; 2189 final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */); 2190 mPlatformCompat = null; 2191 mProcessList = injector.getProcessList(this); 2192 mProcessList.init(this, activeUids, mPlatformCompat); 2193 mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), null); 2194 mPhantomProcessList = new PhantomProcessList(this); 2195 mOomAdjuster = hasHandlerThread 2196 ? new OomAdjuster(this, mProcessList, activeUids, handlerThread) : null; 2197 2198 mIntentFirewall = hasHandlerThread 2199 ? new IntentFirewall(new IntentFirewallInterface(), mHandler) : null; 2200 mProcessStats = null; 2201 mCpHelper = new ContentProviderHelper(this, false); 2202 // For the usage of {@link ActiveServices#cleanUpServices} that may be invoked from 2203 // {@link ActivityTaskSupervisor#cleanUpRemovedTaskLocked}. 2204 mServices = hasHandlerThread ? new ActiveServices(this) : null; 2205 mSystemThread = null; 2206 mUiHandler = injector.getUiHandler(null /* service */); 2207 mUidObserverController = new UidObserverController(mUiHandler); 2208 mUserController = hasHandlerThread ? new UserController(this) : null; 2209 mPendingIntentController = hasHandlerThread 2210 ? new PendingIntentController(handlerThread.getLooper(), mUserController, 2211 mConstants) : null; 2212 mProcStartHandlerThread = null; 2213 mProcStartHandler = null; 2214 mHiddenApiBlacklist = null; 2215 mFactoryTest = FACTORY_TEST_OFF; 2216 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2217 mInternal = new LocalService(); 2218 mPendingStartActivityUids = new PendingStartActivityUids(mContext); 2219 mUseFifoUiScheduling = false; 2220 mEnableOffloadQueue = false; 2221 mFgBroadcastQueue = mBgBroadcastQueue = mOffloadBroadcastQueue = null; 2222 } 2223 2224 // Note: This method is invoked on the main thread but may need to attach various 2225 // handlers to other threads. So take care to be explicit about the looper. ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2226 public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) { 2227 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); 2228 mInjector = new Injector(systemContext); 2229 mContext = systemContext; 2230 2231 mFactoryTest = FactoryTest.getMode(); 2232 mSystemThread = ActivityThread.currentActivityThread(); 2233 mUiContext = mSystemThread.getSystemUiContext(); 2234 2235 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2236 2237 mHandlerThread = new ServiceThread(TAG, 2238 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2239 mHandlerThread.start(); 2240 mHandler = new MainHandler(mHandlerThread.getLooper()); 2241 mUiHandler = mInjector.getUiHandler(this); 2242 2243 mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", 2244 THREAD_PRIORITY_FOREGROUND, false /* allowIo */); 2245 mProcStartHandlerThread.start(); 2246 mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper()); 2247 2248 mConstants = new ActivityManagerConstants(mContext, this, mHandler); 2249 final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */); 2250 mPlatformCompat = (PlatformCompat) ServiceManager.getService( 2251 Context.PLATFORM_COMPAT_SERVICE); 2252 mProcessList = mInjector.getProcessList(this); 2253 mProcessList.init(this, activeUids, mPlatformCompat); 2254 mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), 2255 new LowMemDetector(this)); 2256 mPhantomProcessList = new PhantomProcessList(this); 2257 mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids); 2258 2259 // Broadcast policy parameters 2260 final BroadcastConstants foreConstants = new BroadcastConstants( 2261 Settings.Global.BROADCAST_FG_CONSTANTS); 2262 foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT; 2263 2264 final BroadcastConstants backConstants = new BroadcastConstants( 2265 Settings.Global.BROADCAST_BG_CONSTANTS); 2266 backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; 2267 2268 final BroadcastConstants offloadConstants = new BroadcastConstants( 2269 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS); 2270 offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; 2271 // by default, no "slow" policy in this queue 2272 offloadConstants.SLOW_TIME = Integer.MAX_VALUE; 2273 2274 mEnableOffloadQueue = SystemProperties.getBoolean( 2275 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false); 2276 2277 mFgBroadcastQueue = new BroadcastQueue(this, mHandler, 2278 "foreground", foreConstants, false); 2279 mBgBroadcastQueue = new BroadcastQueue(this, mHandler, 2280 "background", backConstants, true); 2281 mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, 2282 "offload", offloadConstants, true); 2283 mBroadcastQueues[0] = mFgBroadcastQueue; 2284 mBroadcastQueues[1] = mBgBroadcastQueue; 2285 mBroadcastQueues[2] = mOffloadBroadcastQueue; 2286 2287 mServices = new ActiveServices(this); 2288 mCpHelper = new ContentProviderHelper(this, true); 2289 mPackageWatchdog = PackageWatchdog.getInstance(mUiContext); 2290 mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog); 2291 mUidObserverController = new UidObserverController(mUiHandler); 2292 2293 final File systemDir = SystemServiceManager.ensureSystemDir(); 2294 2295 // TODO: Move creation of battery stats service outside of activity manager service. 2296 mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, 2297 BackgroundThread.get().getHandler()); 2298 mBatteryStatsService.getActiveStatistics().readLocked(); 2299 mBatteryStatsService.scheduleWriteToDisk(); 2300 mOnBattery = DEBUG_POWER ? true 2301 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2302 mBatteryStatsService.getActiveStatistics().setCallback(this); 2303 mOomAdjProfiler.batteryPowerChanged(mOnBattery); 2304 2305 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2306 2307 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler); 2308 2309 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class); 2310 2311 mUserController = new UserController(this); 2312 2313 mPendingIntentController = new PendingIntentController( 2314 mHandlerThread.getLooper(), mUserController, mConstants); 2315 2316 mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0; 2317 2318 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations")); 2319 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2320 2321 mActivityTaskManager = atm; 2322 mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, 2323 DisplayThread.get().getLooper()); 2324 mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class); 2325 2326 mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext); 2327 2328 Watchdog.getInstance().addMonitor(this); 2329 Watchdog.getInstance().addThread(mHandler); 2330 2331 // bind background threads to little cores 2332 // this is expected to fail inside of framework tests because apps can't touch cpusets directly 2333 // make sure we've already adjusted system_server's internal view of itself first 2334 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 2335 try { 2336 Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(), 2337 Process.THREAD_GROUP_SYSTEM); 2338 Process.setThreadGroupAndCpuset( 2339 mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(), 2340 Process.THREAD_GROUP_SYSTEM); 2341 } catch (Exception e) { 2342 Slog.w(TAG, "Setting background thread cpuset failed"); 2343 } 2344 2345 mInternal = new LocalService(); 2346 mPendingStartActivityUids = new PendingStartActivityUids(mContext); 2347 mTraceErrorLogger = new TraceErrorLogger(); 2348 } 2349 setSystemServiceManager(SystemServiceManager mgr)2350 public void setSystemServiceManager(SystemServiceManager mgr) { 2351 mSystemServiceManager = mgr; 2352 } 2353 setInstaller(Installer installer)2354 public void setInstaller(Installer installer) { 2355 mInstaller = installer; 2356 } 2357 start()2358 private void start() { 2359 removeAllProcessGroups(); 2360 2361 mBatteryStatsService.publish(); 2362 mAppOpsService.publish(); 2363 Slog.d("AppOps", "AppOpsService published"); 2364 LocalServices.addService(ActivityManagerInternal.class, mInternal); 2365 LocalManagerRegistry.addManager(ActivityManagerLocal.class, 2366 (ActivityManagerLocal) mInternal); 2367 mActivityTaskManager.onActivityManagerInternalAdded(); 2368 mPendingIntentController.onActivityManagerInternalAdded(); 2369 mAppProfiler.onActivityManagerInternalAdded(); 2370 } 2371 initPowerManagement()2372 public void initPowerManagement() { 2373 mActivityTaskManager.onInitPowerManagement(); 2374 mBatteryStatsService.initPowerManagement(); 2375 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); 2376 } 2377 getBackgroundLaunchBroadcasts()2378 private ArraySet<String> getBackgroundLaunchBroadcasts() { 2379 if (mBackgroundLaunchBroadcasts == null) { 2380 mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts(); 2381 } 2382 return mBackgroundLaunchBroadcasts; 2383 } 2384 2385 /** 2386 * Ensures that the given package name has an explicit set of allowed associations. 2387 * If it does not, give it an empty set. 2388 */ requireAllowedAssociationsLocked(String packageName)2389 void requireAllowedAssociationsLocked(String packageName) { 2390 ensureAllowedAssociations(); 2391 if (mAllowedAssociations.get(packageName) == null) { 2392 mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName, 2393 new ArraySet<>(), /* isDebuggable = */ false)); 2394 } 2395 } 2396 2397 /** 2398 * Returns true if the package {@code pkg1} running under user handle {@code uid1} is 2399 * allowed association with the package {@code pkg2} running under user handle {@code uid2}. 2400 * <p> If either of the packages are running as part of the core system, then the 2401 * association is implicitly allowed. 2402 */ validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2403 boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) { 2404 ensureAllowedAssociations(); 2405 // Interactions with the system uid are always allowed, since that is the core system 2406 // that everyone needs to be able to interact with. Also allow reflexive associations 2407 // within the same uid. 2408 if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID 2409 || UserHandle.getAppId(uid2) == SYSTEM_UID) { 2410 return true; 2411 } 2412 2413 // Check for association on both source and target packages. 2414 PackageAssociationInfo pai = mAllowedAssociations.get(pkg1); 2415 if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) { 2416 return false; 2417 } 2418 pai = mAllowedAssociations.get(pkg2); 2419 if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) { 2420 return false; 2421 } 2422 // If no explicit associations are provided in the manifest, then assume the app is 2423 // allowed associations with any package. 2424 return true; 2425 } 2426 2427 /** Sets up allowed associations for system prebuilt packages from system config (if needed). */ ensureAllowedAssociations()2428 private void ensureAllowedAssociations() { 2429 if (mAllowedAssociations == null) { 2430 ArrayMap<String, ArraySet<String>> allowedAssociations = 2431 SystemConfig.getInstance().getAllowedAssociations(); 2432 mAllowedAssociations = new ArrayMap<>(allowedAssociations.size()); 2433 PackageManagerInternal pm = getPackageManagerInternal(); 2434 for (int i = 0; i < allowedAssociations.size(); i++) { 2435 final String pkg = allowedAssociations.keyAt(i); 2436 final ArraySet<String> asc = allowedAssociations.valueAt(i); 2437 2438 // Query latest debuggable flag from package-manager. 2439 boolean isDebuggable = false; 2440 try { 2441 ApplicationInfo ai = AppGlobals.getPackageManager() 2442 .getApplicationInfo(pkg, MATCH_ALL, 0); 2443 if (ai != null) { 2444 isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 2445 } 2446 } catch (RemoteException e) { 2447 /* ignore */ 2448 } 2449 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable)); 2450 } 2451 } 2452 } 2453 2454 /** Updates allowed associations for app info (specifically, based on debuggability). */ updateAssociationForApp(ApplicationInfo appInfo)2455 private void updateAssociationForApp(ApplicationInfo appInfo) { 2456 ensureAllowedAssociations(); 2457 PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName); 2458 if (pai != null) { 2459 pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); 2460 } 2461 } 2462 2463 @Override onTransact(int code, Parcel data, Parcel reply, int flags)2464 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2465 throws RemoteException { 2466 if (code == SYSPROPS_TRANSACTION) { 2467 // We need to tell all apps about the system property change. 2468 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2469 synchronized (mProcLock) { 2470 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 2471 mProcessList.getProcessNamesLOSP().getMap(); 2472 final int numOfNames = pmap.size(); 2473 for (int ip = 0; ip < numOfNames; ip++) { 2474 SparseArray<ProcessRecord> apps = pmap.valueAt(ip); 2475 final int numOfApps = apps.size(); 2476 for (int ia = 0; ia < numOfApps; ia++) { 2477 ProcessRecord app = apps.valueAt(ia); 2478 final IApplicationThread thread = app.getThread(); 2479 if (thread != null) { 2480 procs.add(thread.asBinder()); 2481 } 2482 } 2483 } 2484 } 2485 2486 int N = procs.size(); 2487 for (int i=0; i<N; i++) { 2488 Parcel data2 = Parcel.obtain(); 2489 try { 2490 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 2491 Binder.FLAG_ONEWAY); 2492 } catch (RemoteException e) { 2493 } 2494 data2.recycle(); 2495 } 2496 } 2497 try { 2498 return super.onTransact(code, data, reply, flags); 2499 } catch (RuntimeException e) { 2500 // The activity manager only throws certain exceptions intentionally, so let's 2501 // log all others. 2502 if (!(e instanceof SecurityException 2503 || e instanceof IllegalArgumentException 2504 || e instanceof IllegalStateException)) { 2505 Slog.wtf(TAG, "Activity Manager Crash." 2506 + " UID:" + Binder.getCallingUid() 2507 + " PID:" + Binder.getCallingPid() 2508 + " TRANS:" + code, e); 2509 } 2510 throw e; 2511 } 2512 } 2513 updateCpuStats()2514 void updateCpuStats() { 2515 mAppProfiler.updateCpuStats(); 2516 } 2517 updateCpuStatsNow()2518 void updateCpuStatsNow() { 2519 mAppProfiler.updateCpuStatsNow(); 2520 } 2521 2522 @Override batteryNeedsCpuUpdate()2523 public void batteryNeedsCpuUpdate() { 2524 updateCpuStatsNow(); 2525 } 2526 2527 @Override batteryPowerChanged(boolean onBattery)2528 public void batteryPowerChanged(boolean onBattery) { 2529 // When plugging in, update the CPU stats first before changing 2530 // the plug state. 2531 updateCpuStatsNow(); 2532 synchronized (mProcLock) { 2533 mOnBattery = DEBUG_POWER ? true : onBattery; 2534 mOomAdjProfiler.batteryPowerChanged(onBattery); 2535 } 2536 } 2537 2538 @Override batteryStatsReset()2539 public void batteryStatsReset() { 2540 mOomAdjProfiler.reset(); 2541 } 2542 2543 @Override batterySendBroadcast(Intent intent)2544 public void batterySendBroadcast(Intent intent) { 2545 synchronized (this) { 2546 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, null, 2547 OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(), 2548 Binder.getCallingPid(), UserHandle.USER_ALL); 2549 } 2550 } 2551 2552 /** 2553 * Initialize the application bind args. These are passed to each 2554 * process when the bindApplication() IPC is sent to the process. They're 2555 * lazily setup to make sure the services are running when they're asked for. 2556 */ getCommonServicesLocked(boolean isolated)2557 private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) { 2558 // Isolated processes won't get this optimization, so that we don't 2559 // violate the rules about which services they have access to. 2560 if (isolated) { 2561 if (mIsolatedAppBindArgs == null) { 2562 mIsolatedAppBindArgs = new ArrayMap<>(1); 2563 addServiceToMap(mIsolatedAppBindArgs, "package"); 2564 addServiceToMap(mIsolatedAppBindArgs, "permissionmgr"); 2565 } 2566 return mIsolatedAppBindArgs; 2567 } 2568 2569 if (mAppBindArgs == null) { 2570 mAppBindArgs = new ArrayMap<>(); 2571 2572 // Add common services. 2573 // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too. 2574 // Enable the check in ApplicationThread.bindApplication() to make sure. 2575 addServiceToMap(mAppBindArgs, "package"); 2576 addServiceToMap(mAppBindArgs, "permissionmgr"); 2577 addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE); 2578 addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE); 2579 addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE); 2580 addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE); 2581 addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE); 2582 addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE); 2583 addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE); 2584 addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE); 2585 addServiceToMap(mAppBindArgs, "graphicsstats"); 2586 addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE); 2587 addServiceToMap(mAppBindArgs, "content"); 2588 addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE); 2589 addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE); 2590 addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE); 2591 addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE); 2592 addServiceToMap(mAppBindArgs, Context.POWER_SERVICE); 2593 addServiceToMap(mAppBindArgs, Context.USER_SERVICE); 2594 addServiceToMap(mAppBindArgs, "mount"); 2595 addServiceToMap(mAppBindArgs, Context.PLATFORM_COMPAT_SERVICE); 2596 } 2597 return mAppBindArgs; 2598 } 2599 addServiceToMap(ArrayMap<String, IBinder> map, String name)2600 private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) { 2601 final IBinder service = ServiceManager.getService(name); 2602 if (service != null) { 2603 map.put(name, service); 2604 if (false) { 2605 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache."); 2606 } 2607 } 2608 } 2609 2610 @Override setFocusedRootTask(int taskId)2611 public void setFocusedRootTask(int taskId) { 2612 mActivityTaskManager.setFocusedRootTask(taskId); 2613 } 2614 2615 /** Sets the task stack listener that gets callbacks when a task stack changes. */ 2616 @Override registerTaskStackListener(ITaskStackListener listener)2617 public void registerTaskStackListener(ITaskStackListener listener) { 2618 mActivityTaskManager.registerTaskStackListener(listener); 2619 } 2620 2621 /** 2622 * Unregister a task stack listener so that it stops receiving callbacks. 2623 */ 2624 @Override unregisterTaskStackListener(ITaskStackListener listener)2625 public void unregisterTaskStackListener(ITaskStackListener listener) { 2626 mActivityTaskManager.unregisterTaskStackListener(listener); 2627 } 2628 2629 @GuardedBy("this") updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2630 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2631 ProcessRecord client) { 2632 mProcessList.updateLruProcessLocked(app, activityChange, client); 2633 } 2634 2635 @GuardedBy("this") removeLruProcessLocked(ProcessRecord app)2636 final void removeLruProcessLocked(ProcessRecord app) { 2637 mProcessList.removeLruProcessLocked(app); 2638 } 2639 2640 @GuardedBy("this") getProcessRecordLocked(String processName, int uid)2641 final ProcessRecord getProcessRecordLocked(String processName, int uid) { 2642 return mProcessList.getProcessRecordLocked(processName, uid); 2643 } 2644 2645 @GuardedBy(anyOf = {"this", "mProcLock"}) getProcessNamesLOSP()2646 final ProcessMap<ProcessRecord> getProcessNamesLOSP() { 2647 return mProcessList.getProcessNamesLOSP(); 2648 } 2649 notifyPackageUse(String packageName, int reason)2650 void notifyPackageUse(String packageName, int reason) { 2651 getPackageManagerInternal().notifyPackageUse(packageName, reason); 2652 } 2653 startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2654 boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 2655 String processName, String abiOverride, int uid, Runnable crashHandler) { 2656 synchronized(this) { 2657 ApplicationInfo info = new ApplicationInfo(); 2658 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 2659 // For isolated processes, the former contains the parent's uid and the latter the 2660 // actual uid of the isolated process. 2661 // In the special case introduced by this method (which is, starting an isolated 2662 // process directly from the SystemServer without an actual parent app process) the 2663 // closest thing to a parent's uid is SYSTEM_UID. 2664 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 2665 // the |isolated| logic in the ProcessRecord constructor. 2666 info.uid = SYSTEM_UID; 2667 info.processName = processName; 2668 info.className = entryPoint; 2669 info.packageName = "android"; 2670 info.seInfoUser = SELinuxUtil.COMPLETE_STR; 2671 info.targetSdkVersion = Build.VERSION.SDK_INT; 2672 ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */, 2673 false /* knownToBeDead */, 0 /* intentFlags */, 2674 sNullHostingRecord /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY, 2675 true /* allowWhileBooting */, true /* isolated */, 2676 uid, abiOverride, entryPoint, entryPointArgs, crashHandler); 2677 return proc != null; 2678 } 2679 } 2680 2681 @GuardedBy("this") startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated)2682 final ProcessRecord startProcessLocked(String processName, 2683 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2684 HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, 2685 boolean isolated) { 2686 return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, 2687 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */, 2688 null /* ABI override */, null /* entryPoint */, 2689 null /* entryPointArgs */, null /* crashHandler */); 2690 } 2691 isAllowedWhileBooting(ApplicationInfo ai)2692 boolean isAllowedWhileBooting(ApplicationInfo ai) { 2693 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 2694 } 2695 2696 /** 2697 * Update battery stats on the activity' usage. 2698 * @param activity 2699 * @param uid 2700 * @param userId 2701 * @param resumed 2702 */ updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)2703 void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) { 2704 if (DEBUG_SWITCH) { 2705 Slog.d(TAG_SWITCH, 2706 "updateBatteryStats: comp=" + activity + "res=" + resumed); 2707 } 2708 mBatteryStatsService.updateBatteryStatsOnActivityUsage(activity.getPackageName(), 2709 activity.getShortClassName(), uid, userId, resumed); 2710 } 2711 2712 /** 2713 * Update UsageStas on the activity's usage. 2714 * @param activity 2715 * @param userId 2716 * @param event 2717 * @param appToken ActivityRecord's appToken. 2718 * @param taskRoot Task's root 2719 */ updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)2720 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 2721 IBinder appToken, ComponentName taskRoot) { 2722 if (DEBUG_SWITCH) { 2723 Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp=" 2724 + activity + " hash=" + appToken.hashCode() + " event=" + event); 2725 } 2726 if (mUsageStatsService != null) { 2727 mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(), taskRoot); 2728 if (event == Event.ACTIVITY_RESUMED) { 2729 // Report component usage as an activity is an app component 2730 mUsageStatsService.reportEvent( 2731 activity.getPackageName(), userId, Event.APP_COMPONENT_USED); 2732 } 2733 } 2734 ContentCaptureManagerInternal contentCaptureService = mContentCaptureService; 2735 if (contentCaptureService != null && (event == Event.ACTIVITY_PAUSED 2736 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED 2737 || event == Event.ACTIVITY_DESTROYED)) { 2738 contentCaptureService.notifyActivityEvent(userId, activity, event); 2739 } 2740 } 2741 2742 /** 2743 * Update UsageStats on this package's usage. 2744 * @param packageName 2745 * @param userId 2746 * @param event 2747 */ updateActivityUsageStats(String packageName, int userId, int event)2748 public void updateActivityUsageStats(String packageName, int userId, int event) { 2749 if (DEBUG_SWITCH) { 2750 Slog.d(TAG_SWITCH, "updateActivityUsageStats: package=" 2751 + packageName + " event=" + event); 2752 } 2753 if (mUsageStatsService != null) { 2754 mUsageStatsService.reportEvent(packageName, userId, event); 2755 } 2756 } 2757 2758 /** 2759 * Update Usages on this foreground service's usage. 2760 * @param service 2761 * @param userId 2762 * @param started 2763 */ updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)2764 void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) { 2765 if (DEBUG_SWITCH) { 2766 Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp=" 2767 + service + " started=" + started); 2768 } 2769 if (mUsageStatsService != null) { 2770 mUsageStatsService.reportEvent(service, userId, 2771 started ? UsageEvents.Event.FOREGROUND_SERVICE_START 2772 : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null); 2773 } 2774 } 2775 compatibilityInfoForPackage(ApplicationInfo ai)2776 CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) { 2777 return mAtmInternal.compatibilityInfoForPackage(ai); 2778 } 2779 enforceNotIsolatedCaller(String caller)2780 /* package */ void enforceNotIsolatedCaller(String caller) { 2781 if (UserHandle.isIsolated(Binder.getCallingUid())) { 2782 throw new SecurityException("Isolated process not allowed to call " + caller); 2783 } 2784 } 2785 2786 @Override setPackageScreenCompatMode(String packageName, int mode)2787 public void setPackageScreenCompatMode(String packageName, int mode) { 2788 mActivityTaskManager.setPackageScreenCompatMode(packageName, mode); 2789 } 2790 hasUsageStatsPermission(String callingPackage)2791 private boolean hasUsageStatsPermission(String callingPackage) { 2792 final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS, 2793 Binder.getCallingUid(), callingPackage, null, false, "", false).getOpMode(); 2794 if (mode == AppOpsManager.MODE_DEFAULT) { 2795 return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS) 2796 == PackageManager.PERMISSION_GRANTED; 2797 } 2798 return mode == AppOpsManager.MODE_ALLOWED; 2799 } 2800 2801 @Override getPackageProcessState(String packageName, String callingPackage)2802 public int getPackageProcessState(String packageName, String callingPackage) { 2803 if (!hasUsageStatsPermission(callingPackage)) { 2804 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 2805 "getPackageProcessState"); 2806 } 2807 2808 final int[] procState = {PROCESS_STATE_NONEXISTENT}; 2809 synchronized (mProcLock) { 2810 mProcessList.forEachLruProcessesLOSP(false, proc -> { 2811 if (procState[0] > proc.mState.getSetProcState()) { 2812 if (proc.getPkgList().containsKey(packageName) || (proc.getPkgDeps() != null 2813 && proc.getPkgDeps().contains(packageName))) { 2814 procState[0] = proc.mState.getSetProcState(); 2815 } 2816 } 2817 }); 2818 } 2819 return procState[0]; 2820 } 2821 2822 @Override setProcessMemoryTrimLevel(String process, int userId, int level)2823 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) 2824 throws RemoteException { 2825 if (!isCallerShell()) { 2826 throw new SecurityException("Only shell can call it"); 2827 } 2828 synchronized (this) { 2829 final ProcessRecord app = findProcessLOSP(process, userId, "setProcessMemoryTrimLevel"); 2830 if (app == null) { 2831 throw new IllegalArgumentException("Unknown process: " + process); 2832 } 2833 final IApplicationThread thread = app.getThread(); 2834 if (thread == null) { 2835 throw new IllegalArgumentException("Process has no app thread"); 2836 } 2837 if (app.mProfile.getTrimMemoryLevel() >= level) { 2838 throw new IllegalArgumentException( 2839 "Unable to set a higher trim level than current level"); 2840 } 2841 if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || 2842 app.mState.getCurProcState() > PROCESS_STATE_IMPORTANT_FOREGROUND)) { 2843 throw new IllegalArgumentException("Unable to set a background trim level " 2844 + "on a foreground process"); 2845 } 2846 thread.scheduleTrimMemory(level); 2847 synchronized (mProcLock) { 2848 app.mProfile.setTrimMemoryLevel(level); 2849 } 2850 return true; 2851 } 2852 } 2853 dispatchOomAdjObserver(String msg)2854 void dispatchOomAdjObserver(String msg) { 2855 OomAdjObserver observer; 2856 synchronized (mOomAdjObserverLock) { 2857 observer = mCurOomAdjObserver; 2858 } 2859 2860 if (observer != null) { 2861 observer.onOomAdjMessage(msg); 2862 } 2863 } 2864 setOomAdjObserver(int uid, OomAdjObserver observer)2865 void setOomAdjObserver(int uid, OomAdjObserver observer) { 2866 synchronized (mOomAdjObserverLock) { 2867 mCurOomAdjUid = uid; 2868 mCurOomAdjObserver = observer; 2869 } 2870 } 2871 clearOomAdjObserver()2872 void clearOomAdjObserver() { 2873 synchronized (mOomAdjObserverLock) { 2874 mCurOomAdjUid = -1; 2875 mCurOomAdjObserver = null; 2876 } 2877 } 2878 reportUidInfoMessageLocked(String tag, String msg, int uid)2879 void reportUidInfoMessageLocked(String tag, String msg, int uid) { 2880 Slog.i(TAG, msg); 2881 synchronized (mOomAdjObserverLock) { 2882 if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) { 2883 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget(); 2884 } 2885 } 2886 } 2887 2888 /** 2889 * @deprecated use {@link #startActivityWithFeature} instead 2890 */ 2891 @Deprecated 2892 @Override startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)2893 public int startActivity(IApplicationThread caller, String callingPackage, 2894 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 2895 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { 2896 return mActivityTaskManager.startActivity(caller, callingPackage, null, intent, 2897 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 2898 } 2899 2900 @Override startActivityWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)2901 public int startActivityWithFeature(IApplicationThread caller, String callingPackage, 2902 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, 2903 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, 2904 Bundle bOptions) { 2905 return mActivityTaskManager.startActivity(caller, callingPackage, callingFeatureId, intent, 2906 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions); 2907 } 2908 2909 /** 2910 * @deprecated use {@link #startActivityAsUserWithFeature} instead 2911 */ 2912 @Deprecated 2913 @Override startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)2914 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 2915 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 2916 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 2917 return startActivityAsUserWithFeature(caller, callingPackage, null, intent, resolvedType, 2918 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId); 2919 } 2920 2921 @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)2922 public final int startActivityAsUserWithFeature(IApplicationThread caller, 2923 String callingPackage, String callingFeatureId, Intent intent, String resolvedType, 2924 IBinder resultTo, String resultWho, int requestCode, int startFlags, 2925 ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 2926 return mActivityTaskManager.startActivityAsUser(caller, callingPackage, 2927 callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, 2928 startFlags, profilerInfo, bOptions, userId); 2929 } 2930 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)2931 WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 2932 @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, 2933 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, 2934 Bundle bOptions, int userId) { 2935 return mActivityTaskManager.startActivityAndWait(caller, callingPackage, 2936 callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, 2937 startFlags, profilerInfo, bOptions, userId); 2938 } 2939 2940 @Override startActivityFromRecents(int taskId, Bundle bOptions)2941 public final int startActivityFromRecents(int taskId, Bundle bOptions) { 2942 return mActivityTaskManager.startActivityFromRecents(taskId, bOptions); 2943 } 2944 2945 /** 2946 * This is the internal entry point for handling Activity.finish(). 2947 * 2948 * @param token The Binder token referencing the Activity we want to finish. 2949 * @param resultCode Result code, if any, from this Activity. 2950 * @param resultData Result data (Intent), if any, from this Activity. 2951 * @param finishTask Whether to finish the task associated with this Activity. 2952 * 2953 * @return Returns true if the activity successfully finished, or false if it is still running. 2954 */ 2955 @Override finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)2956 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 2957 int finishTask) { 2958 return ActivityClient.getInstance().finishActivity(token, resultCode, resultData, 2959 finishTask); 2960 } 2961 2962 @Override setRequestedOrientation(IBinder token, int requestedOrientation)2963 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 2964 ActivityClient.getInstance().setRequestedOrientation(token, requestedOrientation); 2965 } 2966 2967 @Override finishHeavyWeightApp()2968 public final void finishHeavyWeightApp() { 2969 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 2970 != PackageManager.PERMISSION_GRANTED) { 2971 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 2972 + Binder.getCallingPid() 2973 + ", uid=" + Binder.getCallingUid() 2974 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 2975 Slog.w(TAG, msg); 2976 throw new SecurityException(msg); 2977 } 2978 mAtmInternal.finishHeavyWeightApp(); 2979 } 2980 2981 @Override crashApplication(int uid, int initialPid, String packageName, int userId, String message, boolean force)2982 public void crashApplication(int uid, int initialPid, String packageName, int userId, 2983 String message, boolean force) { 2984 crashApplicationWithType(uid, initialPid, packageName, userId, message, force, 2985 RemoteServiceException.TYPE_ID); 2986 } 2987 2988 @Override crashApplicationWithType(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId)2989 public void crashApplicationWithType(int uid, int initialPid, String packageName, int userId, 2990 String message, boolean force, int exceptionTypeId) { 2991 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 2992 != PackageManager.PERMISSION_GRANTED) { 2993 String msg = "Permission Denial: crashApplication() from pid=" 2994 + Binder.getCallingPid() 2995 + ", uid=" + Binder.getCallingUid() 2996 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 2997 Slog.w(TAG, msg); 2998 throw new SecurityException(msg); 2999 } 3000 3001 synchronized(this) { 3002 mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId, 3003 message, force, exceptionTypeId); 3004 } 3005 } 3006 3007 /** 3008 * Main function for removing an existing process from the activity manager 3009 * as a result of that process going away. Clears out all connections 3010 * to the process. 3011 */ 3012 @GuardedBy("this") handleAppDiedLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, boolean fromBinderDied)3013 final void handleAppDiedLocked(ProcessRecord app, int pid, 3014 boolean restarting, boolean allowRestart, boolean fromBinderDied) { 3015 boolean kept = cleanUpApplicationRecordLocked(app, pid, restarting, allowRestart, -1, 3016 false /*replacingPid*/, fromBinderDied); 3017 if (!kept && !restarting) { 3018 removeLruProcessLocked(app); 3019 if (pid > 0) { 3020 ProcessList.remove(pid); 3021 } 3022 } 3023 3024 mAppProfiler.onAppDiedLocked(app); 3025 3026 mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> { 3027 Slog.w(TAG, "Crash of app " + app.processName 3028 + " running instrumentation " + app.getActiveInstrumentation().mClass); 3029 Bundle info = new Bundle(); 3030 info.putString("shortMsg", "Process crashed."); 3031 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 3032 }); 3033 } 3034 3035 @GuardedBy(anyOf = {"this", "mProcLock"}) getRecordForAppLOSP(IApplicationThread thread)3036 ProcessRecord getRecordForAppLOSP(IApplicationThread thread) { 3037 if (thread == null) { 3038 return null; 3039 } 3040 3041 ProcessRecord record = mProcessList.getLRURecordForAppLOSP(thread); 3042 if (record != null) return record; 3043 3044 // Validation: if it isn't in the LRU list, it shouldn't exist, but let's 3045 // double-check that. 3046 final IBinder threadBinder = thread.asBinder(); 3047 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 3048 mProcessList.getProcessNamesLOSP().getMap(); 3049 for (int i = pmap.size()-1; i >= 0; i--) { 3050 final SparseArray<ProcessRecord> procs = pmap.valueAt(i); 3051 for (int j = procs.size()-1; j >= 0; j--) { 3052 final ProcessRecord proc = procs.valueAt(j); 3053 final IApplicationThread procThread = proc.getThread(); 3054 if (procThread != null && procThread.asBinder() == threadBinder) { 3055 Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: " 3056 + proc); 3057 return proc; 3058 } 3059 } 3060 } 3061 3062 return null; 3063 } 3064 3065 @GuardedBy("this") appDiedLocked(ProcessRecord app, String reason)3066 final void appDiedLocked(ProcessRecord app, String reason) { 3067 appDiedLocked(app, app.getPid(), app.getThread(), false, reason); 3068 } 3069 3070 @GuardedBy("this") appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied, String reason)3071 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, 3072 boolean fromBinderDied, String reason) { 3073 // First check if this ProcessRecord is actually active for the pid. 3074 final ProcessRecord curProc; 3075 synchronized (mPidsSelfLocked) { 3076 curProc = mPidsSelfLocked.get(pid); 3077 } 3078 if (curProc != app) { 3079 if (!fromBinderDied || !mProcessList.handleDyingAppDeathLocked(app, pid)) { 3080 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc); 3081 } 3082 return; 3083 } 3084 3085 mBatteryStatsService.noteProcessDied(app.info.uid, pid); 3086 3087 if (!app.isKilled()) { 3088 if (!fromBinderDied) { 3089 killProcessQuiet(pid); 3090 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_OTHER, 3091 ApplicationExitInfo.SUBREASON_UNKNOWN, reason); 3092 } 3093 ProcessList.killProcessGroup(app.uid, pid); 3094 synchronized (mProcLock) { 3095 app.setKilled(true); 3096 } 3097 } 3098 3099 // Clean up already done if the process has been re-started. 3100 IApplicationThread appThread; 3101 final int setAdj = app.mState.getSetAdj(); 3102 final int setProcState = app.mState.getSetProcState(); 3103 if (app.getPid() == pid && (appThread = app.getThread()) != null 3104 && appThread.asBinder() == thread.asBinder()) { 3105 boolean doLowMem = app.getActiveInstrumentation() == null; 3106 boolean doOomAdj = doLowMem; 3107 if (!app.isKilledByAm()) { 3108 reportUidInfoMessageLocked(TAG, 3109 "Process " + app.processName + " (pid " + pid + ") has died: " 3110 + ProcessList.makeOomAdjString(setAdj, true) + " " 3111 + ProcessList.makeProcStateString(setProcState), app.info.uid); 3112 mAppProfiler.setAllowLowerMemLevelLocked(true); 3113 } else { 3114 // Note that we always want to do oom adj to update our state with the 3115 // new number of procs. 3116 mAppProfiler.setAllowLowerMemLevelLocked(false); 3117 doLowMem = false; 3118 } 3119 EventLogTags.writeAmProcDied(app.userId, pid, app.processName, setAdj, setProcState); 3120 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 3121 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder()); 3122 handleAppDiedLocked(app, pid, false, true, fromBinderDied); 3123 3124 if (doOomAdj) { 3125 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END); 3126 } 3127 if (doLowMem) { 3128 mAppProfiler.doLowMemReportIfNeededLocked(app); 3129 } 3130 } else if (app.getPid() != pid) { 3131 // A new process has already been started. 3132 reportUidInfoMessageLocked(TAG, 3133 "Process " + app.processName + " (pid " + pid 3134 + ") has died and restarted (pid " + app.getPid() + ").", app.info.uid); 3135 3136 EventLogTags.writeAmProcDied(app.userId, app.getPid(), app.processName, 3137 setAdj, setProcState); 3138 } else if (DEBUG_PROCESSES) { 3139 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread " 3140 + thread.asBinder()); 3141 } 3142 3143 // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal 3144 // for pulling memory stats of other running processes when this process died. 3145 if (!hasMemcg()) { 3146 FrameworkStatsLog.write(FrameworkStatsLog.APP_DIED, SystemClock.elapsedRealtime()); 3147 } 3148 } 3149 3150 /** 3151 * If a stack trace dump file is configured, dump process stack traces. 3152 * @param firstPids of dalvik VM processes to dump stack traces for first 3153 * @param lastPids of dalvik VM processes to dump stack traces for last 3154 * @param nativePids optional list of native pids to dump stack crawls 3155 * @param logExceptionCreatingFile optional writer to which we log errors creating the file 3156 */ dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile)3157 public static File dumpStackTraces(ArrayList<Integer> firstPids, 3158 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 3159 ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile) { 3160 return dumpStackTraces(firstPids, processCpuTracker, lastPids, nativePids, 3161 logExceptionCreatingFile, null, null); 3162 } 3163 3164 /** 3165 * If a stack trace dump file is configured, dump process stack traces. 3166 * @param firstPids of dalvik VM processes to dump stack traces for first 3167 * @param lastPids of dalvik VM processes to dump stack traces for last 3168 * @param nativePids optional list of native pids to dump stack crawls 3169 * @param logExceptionCreatingFile optional writer to which we log errors creating the file 3170 * @param subject optional line related to the error 3171 */ dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, String subject)3172 public static File dumpStackTraces(ArrayList<Integer> firstPids, 3173 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 3174 ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, 3175 String subject) { 3176 return dumpStackTraces(firstPids, processCpuTracker, lastPids, nativePids, 3177 logExceptionCreatingFile, null, subject); 3178 } 3179 3180 /** 3181 * @param firstPidOffsets Optional, when it's set, it receives the start/end offset 3182 * of the very first pid to be dumped. 3183 */ dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, long[] firstPidOffsets, String subject)3184 /* package */ static File dumpStackTraces(ArrayList<Integer> firstPids, 3185 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 3186 ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, 3187 long[] firstPidOffsets, String subject) { 3188 ArrayList<Integer> extraPids = null; 3189 3190 Slog.i(TAG, "dumpStackTraces pids=" + lastPids + " nativepids=" + nativePids); 3191 3192 // Measure CPU usage as soon as we're called in order to get a realistic sampling 3193 // of the top users at the time of the request. 3194 if (processCpuTracker != null) { 3195 processCpuTracker.init(); 3196 try { 3197 Thread.sleep(200); 3198 } catch (InterruptedException ignored) { 3199 } 3200 3201 processCpuTracker.update(); 3202 3203 // We'll take the stack crawls of just the top apps using CPU. 3204 final int N = processCpuTracker.countWorkingStats(); 3205 extraPids = new ArrayList<>(); 3206 for (int i = 0; i < N && extraPids.size() < 5; i++) { 3207 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i); 3208 if (lastPids.indexOfKey(stats.pid) >= 0) { 3209 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid); 3210 3211 extraPids.add(stats.pid); 3212 } else { 3213 Slog.i(TAG, "Skipping next CPU consuming process, not a java proc: " 3214 + stats.pid); 3215 } 3216 } 3217 } 3218 3219 final File tracesDir = new File(ANR_TRACE_DIR); 3220 // Each set of ANR traces is written to a separate file and dumpstate will process 3221 // all such files and add them to a captured bug report if they're recent enough. 3222 maybePruneOldTraces(tracesDir); 3223 3224 // NOTE: We should consider creating the file in native code atomically once we've 3225 // gotten rid of the old scheme of dumping and lot of the code that deals with paths 3226 // can be removed. 3227 File tracesFile; 3228 try { 3229 tracesFile = createAnrDumpFile(tracesDir); 3230 } catch (IOException e) { 3231 Slog.w(TAG, "Exception creating ANR dump file:", e); 3232 if (logExceptionCreatingFile != null) { 3233 logExceptionCreatingFile.append("----- Exception creating ANR dump file -----\n"); 3234 e.printStackTrace(new PrintWriter(logExceptionCreatingFile)); 3235 } 3236 return null; 3237 } 3238 3239 if (subject != null) { 3240 try (FileOutputStream fos = new FileOutputStream(tracesFile, true)) { 3241 String header = "Subject: " + subject + "\n"; 3242 fos.write(header.getBytes(StandardCharsets.UTF_8)); 3243 } catch (IOException e) { 3244 Slog.w(TAG, "Exception writing subject to ANR dump file:", e); 3245 } 3246 } 3247 3248 Pair<Long, Long> offsets = dumpStackTraces( 3249 tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids); 3250 if (firstPidOffsets != null) { 3251 if (offsets == null) { 3252 firstPidOffsets[0] = firstPidOffsets[1] = -1; 3253 } else { 3254 firstPidOffsets[0] = offsets.first; // Start offset to the ANR trace file 3255 firstPidOffsets[1] = offsets.second; // End offset to the ANR trace file 3256 } 3257 } 3258 return tracesFile; 3259 } 3260 3261 @GuardedBy("ActivityManagerService.class") 3262 private static SimpleDateFormat sAnrFileDateFormat; 3263 static final String ANR_FILE_PREFIX = "anr_"; 3264 createAnrDumpFile(File tracesDir)3265 private static synchronized File createAnrDumpFile(File tracesDir) throws IOException { 3266 if (sAnrFileDateFormat == null) { 3267 sAnrFileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS"); 3268 } 3269 3270 final String formattedDate = sAnrFileDateFormat.format(new Date()); 3271 final File anrFile = new File(tracesDir, ANR_FILE_PREFIX + formattedDate); 3272 3273 if (anrFile.createNewFile()) { 3274 FileUtils.setPermissions(anrFile.getAbsolutePath(), 0600, -1, -1); // -rw------- 3275 return anrFile; 3276 } else { 3277 throw new IOException("Unable to create ANR dump file: createNewFile failed"); 3278 } 3279 } 3280 3281 /** 3282 * Prune all trace files that are more than a day old. 3283 * 3284 * NOTE: It might make sense to move this functionality to tombstoned eventually, along with a 3285 * shift away from anr_XX and tombstone_XX to a more descriptive name. We do it here for now 3286 * since it's the system_server that creates trace files for most ANRs. 3287 */ maybePruneOldTraces(File tracesDir)3288 private static void maybePruneOldTraces(File tracesDir) { 3289 final File[] files = tracesDir.listFiles(); 3290 if (files == null) return; 3291 3292 final int max = SystemProperties.getInt("tombstoned.max_anr_count", 64); 3293 final long now = System.currentTimeMillis(); 3294 Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed()); 3295 for (int i = 0; i < files.length; ++i) { 3296 if (i > max || (now - files[i].lastModified()) > DAY_IN_MILLIS) { 3297 if (!files[i].delete()) { 3298 Slog.w(TAG, "Unable to prune stale trace file: " + files[i]); 3299 } 3300 } 3301 } 3302 } 3303 3304 /** 3305 * Dump java traces for process {@code pid} to the specified file. If java trace dumping 3306 * fails, a native backtrace is attempted. Note that the timeout {@code timeoutMs} only applies 3307 * to the java section of the trace, a further {@code NATIVE_DUMP_TIMEOUT_MS} might be spent 3308 * attempting to obtain native traces in the case of a failure. Returns the total time spent 3309 * capturing traces. 3310 */ dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs)3311 private static long dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs) { 3312 final long timeStart = SystemClock.elapsedRealtime(); 3313 boolean javaSuccess = Debug.dumpJavaBacktraceToFileTimeout(pid, fileName, 3314 (int) (timeoutMs / 1000)); 3315 if (javaSuccess) { 3316 // Check that something is in the file, actually. Try-catch should not be necessary, 3317 // but better safe than sorry. 3318 try { 3319 long size = new File(fileName).length(); 3320 if (size < JAVA_DUMP_MINIMUM_SIZE) { 3321 Slog.w(TAG, "Successfully created Java ANR file is empty!"); 3322 javaSuccess = false; 3323 } 3324 } catch (Exception e) { 3325 Slog.w(TAG, "Unable to get ANR file size", e); 3326 javaSuccess = false; 3327 } 3328 } 3329 if (!javaSuccess) { 3330 Slog.w(TAG, "Dumping Java threads failed, initiating native stack dump."); 3331 if (!Debug.dumpNativeBacktraceToFileTimeout(pid, fileName, 3332 (NATIVE_DUMP_TIMEOUT_MS / 1000))) { 3333 Slog.w(TAG, "Native stack dump failed!"); 3334 } 3335 } 3336 3337 return SystemClock.elapsedRealtime() - timeStart; 3338 } 3339 3340 /** 3341 * @return The start/end offset of the trace of the very first PID 3342 */ dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, ArrayList<Integer> nativePids, ArrayList<Integer> extraPids)3343 public static Pair<Long, Long> dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, 3344 ArrayList<Integer> nativePids, ArrayList<Integer> extraPids) { 3345 3346 Slog.i(TAG, "Dumping to " + tracesFile); 3347 3348 // We don't need any sort of inotify based monitoring when we're dumping traces via 3349 // tombstoned. Data is piped to an "intercept" FD installed in tombstoned so we're in full 3350 // control of all writes to the file in question. 3351 3352 // We must complete all stack dumps within 20 seconds. 3353 long remainingTime = 20 * 1000; 3354 3355 // As applications are usually interested with the ANR stack traces, but we can't share with 3356 // them the stack traces other than their own stacks. So after the very first PID is 3357 // dumped, remember the current file size. 3358 long firstPidStart = -1; 3359 long firstPidEnd = -1; 3360 3361 // First collect all of the stacks of the most important pids. 3362 if (firstPids != null) { 3363 int num = firstPids.size(); 3364 for (int i = 0; i < num; i++) { 3365 final int pid = firstPids.get(i); 3366 // We don't copy ANR traces from the system_server intentionally. 3367 final boolean firstPid = i == 0 && MY_PID != pid; 3368 File tf = null; 3369 if (firstPid) { 3370 tf = new File(tracesFile); 3371 firstPidStart = tf.exists() ? tf.length() : 0; 3372 } 3373 3374 Slog.i(TAG, "Collecting stacks for pid " + pid); 3375 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, 3376 remainingTime); 3377 3378 remainingTime -= timeTaken; 3379 if (remainingTime <= 0) { 3380 Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + pid 3381 + "); deadline exceeded."); 3382 return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null; 3383 } 3384 3385 if (firstPid) { 3386 firstPidEnd = tf.length(); 3387 } 3388 if (DEBUG_ANR) { 3389 Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms"); 3390 } 3391 } 3392 } 3393 3394 // Next collect the stacks of the native pids 3395 if (nativePids != null) { 3396 for (int pid : nativePids) { 3397 Slog.i(TAG, "Collecting stacks for native pid " + pid); 3398 final long nativeDumpTimeoutMs = Math.min(NATIVE_DUMP_TIMEOUT_MS, remainingTime); 3399 3400 final long start = SystemClock.elapsedRealtime(); 3401 Debug.dumpNativeBacktraceToFileTimeout( 3402 pid, tracesFile, (int) (nativeDumpTimeoutMs / 1000)); 3403 final long timeTaken = SystemClock.elapsedRealtime() - start; 3404 3405 remainingTime -= timeTaken; 3406 if (remainingTime <= 0) { 3407 Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid + 3408 "); deadline exceeded."); 3409 return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null; 3410 } 3411 3412 if (DEBUG_ANR) { 3413 Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms"); 3414 } 3415 } 3416 } 3417 3418 // Lastly, dump stacks for all extra PIDs from the CPU tracker. 3419 if (extraPids != null) { 3420 for (int pid : extraPids) { 3421 Slog.i(TAG, "Collecting stacks for extra pid " + pid); 3422 3423 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, remainingTime); 3424 3425 remainingTime -= timeTaken; 3426 if (remainingTime <= 0) { 3427 Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + pid + 3428 "); deadline exceeded."); 3429 return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null; 3430 } 3431 3432 if (DEBUG_ANR) { 3433 Slog.d(TAG, "Done with extra pid " + pid + " in " + timeTaken + "ms"); 3434 } 3435 } 3436 } 3437 Slog.i(TAG, "Done dumping"); 3438 return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null; 3439 } 3440 3441 @Override clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)3442 public boolean clearApplicationUserData(final String packageName, boolean keepState, 3443 final IPackageDataObserver observer, int userId) { 3444 enforceNotIsolatedCaller("clearApplicationUserData"); 3445 int uid = Binder.getCallingUid(); 3446 int pid = Binder.getCallingPid(); 3447 final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false, 3448 ALLOW_FULL_ONLY, "clearApplicationUserData", null); 3449 3450 final ApplicationInfo appInfo; 3451 final boolean isInstantApp; 3452 3453 final long callingId = Binder.clearCallingIdentity(); 3454 try { 3455 IPackageManager pm = AppGlobals.getPackageManager(); 3456 // Instant packages are not protected 3457 if (getPackageManagerInternal().isPackageDataProtected( 3458 resolvedUserId, packageName)) { 3459 throw new SecurityException( 3460 "Cannot clear data for a protected package: " + packageName); 3461 } 3462 3463 ApplicationInfo applicationInfo = null; 3464 try { 3465 applicationInfo = pm.getApplicationInfo(packageName, 3466 MATCH_UNINSTALLED_PACKAGES, resolvedUserId); 3467 } catch (RemoteException e) { 3468 /* ignore */ 3469 } 3470 appInfo = applicationInfo; 3471 3472 final boolean clearingOwnUidData = appInfo != null && appInfo.uid == uid; 3473 3474 if (!clearingOwnUidData && checkComponentPermission(permission.CLEAR_APP_USER_DATA, 3475 pid, uid, -1, true) != PackageManager.PERMISSION_GRANTED) { 3476 throw new SecurityException("PID " + pid + " does not have permission " 3477 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 3478 + " of package " + packageName); 3479 } 3480 3481 final boolean hasInstantMetadata = getPackageManagerInternal() 3482 .hasInstantApplicationMetadata(packageName, resolvedUserId); 3483 final boolean isUninstalledAppWithoutInstantMetadata = 3484 (appInfo == null && !hasInstantMetadata); 3485 isInstantApp = (appInfo != null && appInfo.isInstantApp()) 3486 || hasInstantMetadata; 3487 final boolean canAccessInstantApps = checkComponentPermission( 3488 permission.ACCESS_INSTANT_APPS, pid, uid, -1, true) 3489 == PackageManager.PERMISSION_GRANTED; 3490 3491 if (isUninstalledAppWithoutInstantMetadata || (isInstantApp 3492 && !canAccessInstantApps)) { 3493 Slog.w(TAG, "Invalid packageName: " + packageName); 3494 if (observer != null) { 3495 try { 3496 observer.onRemoveCompleted(packageName, false); 3497 } catch (RemoteException e) { 3498 Slog.i(TAG, "Observer no longer exists."); 3499 } 3500 } 3501 return false; 3502 } 3503 3504 synchronized (this) { 3505 if (appInfo != null) { 3506 forceStopPackageLocked(packageName, appInfo.uid, "clear data"); 3507 mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId); 3508 } 3509 } 3510 3511 final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() { 3512 @Override 3513 public void onRemoveCompleted(String packageName, boolean succeeded) 3514 throws RemoteException { 3515 if (appInfo != null) { 3516 synchronized (ActivityManagerService.this) { 3517 finishForceStopPackageLocked(packageName, appInfo.uid); 3518 } 3519 } 3520 final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 3521 Uri.fromParts("package", packageName, null)); 3522 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 3523 intent.putExtra(Intent.EXTRA_UID, (appInfo != null) ? appInfo.uid : -1); 3524 intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId); 3525 if (isInstantApp) { 3526 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName); 3527 broadcastIntentInPackage("android", null, SYSTEM_UID, uid, pid, intent, 3528 null, null, 0, null, null, permission.ACCESS_INSTANT_APPS, null, 3529 false, false, resolvedUserId, false, null); 3530 } else { 3531 broadcastIntentInPackage("android", null, SYSTEM_UID, uid, pid, intent, 3532 null, null, 0, null, null, null, null, false, false, resolvedUserId, 3533 false, null); 3534 } 3535 3536 if (observer != null) { 3537 observer.onRemoveCompleted(packageName, succeeded); 3538 } 3539 } 3540 }; 3541 3542 try { 3543 // Clear application user data 3544 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId); 3545 3546 if (appInfo != null) { 3547 // Restore already established notification state and permission grants, 3548 // so it told us to keep those intact -- it's about to emplace app data 3549 // that is appropriate for those bits of system state. 3550 if (!keepState) { 3551 // Remove all permissions granted from/to this package 3552 mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId, 3553 true, false); 3554 3555 // Reset notification state 3556 INotificationManager inm = NotificationManager.getService(); 3557 inm.clearData(packageName, appInfo.uid, uid == appInfo.uid); 3558 } 3559 3560 // Clear its scheduled jobs 3561 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 3562 // Clearing data is a user-initiated action. 3563 js.cancelJobsForUid(appInfo.uid, JobParameters.STOP_REASON_USER, 3564 JobParameters.INTERNAL_STOP_REASON_DATA_CLEARED, "clear data"); 3565 3566 // Clear its pending alarms 3567 AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class); 3568 ami.removeAlarmsForUid(appInfo.uid); 3569 } 3570 } catch (RemoteException e) { 3571 } 3572 } finally { 3573 Binder.restoreCallingIdentity(callingId); 3574 } 3575 return true; 3576 } 3577 3578 @Override killBackgroundProcesses(final String packageName, int userId)3579 public void killBackgroundProcesses(final String packageName, int userId) { 3580 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3581 != PackageManager.PERMISSION_GRANTED && 3582 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 3583 != PackageManager.PERMISSION_GRANTED) { 3584 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 3585 + Binder.getCallingPid() 3586 + ", uid=" + Binder.getCallingUid() 3587 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3588 Slog.w(TAG, msg); 3589 throw new SecurityException(msg); 3590 } 3591 3592 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 3593 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 3594 final int[] userIds = mUserController.expandUserId(userId); 3595 3596 final long callingId = Binder.clearCallingIdentity(); 3597 try { 3598 IPackageManager pm = AppGlobals.getPackageManager(); 3599 for (int targetUserId : userIds) { 3600 int appId = -1; 3601 try { 3602 appId = UserHandle.getAppId( 3603 pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 3604 targetUserId)); 3605 } catch (RemoteException e) { 3606 } 3607 if (appId == -1) { 3608 Slog.w(TAG, "Invalid packageName: " + packageName); 3609 return; 3610 } 3611 synchronized (this) { 3612 synchronized (mProcLock) { 3613 mProcessList.killPackageProcessesLSP(packageName, appId, targetUserId, 3614 ProcessList.SERVICE_ADJ, ApplicationExitInfo.REASON_USER_REQUESTED, 3615 ApplicationExitInfo.SUBREASON_UNKNOWN, "kill background"); 3616 } 3617 } 3618 } 3619 } finally { 3620 Binder.restoreCallingIdentity(callingId); 3621 } 3622 } 3623 3624 @Override killAllBackgroundProcesses()3625 public void killAllBackgroundProcesses() { 3626 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3627 != PackageManager.PERMISSION_GRANTED) { 3628 final String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 3629 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3630 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3631 Slog.w(TAG, msg); 3632 throw new SecurityException(msg); 3633 } 3634 3635 final long callingId = Binder.clearCallingIdentity(); 3636 try { 3637 synchronized (this) { 3638 // Allow memory level to go down (the flag needs to be set before updating oom adj) 3639 // because this method is also used to simulate low memory. 3640 mAppProfiler.setAllowLowerMemLevelLocked(true); 3641 synchronized (mProcLock) { 3642 mProcessList.killPackageProcessesLSP(null /* packageName */, -1 /* appId */, 3643 UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ, 3644 ApplicationExitInfo.REASON_USER_REQUESTED, 3645 ApplicationExitInfo.SUBREASON_UNKNOWN, 3646 "kill all background"); 3647 } 3648 3649 mAppProfiler.doLowMemReportIfNeededLocked(null); 3650 } 3651 } finally { 3652 Binder.restoreCallingIdentity(callingId); 3653 } 3654 } 3655 3656 /** 3657 * Kills all background processes, except those matching any of the 3658 * specified properties. 3659 * 3660 * @param minTargetSdk the target SDK version at or above which to preserve 3661 * processes, or {@code -1} to ignore the target SDK 3662 * @param maxProcState the process state at or below which to preserve 3663 * processes, or {@code -1} to ignore the process state 3664 */ killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)3665 void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 3666 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3667 != PackageManager.PERMISSION_GRANTED) { 3668 final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid=" 3669 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 3670 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3671 Slog.w(TAG, msg); 3672 throw new SecurityException(msg); 3673 } 3674 3675 final long callingId = Binder.clearCallingIdentity(); 3676 try { 3677 synchronized (this) { 3678 synchronized (mProcLock) { 3679 mProcessList.killAllBackgroundProcessesExceptLSP(minTargetSdk, maxProcState); 3680 } 3681 } 3682 } finally { 3683 Binder.restoreCallingIdentity(callingId); 3684 } 3685 } 3686 3687 @Override forceStopPackage(final String packageName, int userId)3688 public void forceStopPackage(final String packageName, int userId) { 3689 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3690 != PackageManager.PERMISSION_GRANTED) { 3691 String msg = "Permission Denial: forceStopPackage() from pid=" 3692 + Binder.getCallingPid() 3693 + ", uid=" + Binder.getCallingUid() 3694 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3695 Slog.w(TAG, msg); 3696 throw new SecurityException(msg); 3697 } 3698 final int callingPid = Binder.getCallingPid(); 3699 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 3700 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 3701 final long callingId = Binder.clearCallingIdentity(); 3702 try { 3703 IPackageManager pm = AppGlobals.getPackageManager(); 3704 synchronized(this) { 3705 int[] users = userId == UserHandle.USER_ALL 3706 ? mUserController.getUsers() : new int[] { userId }; 3707 for (int user : users) { 3708 if (getPackageManagerInternal().isPackageStateProtected( 3709 packageName, user)) { 3710 Slog.w(TAG, "Ignoring request to force stop protected package " 3711 + packageName + " u" + user); 3712 return; 3713 } 3714 3715 int pkgUid = -1; 3716 try { 3717 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 3718 user); 3719 } catch (RemoteException e) { 3720 } 3721 if (pkgUid == -1) { 3722 Slog.w(TAG, "Invalid packageName: " + packageName); 3723 continue; 3724 } 3725 try { 3726 pm.setPackageStoppedState(packageName, true, user); 3727 } catch (RemoteException e) { 3728 } catch (IllegalArgumentException e) { 3729 Slog.w(TAG, "Failed trying to unstop package " 3730 + packageName + ": " + e); 3731 } 3732 if (mUserController.isUserRunning(user, 0)) { 3733 forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid); 3734 finishForceStopPackageLocked(packageName, pkgUid); 3735 } 3736 } 3737 } 3738 } finally { 3739 Binder.restoreCallingIdentity(callingId); 3740 } 3741 } 3742 3743 @Override addPackageDependency(String packageName)3744 public void addPackageDependency(String packageName) { 3745 int callingPid = Binder.getCallingPid(); 3746 if (callingPid == myPid()) { 3747 // Yeah, um, no. 3748 return; 3749 } 3750 ProcessRecord proc; 3751 synchronized (mPidsSelfLocked) { 3752 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 3753 } 3754 if (proc != null) { 3755 ArraySet<String> pkgDeps = proc.getPkgDeps(); 3756 synchronized (this) { 3757 synchronized (mProcLock) { 3758 if (pkgDeps == null) { 3759 proc.setPkgDeps(pkgDeps = new ArraySet<String>(1)); 3760 } 3761 pkgDeps.add(packageName); 3762 } 3763 } 3764 } 3765 } 3766 3767 /* 3768 * The pkg name and app id have to be specified. 3769 */ 3770 @Override killApplication(String pkg, int appId, int userId, String reason)3771 public void killApplication(String pkg, int appId, int userId, String reason) { 3772 if (pkg == null) { 3773 return; 3774 } 3775 // Make sure the uid is valid. 3776 if (appId < 0) { 3777 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 3778 return; 3779 } 3780 int callerUid = Binder.getCallingUid(); 3781 // Only the system server can kill an application 3782 if (UserHandle.getAppId(callerUid) == SYSTEM_UID) { 3783 // Post an aysnc message to kill the application 3784 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 3785 msg.arg1 = appId; 3786 msg.arg2 = userId; 3787 Bundle bundle = new Bundle(); 3788 bundle.putString("pkg", pkg); 3789 bundle.putString("reason", reason); 3790 msg.obj = bundle; 3791 mHandler.sendMessage(msg); 3792 } else { 3793 throw new SecurityException(callerUid + " cannot kill pkg: " + 3794 pkg); 3795 } 3796 } 3797 3798 @Override closeSystemDialogs(String reason)3799 public void closeSystemDialogs(String reason) { 3800 mAtmInternal.closeSystemDialogs(reason); 3801 } 3802 3803 @Override getProcessMemoryInfo(int[] pids)3804 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 3805 enforceNotIsolatedCaller("getProcessMemoryInfo"); 3806 3807 final long now = SystemClock.uptimeMillis(); 3808 final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME; 3809 3810 final int callingPid = Binder.getCallingPid(); 3811 final int callingUid = Binder.getCallingUid(); 3812 final int callingUserId = UserHandle.getUserId(callingUid); 3813 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 3814 callingUid) == PackageManager.PERMISSION_GRANTED; 3815 // Check REAL_GET_TASKS to see if they are allowed to access other uids 3816 final boolean allUids = mAtmInternal.isGetTasksAllowed( 3817 "getProcessMemoryInfo", callingPid, callingUid); 3818 3819 // Check if the caller is actually instrumented and from shell, if it's true, we may lift 3820 // the throttle of PSS info sampling. 3821 boolean isCallerInstrumentedFromShell = false; 3822 synchronized (mProcLock) { 3823 synchronized (mPidsSelfLocked) { 3824 ProcessRecord caller = mPidsSelfLocked.get(callingPid); 3825 if (caller != null) { 3826 final ActiveInstrumentation instr = caller.getActiveInstrumentation(); 3827 isCallerInstrumentedFromShell = instr != null 3828 && (instr.mSourceUid == SHELL_UID || instr.mSourceUid == ROOT_UID); 3829 } 3830 } 3831 } 3832 3833 final Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 3834 for (int i=pids.length-1; i>=0; i--) { 3835 final Debug.MemoryInfo mi = infos[i] = new Debug.MemoryInfo(); 3836 final ProcessRecord proc; 3837 final int oomAdj; 3838 final ProcessProfileRecord profile; 3839 synchronized (mAppProfiler.mProfilerLock) { 3840 synchronized (mPidsSelfLocked) { 3841 proc = mPidsSelfLocked.get(pids[i]); 3842 if (proc != null) { 3843 profile = proc.mProfile; 3844 oomAdj = profile.getSetAdj(); 3845 } else { 3846 profile = null; 3847 oomAdj = 0; 3848 } 3849 } 3850 } 3851 final int targetUid = (proc != null) ? proc.uid : -1; 3852 final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1; 3853 3854 if (callingUid != targetUid) { 3855 if (!allUids) { 3856 continue; // Not allowed to see other UIDs. 3857 } 3858 3859 if (!allUsers && (targetUserId != callingUserId)) { 3860 continue; // Not allowed to see other users. 3861 } 3862 } 3863 if (proc != null) { 3864 synchronized (mAppProfiler.mProfilerLock) { 3865 if (profile.getLastMemInfoTime() >= lastNow && profile.getLastMemInfo() != null 3866 && !isCallerInstrumentedFromShell) { 3867 // It hasn't been long enough that we want to take another sample; return 3868 // the last one. 3869 mi.set(profile.getLastMemInfo()); 3870 continue; 3871 } 3872 } 3873 } 3874 final long startTime = SystemClock.currentThreadTimeMillis(); 3875 final Debug.MemoryInfo memInfo = new Debug.MemoryInfo(); 3876 Debug.getMemoryInfo(pids[i], memInfo); 3877 final long duration = SystemClock.currentThreadTimeMillis() - startTime; 3878 mi.set(memInfo); 3879 if (proc != null) { 3880 synchronized (mAppProfiler.mProfilerLock) { 3881 profile.setLastMemInfo(memInfo); 3882 profile.setLastMemInfoTime(SystemClock.uptimeMillis()); 3883 if (profile.getThread() != null && profile.getSetAdj() == oomAdj) { 3884 // Record this for posterity if the process has been stable. 3885 profile.addPss(mi.getTotalPss(), 3886 mi.getTotalUss(), mi.getTotalRss(), false, 3887 ProcessStats.ADD_PSS_EXTERNAL_SLOW, duration); 3888 proc.getPkgList().forEachPackageProcessStats(holder -> { 3889 final ProcessState state = holder.state; 3890 FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED, 3891 proc.info.uid, 3892 state != null ? state.getName() : proc.processName, 3893 state != null ? state.getPackage() : proc.info.packageName, 3894 mi.getTotalPss(), 3895 mi.getTotalUss(), 3896 mi.getTotalRss(), 3897 ProcessStats.ADD_PSS_EXTERNAL_SLOW, 3898 duration, 3899 holder.appVersion); 3900 }); 3901 } 3902 } 3903 } 3904 } 3905 return infos; 3906 } 3907 3908 @Override getProcessPss(int[] pids)3909 public long[] getProcessPss(int[] pids) { 3910 enforceNotIsolatedCaller("getProcessPss"); 3911 3912 final int callingPid = Binder.getCallingPid(); 3913 final int callingUid = Binder.getCallingUid(); 3914 final int userId = UserHandle.getUserId(callingUid); 3915 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 3916 callingUid) == PackageManager.PERMISSION_GRANTED; 3917 // Check REAL_GET_TASKS to see if they are allowed to access other uids 3918 final boolean allUids = mAtmInternal.isGetTasksAllowed( 3919 "getProcessPss", callingPid, callingUid); 3920 3921 final long[] pss = new long[pids.length]; 3922 for (int i=pids.length-1; i>=0; i--) { 3923 ProcessRecord proc; 3924 int oomAdj; 3925 synchronized (mProcLock) { 3926 synchronized (mPidsSelfLocked) { 3927 proc = mPidsSelfLocked.get(pids[i]); 3928 oomAdj = proc != null ? proc.mState.getSetAdj() : 0; 3929 } 3930 } 3931 if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) { 3932 // The caller is not allow to get information about this other process... 3933 // just leave it empty. 3934 continue; 3935 } 3936 final long[] tmpUss = new long[3]; 3937 final long startTime = SystemClock.currentThreadTimeMillis(); 3938 final long pi = pss[i] = Debug.getPss(pids[i], tmpUss, null); 3939 final long duration = SystemClock.currentThreadTimeMillis() - startTime; 3940 if (proc != null) { 3941 final ProcessProfileRecord profile = proc.mProfile; 3942 synchronized (mAppProfiler.mProfilerLock) { 3943 if (profile.getThread() != null && profile.getSetAdj() == oomAdj) { 3944 // Record this for posterity if the process has been stable. 3945 profile.addPss(pi, tmpUss[0], tmpUss[2], false, 3946 ProcessStats.ADD_PSS_EXTERNAL, duration); 3947 proc.getPkgList().forEachPackageProcessStats(holder -> { 3948 FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED, 3949 proc.info.uid, 3950 holder.state.getName(), 3951 holder.state.getPackage(), 3952 pi, 3953 tmpUss[0], 3954 tmpUss[2], 3955 ProcessStats.ADD_PSS_EXTERNAL, 3956 duration, 3957 holder.appVersion); 3958 }); 3959 } 3960 } 3961 } 3962 } 3963 return pss; 3964 } 3965 3966 @Override killApplicationProcess(String processName, int uid)3967 public void killApplicationProcess(String processName, int uid) { 3968 if (processName == null) { 3969 return; 3970 } 3971 3972 int callerUid = Binder.getCallingUid(); 3973 // Only the system server can kill an application 3974 if (callerUid == SYSTEM_UID) { 3975 synchronized (this) { 3976 ProcessRecord app = getProcessRecordLocked(processName, uid); 3977 IApplicationThread thread; 3978 if (app != null && (thread = app.getThread()) != null) { 3979 try { 3980 thread.scheduleSuicide(); 3981 } catch (RemoteException e) { 3982 // If the other end already died, then our work here is done. 3983 } 3984 } else { 3985 Slog.w(TAG, "Process/uid not found attempting kill of " 3986 + processName + " / " + uid); 3987 } 3988 } 3989 } else { 3990 throw new SecurityException(callerUid + " cannot kill app process: " + 3991 processName); 3992 } 3993 } 3994 3995 @GuardedBy("this") forceStopPackageLocked(final String packageName, int uid, String reason)3996 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 3997 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 3998 false, true, false, false, UserHandle.getUserId(uid), reason); 3999 } 4000 4001 @GuardedBy("this") finishForceStopPackageLocked(final String packageName, int uid)4002 private void finishForceStopPackageLocked(final String packageName, int uid) { 4003 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 4004 Uri.fromParts("package", packageName, null)); 4005 if (!mProcessesReady) { 4006 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 4007 | Intent.FLAG_RECEIVER_FOREGROUND); 4008 } 4009 intent.putExtra(Intent.EXTRA_UID, uid); 4010 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 4011 broadcastIntentLocked(null, null, null, intent, 4012 null, null, 0, null, null, null, null, OP_NONE, 4013 null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(), 4014 Binder.getCallingPid(), UserHandle.getUserId(uid)); 4015 } 4016 cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4017 private void cleanupDisabledPackageComponentsLocked( 4018 String packageName, int userId, String[] changedClasses) { 4019 4020 Set<String> disabledClasses = null; 4021 boolean packageDisabled = false; 4022 IPackageManager pm = AppGlobals.getPackageManager(); 4023 4024 if (changedClasses == null) { 4025 // Nothing changed... 4026 return; 4027 } 4028 4029 // Determine enable/disable state of the package and its components. 4030 int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4031 for (int i = changedClasses.length - 1; i >= 0; i--) { 4032 final String changedClass = changedClasses[i]; 4033 4034 if (changedClass.equals(packageName)) { 4035 try { 4036 // Entire package setting changed 4037 enabled = pm.getApplicationEnabledSetting(packageName, 4038 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4039 } catch (Exception e) { 4040 // No such package/component; probably racing with uninstall. In any 4041 // event it means we have nothing further to do here. 4042 return; 4043 } 4044 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4045 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 4046 if (packageDisabled) { 4047 // Entire package is disabled. 4048 // No need to continue to check component states. 4049 disabledClasses = null; 4050 break; 4051 } 4052 } else { 4053 try { 4054 enabled = pm.getComponentEnabledSetting( 4055 new ComponentName(packageName, changedClass), 4056 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 4057 } catch (Exception e) { 4058 // As above, probably racing with uninstall. 4059 return; 4060 } 4061 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 4062 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) { 4063 if (disabledClasses == null) { 4064 disabledClasses = new ArraySet<>(changedClasses.length); 4065 } 4066 disabledClasses.add(changedClass); 4067 } 4068 } 4069 } 4070 4071 if (!packageDisabled && disabledClasses == null) { 4072 // Nothing to do here... 4073 return; 4074 } 4075 4076 mAtmInternal.cleanupDisabledPackageComponents( 4077 packageName, disabledClasses, userId, mBooted); 4078 4079 // Clean-up disabled services. 4080 mServices.bringDownDisabledPackageServicesLocked( 4081 packageName, disabledClasses, userId, false /* evenPersistent */, true /* doIt */); 4082 4083 // Clean-up disabled providers. 4084 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4085 mCpHelper.getProviderMap().collectPackageProvidersLocked( 4086 packageName, disabledClasses, true, false, userId, providers); 4087 for (int i = providers.size() - 1; i >= 0; i--) { 4088 mCpHelper.removeDyingProviderLocked(null, providers.get(i), true); 4089 } 4090 4091 // Clean-up disabled broadcast receivers. 4092 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 4093 mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4094 packageName, disabledClasses, userId, true); 4095 } 4096 4097 } 4098 clearBroadcastQueueForUserLocked(int userId)4099 final boolean clearBroadcastQueueForUserLocked(int userId) { 4100 boolean didSomething = false; 4101 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 4102 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4103 null, null, userId, true); 4104 } 4105 return didSomething; 4106 } 4107 4108 @GuardedBy("this") forceStopAppZygoteLocked(String packageName, int appId, int userId)4109 final void forceStopAppZygoteLocked(String packageName, int appId, int userId) { 4110 if (packageName == null) { 4111 return; 4112 } 4113 if (appId < 0) { 4114 try { 4115 appId = UserHandle.getAppId(AppGlobals.getPackageManager() 4116 .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0)); 4117 } catch (RemoteException e) { 4118 } 4119 } 4120 4121 mProcessList.killAppZygotesLocked(packageName, appId, userId, true /* force */); 4122 } 4123 4124 @GuardedBy("this") forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reason)4125 final boolean forceStopPackageLocked(String packageName, int appId, 4126 boolean callerWillRestart, boolean purgeCache, boolean doit, 4127 boolean evenPersistent, boolean uninstalling, int userId, String reason) { 4128 int i; 4129 4130 if (userId == UserHandle.USER_ALL && packageName == null) { 4131 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 4132 } 4133 4134 if (appId < 0 && packageName != null) { 4135 try { 4136 appId = UserHandle.getAppId(AppGlobals.getPackageManager() 4137 .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0)); 4138 } catch (RemoteException e) { 4139 } 4140 } 4141 4142 boolean didSomething; 4143 if (doit) { 4144 if (packageName != null) { 4145 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId 4146 + " user=" + userId + ": " + reason); 4147 } else { 4148 Slog.i(TAG, "Force stopping u" + userId + ": " + reason); 4149 } 4150 4151 mAppErrors.resetProcessCrashTime(packageName == null, appId, userId); 4152 } 4153 4154 synchronized (mProcLock) { 4155 // Notify first that the package is stopped, so its process won't be restarted 4156 // unexpectedly if there is an activity of the package without attached process 4157 // becomes visible when killing its other processes with visible activities. 4158 didSomething = mAtmInternal.onForceStopPackage( 4159 packageName, doit, evenPersistent, userId); 4160 4161 didSomething |= mProcessList.killPackageProcessesLSP(packageName, appId, userId, 4162 ProcessList.INVALID_ADJ, callerWillRestart, false /* allowRestart */, doit, 4163 evenPersistent, true /* setRemoved */, 4164 packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED 4165 : ApplicationExitInfo.REASON_USER_REQUESTED, 4166 ApplicationExitInfo.SUBREASON_UNKNOWN, 4167 (packageName == null ? ("stop user " + userId) : ("stop " + packageName)) 4168 + " due to " + reason); 4169 } 4170 4171 if (mServices.bringDownDisabledPackageServicesLocked( 4172 packageName, null /* filterByClasses */, userId, evenPersistent, doit)) { 4173 if (!doit) { 4174 return true; 4175 } 4176 didSomething = true; 4177 } 4178 4179 if (packageName == null) { 4180 // Remove all sticky broadcasts from this user. 4181 mStickyBroadcasts.remove(userId); 4182 } 4183 4184 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 4185 if (mCpHelper.getProviderMap().collectPackageProvidersLocked(packageName, null, doit, 4186 evenPersistent, userId, providers)) { 4187 if (!doit) { 4188 return true; 4189 } 4190 didSomething = true; 4191 } 4192 for (i = providers.size() - 1; i >= 0; i--) { 4193 mCpHelper.removeDyingProviderLocked(null, providers.get(i), true); 4194 } 4195 4196 // Remove transient permissions granted from/to this package/user 4197 mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false); 4198 4199 if (doit) { 4200 for (i = mBroadcastQueues.length - 1; i >= 0; i--) { 4201 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 4202 packageName, null, userId, doit); 4203 } 4204 } 4205 4206 if (packageName == null || uninstalling) { 4207 didSomething |= mPendingIntentController.removePendingIntentsForPackage( 4208 packageName, userId, appId, doit); 4209 } 4210 4211 if (doit) { 4212 if (purgeCache && packageName != null) { 4213 AttributeCache ac = AttributeCache.instance(); 4214 if (ac != null) { 4215 ac.removePackage(packageName); 4216 } 4217 } 4218 if (mBooted) { 4219 mAtmInternal.resumeTopActivities(true /* scheduleIdle */); 4220 } 4221 } 4222 4223 return didSomething; 4224 } 4225 4226 @GuardedBy("this") processStartTimedOutLocked(ProcessRecord app)4227 private final void processStartTimedOutLocked(ProcessRecord app) { 4228 final int pid = app.getPid(); 4229 boolean gone = removePidIfNoThreadLocked(app); 4230 4231 if (gone) { 4232 Slog.w(TAG, "Process " + app + " failed to attach"); 4233 EventLogTags.writeAmProcessStartTimeout(app.userId, pid, app.uid, app.processName); 4234 synchronized (mProcLock) { 4235 mProcessList.removeProcessNameLocked(app.processName, app.uid); 4236 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 4237 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 4238 // Take care of any launching providers waiting for this process. 4239 mCpHelper.cleanupAppInLaunchingProvidersLocked(app, true); 4240 // Take care of any services that are waiting for the process. 4241 mServices.processStartTimedOutLocked(app); 4242 app.killLocked("start timeout", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 4243 true); 4244 if (app.isolated) { 4245 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 4246 } 4247 removeLruProcessLocked(app); 4248 } 4249 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4250 if (backupTarget != null && backupTarget.app.getPid() == pid) { 4251 Slog.w(TAG, "Unattached app died before backup, skipping"); 4252 mHandler.post(new Runnable() { 4253 @Override 4254 public void run(){ 4255 try { 4256 IBackupManager bm = IBackupManager.Stub.asInterface( 4257 ServiceManager.getService(Context.BACKUP_SERVICE)); 4258 bm.agentDisconnectedForUser(app.userId, app.info.packageName); 4259 } catch (RemoteException e) { 4260 // Can't happen; the backup manager is local 4261 } 4262 } 4263 }); 4264 } 4265 if (isPendingBroadcastProcessLocked(pid)) { 4266 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 4267 skipPendingBroadcastLocked(pid); 4268 } 4269 } else { 4270 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 4271 } 4272 } 4273 4274 @GuardedBy("this") attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4275 private boolean attachApplicationLocked(@NonNull IApplicationThread thread, 4276 int pid, int callingUid, long startSeq) { 4277 4278 // Find the application record that is being attached... either via 4279 // the pid if we are running in multiple processes, or just pull the 4280 // next app record if we are emulating process with anonymous threads. 4281 ProcessRecord app; 4282 long startTime = SystemClock.uptimeMillis(); 4283 long bindApplicationTimeMillis; 4284 if (pid != MY_PID && pid >= 0) { 4285 synchronized (mPidsSelfLocked) { 4286 app = mPidsSelfLocked.get(pid); 4287 } 4288 if (app != null && (app.getStartUid() != callingUid || app.getStartSeq() != startSeq)) { 4289 String processName = null; 4290 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4291 if (pending != null) { 4292 processName = pending.processName; 4293 } 4294 final String msg = "attachApplicationLocked process:" + processName 4295 + " startSeq:" + startSeq 4296 + " pid:" + pid 4297 + " belongs to another existing app:" + app.processName 4298 + " startSeq:" + app.getStartSeq(); 4299 Slog.wtf(TAG, msg); 4300 // SafetyNet logging for b/131105245. 4301 EventLog.writeEvent(0x534e4554, "131105245", app.getStartUid(), msg); 4302 // If there is already an app occupying that pid that hasn't been cleaned up 4303 cleanUpApplicationRecordLocked(app, pid, false, false, -1, 4304 true /*replacingPid*/, false /* fromBinderDied */); 4305 removePidLocked(pid, app); 4306 app = null; 4307 } 4308 } else { 4309 app = null; 4310 } 4311 4312 // It's possible that process called attachApplication before we got a chance to 4313 // update the internal state. 4314 if (app == null && startSeq > 0) { 4315 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq); 4316 if (pending != null && pending.getStartUid() == callingUid 4317 && pending.getStartSeq() == startSeq 4318 && mProcessList.handleProcessStartedLocked(pending, pid, 4319 pending.isUsingWrapper(), startSeq, true)) { 4320 app = pending; 4321 } 4322 } 4323 4324 if (app == null) { 4325 Slog.w(TAG, "No pending application record for pid " + pid 4326 + " (IApplicationThread " + thread + "); dropping process"); 4327 EventLogTags.writeAmDropProcess(pid); 4328 if (pid > 0 && pid != MY_PID) { 4329 killProcessQuiet(pid); 4330 //TODO: killProcessGroup(app.info.uid, pid); 4331 // We can't log the app kill info for this process since we don't 4332 // know who it is, so just skip the logging. 4333 } else { 4334 try { 4335 thread.scheduleExit(); 4336 } catch (Exception e) { 4337 // Ignore exceptions. 4338 } 4339 } 4340 return false; 4341 } 4342 4343 // If this application record is still attached to a previous 4344 // process, clean it up now. 4345 if (app.getThread() != null) { 4346 handleAppDiedLocked(app, pid, true, true, false /* fromBinderDied */); 4347 } 4348 4349 // Tell the process all about itself. 4350 4351 if (DEBUG_ALL) Slog.v( 4352 TAG, "Binding process pid " + pid + " to record " + app); 4353 4354 final String processName = app.processName; 4355 try { 4356 AppDeathRecipient adr = new AppDeathRecipient( 4357 app, pid, thread); 4358 thread.asBinder().linkToDeath(adr, 0); 4359 app.setDeathRecipient(adr); 4360 } catch (RemoteException e) { 4361 app.resetPackageList(mProcessStats); 4362 mProcessList.startProcessLocked(app, 4363 new HostingRecord("link fail", processName), 4364 ZYGOTE_POLICY_FLAG_EMPTY); 4365 return false; 4366 } 4367 4368 EventLogTags.writeAmProcBound(app.userId, pid, app.processName); 4369 4370 synchronized (mProcLock) { 4371 app.mState.setCurAdj(ProcessList.INVALID_ADJ); 4372 app.mState.setSetAdj(ProcessList.INVALID_ADJ); 4373 app.mState.setVerifiedAdj(ProcessList.INVALID_ADJ); 4374 mOomAdjuster.setAttachingSchedGroupLSP(app); 4375 app.mState.setForcingToImportant(null); 4376 updateProcessForegroundLocked(app, false, 0, false); 4377 app.mState.setHasShownUi(false); 4378 app.mState.setCached(false); 4379 app.setDebugging(false); 4380 app.setKilledByAm(false); 4381 app.setKilled(false); 4382 // We carefully use the same state that PackageManager uses for 4383 // filtering, since we use this flag to decide if we need to install 4384 // providers when user is unlocked later 4385 app.setUnlocked(StorageManager.isUserKeyUnlocked(app.userId)); 4386 } 4387 4388 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4389 4390 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4391 List<ProviderInfo> providers = normalMode 4392 ? mCpHelper.generateApplicationProvidersLocked(app) 4393 : null; 4394 4395 if (providers != null && mCpHelper.checkAppInLaunchingProvidersLocked(app)) { 4396 Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG); 4397 msg.obj = app; 4398 mHandler.sendMessageDelayed(msg, 4399 ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS); 4400 } 4401 4402 checkTime(startTime, "attachApplicationLocked: before bindApplication"); 4403 4404 if (!normalMode) { 4405 Slog.i(TAG, "Launching preboot mode app: " + app); 4406 } 4407 4408 if (DEBUG_ALL) Slog.v( 4409 TAG, "New app record " + app 4410 + " thread=" + thread.asBinder() + " pid=" + pid); 4411 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 4412 try { 4413 int testMode = ApplicationThreadConstants.DEBUG_OFF; 4414 if (mDebugApp != null && mDebugApp.equals(processName)) { 4415 testMode = mWaitForDebugger 4416 ? ApplicationThreadConstants.DEBUG_WAIT 4417 : ApplicationThreadConstants.DEBUG_ON; 4418 app.setDebugging(true); 4419 if (mDebugTransient) { 4420 mDebugApp = mOrigDebugApp; 4421 mWaitForDebugger = mOrigWaitForDebugger; 4422 } 4423 } 4424 4425 boolean enableTrackAllocation = false; 4426 synchronized (mProcLock) { 4427 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) { 4428 enableTrackAllocation = true; 4429 mTrackAllocationApp = null; 4430 } 4431 } 4432 4433 // If the app is being launched for restore or full backup, set it up specially 4434 boolean isRestrictedBackupMode = false; 4435 if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) { 4436 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID 4437 && ((backupTarget.backupMode == BackupRecord.RESTORE) 4438 || (backupTarget.backupMode == BackupRecord.RESTORE_FULL) 4439 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL)); 4440 } 4441 4442 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 4443 4444 if (instr != null) { 4445 notifyPackageUse(instr.mClass.getPackageName(), 4446 PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION); 4447 } 4448 ProtoLog.v(WM_DEBUG_CONFIGURATION, "Binding proc %s with config %s", 4449 processName, app.getWindowProcessController().getConfiguration()); 4450 ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info; 4451 app.setCompat(compatibilityInfoForPackage(appInfo)); 4452 4453 ProfilerInfo profilerInfo = mAppProfiler.setupProfilerInfoLocked(thread, app, instr); 4454 4455 // We deprecated Build.SERIAL and it is not accessible to 4456 // Instant Apps and target APIs higher than O MR1. Since access to the serial 4457 // is now behind a permission we push down the value. 4458 final String buildSerial = (!appInfo.isInstantApp() 4459 && appInfo.targetSdkVersion < Build.VERSION_CODES.P) 4460 ? sTheRealBuildSerial : Build.UNKNOWN; 4461 4462 // Figure out whether the app needs to run in autofill compat mode. 4463 AutofillOptions autofillOptions = null; 4464 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 4465 final AutofillManagerInternal afm = LocalServices.getService( 4466 AutofillManagerInternal.class); 4467 if (afm != null) { 4468 autofillOptions = afm.getAutofillOptions( 4469 app.info.packageName, app.info.longVersionCode, app.userId); 4470 } 4471 } 4472 ContentCaptureOptions contentCaptureOptions = null; 4473 if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) { 4474 final ContentCaptureManagerInternal ccm = 4475 LocalServices.getService(ContentCaptureManagerInternal.class); 4476 if (ccm != null) { 4477 contentCaptureOptions = ccm.getOptionsForPackage(app.userId, 4478 app.info.packageName); 4479 } 4480 } 4481 SharedMemory serializedSystemFontMap = null; 4482 final FontManagerInternal fm = LocalServices.getService(FontManagerInternal.class); 4483 if (fm != null) { 4484 serializedSystemFontMap = fm.getSerializedSystemFontMap(); 4485 } 4486 4487 checkTime(startTime, "attachApplicationLocked: immediately before bindApplication"); 4488 bindApplicationTimeMillis = SystemClock.elapsedRealtime(); 4489 mAtmInternal.preBindApplication(app.getWindowProcessController()); 4490 final ActiveInstrumentation instr2 = app.getActiveInstrumentation(); 4491 if (mPlatformCompat != null) { 4492 mPlatformCompat.resetReporting(app.info); 4493 } 4494 final ProviderInfoList providerList = ProviderInfoList.fromList(providers); 4495 if (app.getIsolatedEntryPoint() != null) { 4496 // This is an isolated process which should just call an entry point instead of 4497 // being bound to an application. 4498 thread.runIsolatedEntryPoint( 4499 app.getIsolatedEntryPoint(), app.getIsolatedEntryPointArgs()); 4500 } else if (instr2 != null) { 4501 thread.bindApplication(processName, appInfo, providerList, 4502 instr2.mClass, 4503 profilerInfo, instr2.mArguments, 4504 instr2.mWatcher, 4505 instr2.mUiAutomationConnection, testMode, 4506 mBinderTransactionTrackingEnabled, enableTrackAllocation, 4507 isRestrictedBackupMode || !normalMode, app.isPersistent(), 4508 new Configuration(app.getWindowProcessController().getConfiguration()), 4509 app.getCompat(), getCommonServicesLocked(app.isolated), 4510 mCoreSettingsObserver.getCoreSettingsLocked(), 4511 buildSerial, autofillOptions, contentCaptureOptions, 4512 app.getDisabledCompatChanges(), serializedSystemFontMap); 4513 } else { 4514 thread.bindApplication(processName, appInfo, providerList, null, profilerInfo, 4515 null, null, null, testMode, 4516 mBinderTransactionTrackingEnabled, enableTrackAllocation, 4517 isRestrictedBackupMode || !normalMode, app.isPersistent(), 4518 new Configuration(app.getWindowProcessController().getConfiguration()), 4519 app.getCompat(), getCommonServicesLocked(app.isolated), 4520 mCoreSettingsObserver.getCoreSettingsLocked(), 4521 buildSerial, autofillOptions, contentCaptureOptions, 4522 app.getDisabledCompatChanges(), serializedSystemFontMap); 4523 } 4524 if (profilerInfo != null) { 4525 profilerInfo.closeFd(); 4526 profilerInfo = null; 4527 } 4528 4529 // Make app active after binding application or client may be running requests (e.g 4530 // starting activities) before it is ready. 4531 synchronized (mProcLock) { 4532 app.makeActive(thread, mProcessStats); 4533 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication"); 4534 } 4535 updateLruProcessLocked(app, false, null); 4536 checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked"); 4537 final long now = SystemClock.uptimeMillis(); 4538 synchronized (mAppProfiler.mProfilerLock) { 4539 app.mProfile.setLastRequestedGc(now); 4540 app.mProfile.setLastLowMemory(now); 4541 } 4542 } catch (Exception e) { 4543 // We need kill the process group here. (b/148588589) 4544 Slog.wtf(TAG, "Exception thrown during bind of " + app, e); 4545 app.resetPackageList(mProcessStats); 4546 app.unlinkDeathRecipient(); 4547 app.killLocked("error during bind", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 4548 true); 4549 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */); 4550 return false; 4551 } 4552 4553 // Remove this record from the list of starting applications. 4554 mPersistentStartingProcesses.remove(app); 4555 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, 4556 "Attach application locked removing on hold: " + app); 4557 mProcessesOnHold.remove(app); 4558 4559 boolean badApp = false; 4560 boolean didSomething = false; 4561 4562 // See if the top visible activity is waiting to run in this process... 4563 if (normalMode) { 4564 try { 4565 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); 4566 } catch (Exception e) { 4567 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); 4568 badApp = true; 4569 } 4570 } 4571 4572 // Find any services that should be running in this process... 4573 if (!badApp) { 4574 try { 4575 didSomething |= mServices.attachApplicationLocked(app, processName); 4576 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked"); 4577 } catch (Exception e) { 4578 Slog.wtf(TAG, "Exception thrown starting services in " + app, e); 4579 badApp = true; 4580 } 4581 } 4582 4583 // Check if a next-broadcast receiver is in this process... 4584 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 4585 try { 4586 didSomething |= sendPendingBroadcastsLocked(app); 4587 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked"); 4588 } catch (Exception e) { 4589 // If the app died trying to launch the receiver we declare it 'bad' 4590 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e); 4591 badApp = true; 4592 } 4593 } 4594 4595 // Check whether the next backup agent is in this process... 4596 if (!badApp && backupTarget != null && backupTarget.app == app) { 4597 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, 4598 "New app is backup target, launching agent for " + app); 4599 notifyPackageUse(backupTarget.appInfo.packageName, 4600 PackageManager.NOTIFY_PACKAGE_USE_BACKUP); 4601 try { 4602 thread.scheduleCreateBackupAgent(backupTarget.appInfo, 4603 compatibilityInfoForPackage(backupTarget.appInfo), 4604 backupTarget.backupMode, backupTarget.userId, backupTarget.operationType); 4605 } catch (Exception e) { 4606 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e); 4607 badApp = true; 4608 } 4609 } 4610 4611 if (badApp) { 4612 app.killLocked("error during init", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 4613 true); 4614 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */); 4615 return false; 4616 } 4617 4618 if (!didSomething) { 4619 updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN); 4620 checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked"); 4621 } 4622 4623 FrameworkStatsLog.write( 4624 FrameworkStatsLog.PROCESS_START_TIME, 4625 app.info.uid, 4626 pid, 4627 app.info.packageName, 4628 FrameworkStatsLog.PROCESS_START_TIME__TYPE__COLD, 4629 app.getStartTime(), 4630 (int) (bindApplicationTimeMillis - app.getStartTime()), 4631 (int) (SystemClock.elapsedRealtime() - app.getStartTime()), 4632 app.getHostingRecord().getType(), 4633 (app.getHostingRecord().getName() != null ? app.getHostingRecord().getName() : "")); 4634 return true; 4635 } 4636 4637 @Override attachApplication(IApplicationThread thread, long startSeq)4638 public final void attachApplication(IApplicationThread thread, long startSeq) { 4639 if (thread == null) { 4640 throw new SecurityException("Invalid application interface"); 4641 } 4642 synchronized (this) { 4643 int callingPid = Binder.getCallingPid(); 4644 final int callingUid = Binder.getCallingUid(); 4645 final long origId = Binder.clearCallingIdentity(); 4646 attachApplicationLocked(thread, callingPid, callingUid, startSeq); 4647 Binder.restoreCallingIdentity(origId); 4648 } 4649 } 4650 checkTime(long startTime, String where)4651 void checkTime(long startTime, String where) { 4652 long now = SystemClock.uptimeMillis(); 4653 if ((now - startTime) > 50) { 4654 // If we are taking more than 50ms, log about it. 4655 Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where); 4656 } 4657 } 4658 4659 @Override showBootMessage(final CharSequence msg, final boolean always)4660 public void showBootMessage(final CharSequence msg, final boolean always) { 4661 if (Binder.getCallingUid() != myUid()) { 4662 throw new SecurityException(); 4663 } 4664 mWindowManager.showBootMessage(msg, always); 4665 } 4666 finishBooting()4667 final void finishBooting() { 4668 TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing", 4669 Trace.TRACE_TAG_ACTIVITY_MANAGER); 4670 t.traceBegin("FinishBooting"); 4671 4672 synchronized (this) { 4673 if (!mBootAnimationComplete) { 4674 mCallFinishBooting = true; 4675 return; 4676 } 4677 mCallFinishBooting = false; 4678 } 4679 4680 // Let the ART runtime in zygote and system_server know that the boot completed. 4681 ZYGOTE_PROCESS.bootCompleted(); 4682 VMRuntime.bootCompleted(); 4683 4684 IntentFilter pkgFilter = new IntentFilter(); 4685 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 4686 pkgFilter.addDataScheme("package"); 4687 mContext.registerReceiver(new BroadcastReceiver() { 4688 @Override 4689 public void onReceive(Context context, Intent intent) { 4690 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 4691 if (pkgs != null) { 4692 for (String pkg : pkgs) { 4693 synchronized (ActivityManagerService.this) { 4694 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 4695 0, "query restart")) { 4696 setResultCode(Activity.RESULT_OK); 4697 return; 4698 } 4699 } 4700 } 4701 } 4702 } 4703 }, pkgFilter); 4704 4705 // Inform checkpointing systems of success 4706 try { 4707 // This line is needed to CTS test for the correct exception handling 4708 // See b/138952436#comment36 for context 4709 Slog.i(TAG, "About to commit checkpoint"); 4710 IStorageManager storageManager = PackageHelper.getStorageManager(); 4711 storageManager.commitChanges(); 4712 } catch (Exception e) { 4713 PowerManager pm = (PowerManager) 4714 mInjector.getContext().getSystemService(Context.POWER_SERVICE); 4715 pm.reboot("Checkpoint commit failed"); 4716 } 4717 4718 // Let system services know. 4719 mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED); 4720 4721 synchronized (this) { 4722 // Ensure that any processes we had put on hold are now started 4723 // up. 4724 final int NP = mProcessesOnHold.size(); 4725 if (NP > 0) { 4726 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mProcessesOnHold); 4727 for (int ip = 0; ip < NP; ip++) { 4728 if (DEBUG_PROCESSES) { 4729 Slog.v(TAG_PROCESSES, "Starting process on hold: " + procs.get(ip)); 4730 } 4731 mProcessList.startProcessLocked(procs.get(ip), 4732 new HostingRecord("on-hold"), 4733 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 4734 } 4735 } 4736 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 4737 return; 4738 } 4739 // Start looking for apps that are abusing wake locks. 4740 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); 4741 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); 4742 // Check if we are performing userspace reboot before setting sys.boot_completed to 4743 // avoid race with init reseting sys.init.userspace_reboot.in_progress once sys 4744 // .boot_completed is 1. 4745 if (InitProperties.userspace_reboot_in_progress().orElse(false)) { 4746 UserspaceRebootLogger.noteUserspaceRebootSuccess(); 4747 } 4748 // Tell anyone interested that we are done booting! 4749 SystemProperties.set("sys.boot_completed", "1"); 4750 4751 // And trigger dev.bootcomplete if we are not showing encryption progress 4752 if (!"trigger_restart_min_framework".equals(VoldProperties.decrypt().orElse("")) 4753 || "".equals(VoldProperties.encrypt_progress().orElse(""))) { 4754 SystemProperties.set("dev.bootcomplete", "1"); 4755 } 4756 mUserController.sendBootCompleted( 4757 new IIntentReceiver.Stub() { 4758 @Override 4759 public void performReceive(Intent intent, int resultCode, 4760 String data, Bundle extras, boolean ordered, 4761 boolean sticky, int sendingUser) { 4762 synchronized (mProcLock) { 4763 mAppProfiler.requestPssAllProcsLPr( 4764 SystemClock.uptimeMillis(), true, false); 4765 } 4766 } 4767 }); 4768 maybeLogUserspaceRebootEvent(); 4769 mUserController.scheduleStartProfiles(); 4770 } 4771 // UART is on if init's console service is running, send a warning notification. 4772 showConsoleNotificationIfActive(); 4773 4774 t.traceEnd(); 4775 } 4776 showConsoleNotificationIfActive()4777 private void showConsoleNotificationIfActive() { 4778 if (!SystemProperties.get("init.svc.console").equals("running")) { 4779 return; 4780 } 4781 String title = mContext 4782 .getString(com.android.internal.R.string.console_running_notification_title); 4783 String message = mContext 4784 .getString(com.android.internal.R.string.console_running_notification_message); 4785 Notification notification = 4786 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 4787 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 4788 .setWhen(0) 4789 .setOngoing(true) 4790 .setTicker(title) 4791 .setDefaults(0) // please be quiet 4792 .setColor(mContext.getColor( 4793 com.android.internal.R.color 4794 .system_notification_accent_color)) 4795 .setContentTitle(title) 4796 .setContentText(message) 4797 .setVisibility(Notification.VISIBILITY_PUBLIC) 4798 .build(); 4799 4800 NotificationManager notificationManager = 4801 mContext.getSystemService(NotificationManager.class); 4802 notificationManager.notifyAsUser( 4803 null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL); 4804 4805 } 4806 4807 @Override bootAnimationComplete()4808 public void bootAnimationComplete() { 4809 final boolean callFinishBooting; 4810 synchronized (this) { 4811 callFinishBooting = mCallFinishBooting; 4812 mBootAnimationComplete = true; 4813 } 4814 if (callFinishBooting) { 4815 finishBooting(); 4816 } 4817 } 4818 ensureBootCompleted()4819 final void ensureBootCompleted() { 4820 boolean booting; 4821 boolean enableScreen; 4822 synchronized (this) { 4823 booting = mBooting; 4824 mBooting = false; 4825 enableScreen = !mBooted; 4826 mBooted = true; 4827 } 4828 4829 if (booting) { 4830 finishBooting(); 4831 } 4832 4833 if (enableScreen) { 4834 mAtmInternal.enableScreenAfterBoot(mBooted); 4835 } 4836 } 4837 4838 /** 4839 * @deprecated Use {@link #getIntentSenderWithFeature} instead 4840 */ 4841 @Deprecated 4842 @Override getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)4843 public IIntentSender getIntentSender(int type, 4844 String packageName, IBinder token, String resultWho, 4845 int requestCode, Intent[] intents, String[] resolvedTypes, 4846 int flags, Bundle bOptions, int userId) { 4847 return getIntentSenderWithFeature(type, packageName, null, token, resultWho, requestCode, 4848 intents, resolvedTypes, flags, bOptions, userId); 4849 } 4850 4851 @Override getIntentSenderWithFeature(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)4852 public IIntentSender getIntentSenderWithFeature(int type, String packageName, String featureId, 4853 IBinder token, String resultWho, int requestCode, Intent[] intents, 4854 String[] resolvedTypes, int flags, Bundle bOptions, int userId) { 4855 enforceNotIsolatedCaller("getIntentSender"); 4856 4857 return getIntentSenderWithFeatureAsApp(type, packageName, featureId, token, resultWho, 4858 requestCode, intents, resolvedTypes, flags, bOptions, userId, 4859 Binder.getCallingUid()); 4860 } 4861 4862 /** 4863 * System-internal callers can invoke this with owningUid being the app's own identity 4864 * rather than the public API's behavior of always assigning ownership to the actual 4865 * caller identity. This will create an IntentSender as though the package/userid/uid app 4866 * were the caller, so that the ultimate PendingIntent is triggered with only the app's 4867 * capabilities and not the system's. Used in cases like notification groups where 4868 * the OS must synthesize a PendingIntent on an app's behalf. 4869 */ 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)4870 public IIntentSender getIntentSenderWithFeatureAsApp(int type, String packageName, 4871 String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, 4872 String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid) { 4873 // NOTE: The service lock isn't held in this method because nothing in the method requires 4874 // the service lock to be held. 4875 4876 // Refuse possible leaked file descriptors 4877 if (intents != null) { 4878 if (intents.length < 1) { 4879 throw new IllegalArgumentException("Intents array length must be >= 1"); 4880 } 4881 for (int i=0; i<intents.length; i++) { 4882 Intent intent = intents[i]; 4883 if (intent != null) { 4884 if (intent.hasFileDescriptors()) { 4885 throw new IllegalArgumentException("File descriptors passed in Intent"); 4886 } 4887 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 4888 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 4889 throw new IllegalArgumentException( 4890 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 4891 } 4892 intents[i] = new Intent(intent); 4893 } 4894 } 4895 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 4896 throw new IllegalArgumentException( 4897 "Intent array length does not match resolvedTypes length"); 4898 } 4899 } 4900 if (bOptions != null) { 4901 if (bOptions.hasFileDescriptors()) { 4902 throw new IllegalArgumentException("File descriptors passed in options"); 4903 } 4904 } 4905 4906 int origUserId = userId; 4907 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), owningUid, userId, 4908 type == ActivityManager.INTENT_SENDER_BROADCAST, 4909 ALLOW_NON_FULL, "getIntentSender", null); 4910 if (origUserId == UserHandle.USER_CURRENT) { 4911 // We don't want to evaluate this until the pending intent is 4912 // actually executed. However, we do want to always do the 4913 // security checking for it above. 4914 userId = UserHandle.USER_CURRENT; 4915 } 4916 try { 4917 if (owningUid != 0 && owningUid != SYSTEM_UID) { 4918 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName, 4919 MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(owningUid)); 4920 if (!UserHandle.isSameApp(owningUid, uid)) { 4921 String msg = "Permission Denial: getIntentSender() from pid=" 4922 + Binder.getCallingPid() 4923 + ", uid=" + owningUid 4924 + ", (need uid=" + uid + ")" 4925 + " is not allowed to send as package " + packageName; 4926 Slog.w(TAG, msg); 4927 throw new SecurityException(msg); 4928 } 4929 } 4930 4931 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 4932 return mAtmInternal.getIntentSender(type, packageName, featureId, owningUid, 4933 userId, token, resultWho, requestCode, intents, resolvedTypes, flags, 4934 bOptions); 4935 } 4936 return mPendingIntentController.getIntentSender(type, packageName, featureId, 4937 owningUid, userId, token, resultWho, requestCode, intents, resolvedTypes, 4938 flags, bOptions); 4939 } catch (RemoteException e) { 4940 throw new SecurityException(e); 4941 } 4942 } 4943 4944 @Override sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)4945 public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, 4946 Intent intent, String resolvedType, 4947 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 4948 if (target instanceof PendingIntentRecord) { 4949 return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType, 4950 allowlistToken, finishedReceiver, requiredPermission, options); 4951 } else { 4952 if (intent == null) { 4953 // Weird case: someone has given us their own custom IIntentSender, and now 4954 // they have someone else trying to send to it but of course this isn't 4955 // really a PendingIntent, so there is no base Intent, and the caller isn't 4956 // supplying an Intent... but we never want to dispatch a null Intent to 4957 // a receiver, so um... let's make something up. 4958 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call"); 4959 intent = new Intent(Intent.ACTION_MAIN); 4960 } 4961 try { 4962 target.send(code, intent, resolvedType, allowlistToken, null, 4963 requiredPermission, options); 4964 } catch (RemoteException e) { 4965 } 4966 // Platform code can rely on getting a result back when the send is done, but if 4967 // this intent sender is from outside of the system we can't rely on it doing that. 4968 // So instead we don't give it the result receiver, and instead just directly 4969 // report the finish immediately. 4970 if (finishedReceiver != null) { 4971 try { 4972 finishedReceiver.performReceive(intent, 0, 4973 null, null, false, false, UserHandle.getCallingUserId()); 4974 } catch (RemoteException e) { 4975 } 4976 } 4977 return 0; 4978 } 4979 } 4980 4981 @Override cancelIntentSender(IIntentSender sender)4982 public void cancelIntentSender(IIntentSender sender) { 4983 mPendingIntentController.cancelIntentSender(sender); 4984 } 4985 4986 @Override registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)4987 public void registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver) { 4988 mPendingIntentController.registerIntentSenderCancelListener(sender, receiver); 4989 } 4990 4991 @Override unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)4992 public void unregisterIntentSenderCancelListener(IIntentSender sender, 4993 IResultReceiver receiver) { 4994 mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver); 4995 } 4996 4997 @Override getInfoForIntentSender(IIntentSender sender)4998 public PendingIntentInfo getInfoForIntentSender(IIntentSender sender) { 4999 if (sender instanceof PendingIntentRecord) { 5000 PendingIntentRecord res = (PendingIntentRecord) sender; 5001 return new PendingIntentInfo( 5002 res.key.packageName, 5003 res.uid, 5004 (res.key.flags & PendingIntent.FLAG_IMMUTABLE) != 0, 5005 res.key.type); 5006 } else { 5007 return new PendingIntentInfo(null, -1, false, ActivityManager.INTENT_SENDER_UNKNOWN); 5008 } 5009 } 5010 5011 @Override isIntentSenderTargetedToPackage(IIntentSender pendingResult)5012 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 5013 if (!(pendingResult instanceof PendingIntentRecord)) { 5014 return false; 5015 } 5016 try { 5017 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5018 if (res.key.allIntents == null) { 5019 return false; 5020 } 5021 for (int i=0; i<res.key.allIntents.length; i++) { 5022 Intent intent = res.key.allIntents[i]; 5023 if (intent.getPackage() != null && intent.getComponent() != null) { 5024 return false; 5025 } 5026 } 5027 return true; 5028 } catch (ClassCastException e) { 5029 } 5030 return false; 5031 } 5032 5033 @Override isIntentSenderAnActivity(IIntentSender pendingResult)5034 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 5035 if (!(pendingResult instanceof PendingIntentRecord)) { 5036 return false; 5037 } 5038 try { 5039 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5040 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 5041 return true; 5042 } 5043 return false; 5044 } catch (ClassCastException e) { 5045 } 5046 return false; 5047 } 5048 5049 @Override getIntentForIntentSender(IIntentSender pendingResult)5050 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 5051 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5052 "getIntentForIntentSender()"); 5053 if (!(pendingResult instanceof PendingIntentRecord)) { 5054 return null; 5055 } 5056 try { 5057 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5058 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 5059 } catch (ClassCastException e) { 5060 } 5061 return null; 5062 } 5063 5064 @Override queryIntentComponentsForIntentSender( IIntentSender pendingResult, int matchFlags)5065 public ParceledListSlice<ResolveInfo> queryIntentComponentsForIntentSender( 5066 IIntentSender pendingResult, int matchFlags) { 5067 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, 5068 "queryIntentComponentsForIntentSender()"); 5069 Preconditions.checkNotNull(pendingResult); 5070 final PendingIntentRecord res; 5071 try { 5072 res = (PendingIntentRecord) pendingResult; 5073 } catch (ClassCastException e) { 5074 return null; 5075 } 5076 final Intent intent = res.key.requestIntent; 5077 if (intent == null) { 5078 return null; 5079 } 5080 final int userId = res.key.userId; 5081 switch (res.key.type) { 5082 case ActivityManager.INTENT_SENDER_ACTIVITY: 5083 return new ParceledListSlice<>(mContext.getPackageManager() 5084 .queryIntentActivitiesAsUser(intent, matchFlags, userId)); 5085 case ActivityManager.INTENT_SENDER_SERVICE: 5086 case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE: 5087 return new ParceledListSlice<>(mContext.getPackageManager() 5088 .queryIntentServicesAsUser(intent, matchFlags, userId)); 5089 case ActivityManager.INTENT_SENDER_BROADCAST: 5090 return new ParceledListSlice<>(mContext.getPackageManager() 5091 .queryBroadcastReceiversAsUser(intent, matchFlags, userId)); 5092 default: // ActivityManager.INTENT_SENDER_ACTIVITY_RESULT 5093 throw new IllegalStateException("Unsupported intent sender type: " + res.key.type); 5094 } 5095 } 5096 5097 @Override getTagForIntentSender(IIntentSender pendingResult, String prefix)5098 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) { 5099 if (!(pendingResult instanceof PendingIntentRecord)) { 5100 return null; 5101 } 5102 try { 5103 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 5104 synchronized (this) { 5105 return getTagForIntentSenderLocked(res, prefix); 5106 } 5107 } catch (ClassCastException e) { 5108 } 5109 return null; 5110 } 5111 getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5112 String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) { 5113 final Intent intent = res.key.requestIntent; 5114 if (intent != null) { 5115 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null 5116 || res.lastTagPrefix.equals(prefix))) { 5117 return res.lastTag; 5118 } 5119 res.lastTagPrefix = prefix; 5120 final StringBuilder sb = new StringBuilder(128); 5121 if (prefix != null) { 5122 sb.append(prefix); 5123 } 5124 if (intent.getAction() != null) { 5125 sb.append(intent.getAction()); 5126 } else if (intent.getComponent() != null) { 5127 intent.getComponent().appendShortString(sb); 5128 } else { 5129 sb.append("?"); 5130 } 5131 return res.lastTag = sb.toString(); 5132 } 5133 return null; 5134 } 5135 5136 @Override setProcessLimit(int max)5137 public void setProcessLimit(int max) { 5138 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5139 "setProcessLimit()"); 5140 synchronized (this) { 5141 mConstants.setOverrideMaxCachedProcesses(max); 5142 trimApplicationsLocked(true, OomAdjuster.OOM_ADJ_REASON_PROCESS_END); 5143 } 5144 } 5145 5146 @Override getProcessLimit()5147 public int getProcessLimit() { 5148 synchronized (this) { 5149 return mConstants.getOverrideMaxCachedProcesses(); 5150 } 5151 } 5152 importanceTokenDied(ImportanceToken token)5153 void importanceTokenDied(ImportanceToken token) { 5154 synchronized (ActivityManagerService.this) { 5155 ProcessRecord pr = null; 5156 synchronized (mPidsSelfLocked) { 5157 ImportanceToken cur 5158 = mImportantProcesses.get(token.pid); 5159 if (cur != token) { 5160 return; 5161 } 5162 mImportantProcesses.remove(token.pid); 5163 pr = mPidsSelfLocked.get(token.pid); 5164 if (pr == null) { 5165 return; 5166 } 5167 pr.mState.setForcingToImportant(null); 5168 updateProcessForegroundLocked(pr, false, 0, false); 5169 } 5170 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 5171 } 5172 } 5173 5174 @Override setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5175 public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) { 5176 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 5177 "setProcessImportant()"); 5178 synchronized(this) { 5179 boolean changed = false; 5180 5181 ProcessRecord pr = null; 5182 synchronized (mPidsSelfLocked) { 5183 pr = mPidsSelfLocked.get(pid); 5184 if (pr == null && isForeground) { 5185 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 5186 return; 5187 } 5188 ImportanceToken oldToken = mImportantProcesses.get(pid); 5189 if (oldToken != null) { 5190 oldToken.token.unlinkToDeath(oldToken, 0); 5191 mImportantProcesses.remove(pid); 5192 if (pr != null) { 5193 pr.mState.setForcingToImportant(null); 5194 } 5195 changed = true; 5196 } 5197 if (isForeground && token != null) { 5198 ImportanceToken newToken = new ImportanceToken(pid, token, reason) { 5199 @Override 5200 public void binderDied() { 5201 importanceTokenDied(this); 5202 } 5203 }; 5204 try { 5205 token.linkToDeath(newToken, 0); 5206 mImportantProcesses.put(pid, newToken); 5207 pr.mState.setForcingToImportant(newToken); 5208 changed = true; 5209 } catch (RemoteException e) { 5210 // If the process died while doing this, we will later 5211 // do the cleanup with the process death link. 5212 } 5213 } 5214 } 5215 5216 if (changed) { 5217 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 5218 } 5219 } 5220 } 5221 isAppForeground(int uid)5222 private boolean isAppForeground(int uid) { 5223 synchronized (mProcLock) { 5224 UidRecord uidRec = mProcessList.mActiveUids.get(uid); 5225 if (uidRec == null || uidRec.isIdle()) { 5226 return false; 5227 } 5228 return uidRec.getCurProcState() <= PROCESS_STATE_IMPORTANT_FOREGROUND; 5229 } 5230 } 5231 isAppBad(final String processName, final int uid)5232 private boolean isAppBad(final String processName, final int uid) { 5233 return mAppErrors.isBadProcess(processName, uid); 5234 } 5235 5236 // NOTE: this is an internal method used by the OnShellCommand implementation only and should 5237 // be guarded by permission checking. getUidState(int uid)5238 int getUidState(int uid) { 5239 synchronized (mProcLock) { 5240 return mProcessList.getUidProcStateLOSP(uid); 5241 } 5242 } 5243 5244 @GuardedBy("this") getUidStateLocked(int uid)5245 int getUidStateLocked(int uid) { 5246 return mProcessList.getUidProcStateLOSP(uid); 5247 } 5248 5249 // ========================================================= 5250 // PROCESS INFO 5251 // ========================================================= 5252 5253 static class ProcessInfoService extends IProcessInfoService.Stub { 5254 final ActivityManagerService mActivityManagerService; ProcessInfoService(ActivityManagerService activityManagerService)5255 ProcessInfoService(ActivityManagerService activityManagerService) { 5256 mActivityManagerService = activityManagerService; 5257 } 5258 5259 @Override getProcessStatesFromPids( int[] pids, int[] states)5260 public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) { 5261 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 5262 /*in*/ pids, /*out*/ states, null); 5263 } 5264 5265 @Override getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5266 public void getProcessStatesAndOomScoresFromPids( 5267 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 5268 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 5269 /*in*/ pids, /*out*/ states, /*out*/ scores); 5270 } 5271 } 5272 5273 /** 5274 * For each PID in the given input array, write the current process state 5275 * for that process into the states array, or -1 to indicate that no 5276 * process with the given PID exists. If scores array is provided, write 5277 * the oom score for the process into the scores array, with INVALID_ADJ 5278 * indicating the PID doesn't exist. 5279 */ getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5280 public void getProcessStatesAndOomScoresForPIDs( 5281 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 5282 if (scores != null) { 5283 enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE, 5284 "getProcessStatesAndOomScoresForPIDs()"); 5285 } 5286 5287 if (pids == null) { 5288 throw new NullPointerException("pids"); 5289 } else if (states == null) { 5290 throw new NullPointerException("states"); 5291 } else if (pids.length != states.length) { 5292 throw new IllegalArgumentException("pids and states arrays have different lengths!"); 5293 } else if (scores != null && pids.length != scores.length) { 5294 throw new IllegalArgumentException("pids and scores arrays have different lengths!"); 5295 } 5296 5297 synchronized (mProcLock) { 5298 synchronized (mPidsSelfLocked) { 5299 for (int i = 0; i < pids.length; i++) { 5300 ProcessRecord pr = mPidsSelfLocked.get(pids[i]); 5301 if (pr != null) { 5302 final boolean isPendingTop = 5303 mPendingStartActivityUids.isPendingTopPid(pr.uid, pids[i]); 5304 states[i] = isPendingTop ? PROCESS_STATE_TOP : pr.mState.getCurProcState(); 5305 if (scores != null) { 5306 scores[i] = isPendingTop 5307 ? (ProcessList.FOREGROUND_APP_ADJ - 1) : pr.mState.getCurAdj(); 5308 } 5309 } else { 5310 states[i] = PROCESS_STATE_NONEXISTENT; 5311 if (scores != null) { 5312 scores[i] = ProcessList.INVALID_ADJ; 5313 } 5314 } 5315 } 5316 } 5317 } 5318 } 5319 5320 // ========================================================= 5321 // PERMISSIONS 5322 // ========================================================= 5323 5324 static class PermissionController extends IPermissionController.Stub { 5325 ActivityManagerService mActivityManagerService; PermissionController(ActivityManagerService activityManagerService)5326 PermissionController(ActivityManagerService activityManagerService) { 5327 mActivityManagerService = activityManagerService; 5328 } 5329 5330 @Override checkPermission(String permission, int pid, int uid)5331 public boolean checkPermission(String permission, int pid, int uid) { 5332 return mActivityManagerService.checkPermission(permission, pid, 5333 uid) == PackageManager.PERMISSION_GRANTED; 5334 } 5335 5336 @Override noteOp(String op, int uid, String packageName)5337 public int noteOp(String op, int uid, String packageName) { 5338 // TODO moltmann: Allow to specify featureId 5339 return mActivityManagerService.mAppOpsService 5340 .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName, null, 5341 false, "", false).getOpMode(); 5342 } 5343 5344 @Override getPackagesForUid(int uid)5345 public String[] getPackagesForUid(int uid) { 5346 return mActivityManagerService.mContext.getPackageManager() 5347 .getPackagesForUid(uid); 5348 } 5349 5350 @Override isRuntimePermission(String permission)5351 public boolean isRuntimePermission(String permission) { 5352 try { 5353 PermissionInfo info = mActivityManagerService.mContext.getPackageManager() 5354 .getPermissionInfo(permission, 0); 5355 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 5356 == PermissionInfo.PROTECTION_DANGEROUS; 5357 } catch (NameNotFoundException nnfe) { 5358 Slog.e(TAG, "No such permission: "+ permission, nnfe); 5359 } 5360 return false; 5361 } 5362 5363 @Override getPackageUid(String packageName, int flags)5364 public int getPackageUid(String packageName, int flags) { 5365 try { 5366 return mActivityManagerService.mContext.getPackageManager() 5367 .getPackageUid(packageName, flags); 5368 } catch (NameNotFoundException nnfe) { 5369 return -1; 5370 } 5371 } 5372 } 5373 5374 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 5375 @Override checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5376 public int checkComponentPermission(String permission, int pid, int uid, 5377 int owningUid, boolean exported) { 5378 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 5379 owningUid, exported); 5380 } 5381 5382 @Override getAMSLock()5383 public Object getAMSLock() { 5384 return ActivityManagerService.this; 5385 } 5386 } 5387 checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5388 public static int checkComponentPermission(String permission, int pid, int uid, 5389 int owningUid, boolean exported) { 5390 if (pid == MY_PID) { 5391 return PackageManager.PERMISSION_GRANTED; 5392 } 5393 // If there is an explicit permission being checked, and this is coming from a process 5394 // that has been denied access to that permission, then just deny. Ultimately this may 5395 // not be quite right -- it means that even if the caller would have access for another 5396 // reason (such as being the owner of the component it is trying to access), it would still 5397 // fail. This also means the system and root uids would be able to deny themselves 5398 // access to permissions, which... well okay. ¯\_(ツ)_/¯ 5399 if (permission != null) { 5400 synchronized (sActiveProcessInfoSelfLocked) { 5401 ProcessInfo procInfo = sActiveProcessInfoSelfLocked.get(pid); 5402 if (procInfo != null && procInfo.deniedPermissions != null 5403 && procInfo.deniedPermissions.contains(permission)) { 5404 return PackageManager.PERMISSION_DENIED; 5405 } 5406 } 5407 } 5408 return ActivityManager.checkComponentPermission(permission, uid, 5409 owningUid, exported); 5410 } 5411 5412 /** 5413 * As the only public entry point for permissions checking, this method 5414 * can enforce the semantic that requesting a check on a null global 5415 * permission is automatically denied. (Internally a null permission 5416 * string is used when calling {@link #checkComponentPermission} in cases 5417 * when only uid-based security is needed.) 5418 * 5419 * This can be called with or without the global lock held. 5420 */ 5421 @Override checkPermission(String permission, int pid, int uid)5422 public int checkPermission(String permission, int pid, int uid) { 5423 if (permission == null) { 5424 return PackageManager.PERMISSION_DENIED; 5425 } 5426 return checkComponentPermission(permission, pid, uid, -1, true); 5427 } 5428 5429 /** 5430 * Binder IPC calls go through the public entry point. 5431 * This can be called with or without the global lock held. 5432 */ checkCallingPermission(String permission)5433 int checkCallingPermission(String permission) { 5434 return checkPermission(permission, 5435 Binder.getCallingPid(), 5436 Binder.getCallingUid()); 5437 } 5438 5439 /** 5440 * This can be called with or without the global lock held. 5441 */ enforceCallingPermission(String permission, String func)5442 void enforceCallingPermission(String permission, String func) { 5443 if (checkCallingPermission(permission) 5444 == PackageManager.PERMISSION_GRANTED) { 5445 return; 5446 } 5447 5448 String msg = "Permission Denial: " + func + " from pid=" 5449 + Binder.getCallingPid() 5450 + ", uid=" + Binder.getCallingUid() 5451 + " requires " + permission; 5452 Slog.w(TAG, msg); 5453 throw new SecurityException(msg); 5454 } 5455 5456 /** 5457 * This can be called with or without the global lock held. 5458 */ enforcePermission(String permission, int pid, int uid, String func)5459 void enforcePermission(String permission, int pid, int uid, String func) { 5460 if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) { 5461 return; 5462 } 5463 5464 String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid 5465 + " requires " + permission; 5466 Slog.w(TAG, msg); 5467 throw new SecurityException(msg); 5468 } 5469 isAppStartModeDisabled(int uid, String packageName)5470 public boolean isAppStartModeDisabled(int uid, String packageName) { 5471 synchronized (mProcLock) { 5472 return getAppStartModeLOSP(uid, packageName, 0, -1, false, true, false) 5473 == ActivityManager.APP_START_MODE_DISABLED; 5474 } 5475 } 5476 isInRestrictedBucket(int userId, String packageName, long nowElapsed)5477 private boolean isInRestrictedBucket(int userId, String packageName, long nowElapsed) { 5478 return UsageStatsManager.STANDBY_BUCKET_RESTRICTED 5479 <= mUsageStatsService.getAppStandbyBucket(packageName, userId, nowElapsed); 5480 } 5481 5482 // Unified app-op and target sdk check 5483 @GuardedBy(anyOf = {"this", "mProcLock"}) appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)5484 int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) { 5485 // Apps that target O+ are always subject to background check 5486 if (packageTargetSdk >= Build.VERSION_CODES.O) { 5487 if (DEBUG_BACKGROUND_CHECK) { 5488 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted"); 5489 } 5490 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 5491 } 5492 // It's a legacy app. If it's in the RESTRICTED bucket, always restrict on battery. 5493 if (mOnBattery // Short-circuit in common case. 5494 && mConstants.FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS 5495 && isInRestrictedBucket( 5496 UserHandle.getUserId(uid), packageName, SystemClock.elapsedRealtime())) { 5497 if (DEBUG_BACKGROUND_CHECK) { 5498 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " in RESTRICTED bucket"); 5499 } 5500 return ActivityManager.APP_START_MODE_DELAYED; 5501 } 5502 // Not in the RESTRICTED bucket so policy is based on AppOp check. 5503 int appop = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_RUN_IN_BACKGROUND, 5504 uid, packageName, null, ""); 5505 if (DEBUG_BACKGROUND_CHECK) { 5506 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop); 5507 } 5508 switch (appop) { 5509 case AppOpsManager.MODE_ALLOWED: 5510 // If force-background-check is enabled, restrict all apps that aren't allowlisted. 5511 if (mForceBackgroundCheck && 5512 !UserHandle.isCore(uid) && 5513 !isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ true)) { 5514 if (DEBUG_BACKGROUND_CHECK) { 5515 Slog.i(TAG, "Force background check: " + 5516 uid + "/" + packageName + " restricted"); 5517 } 5518 return ActivityManager.APP_START_MODE_DELAYED; 5519 } 5520 return ActivityManager.APP_START_MODE_NORMAL; 5521 case AppOpsManager.MODE_IGNORED: 5522 return ActivityManager.APP_START_MODE_DELAYED; 5523 default: 5524 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 5525 } 5526 } 5527 5528 // Service launch is available to apps with run-in-background exemptions but 5529 // some other background operations are not. If we're doing a check 5530 // of service-launch policy, allow those callers to proceed unrestricted. 5531 @GuardedBy(anyOf = {"this", "mProcLock"}) appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)5532 int appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) { 5533 // Persistent app? 5534 if (mPackageManagerInt.isPackagePersistent(packageName)) { 5535 if (DEBUG_BACKGROUND_CHECK) { 5536 Slog.i(TAG, "App " + uid + "/" + packageName 5537 + " is persistent; not restricted in background"); 5538 } 5539 return ActivityManager.APP_START_MODE_NORMAL; 5540 } 5541 5542 // Non-persistent but background whitelisted? 5543 if (uidOnBackgroundAllowlistLOSP(uid)) { 5544 if (DEBUG_BACKGROUND_CHECK) { 5545 Slog.i(TAG, "App " + uid + "/" + packageName 5546 + " on background allowlist; not restricted in background"); 5547 } 5548 return ActivityManager.APP_START_MODE_NORMAL; 5549 } 5550 5551 // Is this app on the battery whitelist? 5552 if (isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ false)) { 5553 if (DEBUG_BACKGROUND_CHECK) { 5554 Slog.i(TAG, "App " + uid + "/" + packageName 5555 + " on idle allowlist; not restricted in background"); 5556 } 5557 return ActivityManager.APP_START_MODE_NORMAL; 5558 } 5559 5560 // None of the service-policy criteria apply, so we apply the common criteria 5561 return appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk); 5562 } 5563 5564 @GuardedBy(anyOf = {"this", "mProcLock"}) getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)5565 int getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, 5566 int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) { 5567 if (mInternal.isPendingTopUid(uid)) { 5568 return ActivityManager.APP_START_MODE_NORMAL; 5569 } 5570 UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 5571 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg=" 5572 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle=" 5573 + (uidRec != null ? uidRec.isIdle() : false)); 5574 if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.isIdle()) { 5575 boolean ephemeral; 5576 if (uidRec == null) { 5577 ephemeral = getPackageManagerInternal().isPackageEphemeral( 5578 UserHandle.getUserId(uid), packageName); 5579 } else { 5580 ephemeral = uidRec.isEphemeral(); 5581 } 5582 5583 if (ephemeral) { 5584 // We are hard-core about ephemeral apps not running in the background. 5585 return ActivityManager.APP_START_MODE_DISABLED; 5586 } else { 5587 if (disabledOnly) { 5588 // The caller is only interested in whether app starts are completely 5589 // disabled for the given package (that is, it is an instant app). So 5590 // we don't need to go further, which is all just seeing if we should 5591 // apply a "delayed" mode for a regular app. 5592 return ActivityManager.APP_START_MODE_NORMAL; 5593 } 5594 final int startMode = (alwaysRestrict) 5595 ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk) 5596 : appServicesRestrictedInBackgroundLOSP(uid, packageName, 5597 packageTargetSdk); 5598 if (DEBUG_BACKGROUND_CHECK) { 5599 Slog.d(TAG, "checkAllowBackground: uid=" + uid 5600 + " pkg=" + packageName + " startMode=" + startMode 5601 + " onallowlist=" + isOnDeviceIdleAllowlistLOSP(uid, false) 5602 + " onallowlist(ei)=" + isOnDeviceIdleAllowlistLOSP(uid, true)); 5603 } 5604 if (startMode == ActivityManager.APP_START_MODE_DELAYED) { 5605 // This is an old app that has been forced into a "compatible as possible" 5606 // mode of background check. To increase compatibility, we will allow other 5607 // foreground apps to cause its services to start. 5608 if (callingPid >= 0) { 5609 ProcessRecord proc; 5610 synchronized (mPidsSelfLocked) { 5611 proc = mPidsSelfLocked.get(callingPid); 5612 } 5613 if (proc != null && !ActivityManager.isProcStateBackground( 5614 proc.mState.getCurProcState())) { 5615 // Whoever is instigating this is in the foreground, so we will allow it 5616 // to go through. 5617 return ActivityManager.APP_START_MODE_NORMAL; 5618 } 5619 } 5620 } 5621 return startMode; 5622 } 5623 } 5624 return ActivityManager.APP_START_MODE_NORMAL; 5625 } 5626 5627 /** 5628 * @return whether a UID is in the system, user or temp doze allowlist. 5629 */ 5630 @GuardedBy(anyOf = {"this", "mProcLock"}) isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo)5631 boolean isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo) { 5632 final int appId = UserHandle.getAppId(uid); 5633 5634 final int[] allowlist = allowExceptIdleToo 5635 ? mDeviceIdleExceptIdleAllowlist 5636 : mDeviceIdleAllowlist; 5637 5638 return Arrays.binarySearch(allowlist, appId) >= 0 5639 || Arrays.binarySearch(mDeviceIdleTempAllowlist, appId) >= 0 5640 || mPendingTempAllowlist.indexOfKey(uid) >= 0; 5641 } 5642 5643 /** 5644 * Is the uid allowlisted to start FGS? 5645 * @param uid 5646 * @return a TempAllowListEntry if the uid is allowed. 5647 * null if the uid is not allowed. 5648 */ 5649 @Nullable 5650 @GuardedBy(anyOf = {"this", "mProcLock"}) isAllowlistedForFgsStartLOSP(int uid)5651 FgsTempAllowListItem isAllowlistedForFgsStartLOSP(int uid) { 5652 if (Arrays.binarySearch(mDeviceIdleExceptIdleAllowlist, UserHandle.getAppId(uid)) >= 0) { 5653 return FAKE_TEMP_ALLOW_LIST_ITEM; 5654 } 5655 final Pair<Long, FgsTempAllowListItem> entry = mFgsStartTempAllowList.get(uid); 5656 return entry == null ? null : entry.second; 5657 } 5658 5659 /** 5660 * @return allowlist tag for a uid from mPendingTempAllowlist, null if not currently on 5661 * the allowlist 5662 */ 5663 @GuardedBy(anyOf = {"this", "mProcLock"}) getPendingTempAllowlistTagForUidLOSP(int uid)5664 String getPendingTempAllowlistTagForUidLOSP(int uid) { 5665 final PendingTempAllowlist ptw = mPendingTempAllowlist.get(uid); 5666 return ptw != null ? ptw.tag : null; 5667 } 5668 5669 @VisibleForTesting grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId)5670 public void grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId) { 5671 getPackageManagerInternal() 5672 .grantImplicitAccess(userId, intent, recipientAppId, visibleUid, true /*direct*/); 5673 } 5674 5675 /** 5676 * @param uri This uri must NOT contain an embedded userId. 5677 * @param userId The userId in which the uri is to be resolved. 5678 */ 5679 @Override checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)5680 public int checkUriPermission(Uri uri, int pid, int uid, 5681 final int modeFlags, int userId, IBinder callerToken) { 5682 enforceNotIsolatedCaller("checkUriPermission"); 5683 5684 // Our own process gets to do everything. 5685 if (pid == MY_PID) { 5686 return PackageManager.PERMISSION_GRANTED; 5687 } 5688 return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, modeFlags), uid, modeFlags) 5689 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED; 5690 } 5691 5692 @Override checkUriPermissions(@onNull List<Uri> uris, int pid, int uid, final int modeFlags, IBinder callerToken)5693 public int[] checkUriPermissions(@NonNull List<Uri> uris, int pid, int uid, 5694 final int modeFlags, IBinder callerToken) { 5695 final int size = uris.size(); 5696 int[] res = new int[size]; 5697 // Default value DENIED. 5698 Arrays.fill(res, PackageManager.PERMISSION_DENIED); 5699 5700 for (int i = 0; i < size; i++) { 5701 final Uri uri = uris.get(i); 5702 final int userId = ContentProvider.getUserIdFromUri(uri, mContext.getUserId()); 5703 res[i] = checkUriPermission(ContentProvider.getUriWithoutUserId(uri), pid, uid, 5704 modeFlags, userId, callerToken); 5705 } 5706 return res; 5707 } 5708 5709 /** 5710 * @param uri This uri must NOT contain an embedded userId. 5711 * @param userId The userId in which the uri is to be resolved. 5712 */ 5713 @Override grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)5714 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 5715 final int modeFlags, int userId) { 5716 enforceNotIsolatedCaller("grantUriPermission"); 5717 GrantUri grantUri = new GrantUri(userId, uri, modeFlags); 5718 synchronized (this) { 5719 final ProcessRecord r = getRecordForAppLOSP(caller); 5720 if (r == null) { 5721 throw new SecurityException("Unable to find app for caller " 5722 + caller 5723 + " when granting permission to uri " + grantUri); 5724 } 5725 if (targetPkg == null) { 5726 throw new IllegalArgumentException("null target"); 5727 } 5728 5729 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 5730 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 5731 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 5732 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 5733 5734 final Intent intent = new Intent(); 5735 intent.setData(uri); 5736 intent.setFlags(modeFlags); 5737 5738 final NeededUriGrants needed = mUgmInternal.checkGrantUriPermissionFromIntent(intent, 5739 r.uid, targetPkg, UserHandle.getUserId(r.uid)); 5740 mUgmInternal.grantUriPermissionUncheckedFromIntent(needed, null); 5741 } 5742 } 5743 5744 /** 5745 * @param uri This uri must NOT contain an embedded userId. 5746 * @param userId The userId in which the uri is to be resolved. 5747 */ 5748 @Override revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)5749 public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, 5750 final int modeFlags, int userId) { 5751 enforceNotIsolatedCaller("revokeUriPermission"); 5752 synchronized (this) { 5753 final ProcessRecord r = getRecordForAppLOSP(caller); 5754 if (r == null) { 5755 throw new SecurityException("Unable to find app for caller " 5756 + caller 5757 + " when revoking permission to uri " + uri); 5758 } 5759 if (uri == null) { 5760 Slog.w(TAG, "revokeUriPermission: null uri"); 5761 return; 5762 } 5763 5764 if (!Intent.isAccessUriMode(modeFlags)) { 5765 return; 5766 } 5767 5768 final String authority = uri.getAuthority(); 5769 final ProviderInfo pi = mCpHelper.getProviderInfoLocked(authority, userId, 5770 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 5771 if (pi == null) { 5772 Slog.w(TAG, "No content provider found for permission revoke: " 5773 + uri.toSafeString()); 5774 return; 5775 } 5776 5777 mUgmInternal.revokeUriPermission(targetPackage, r.uid, 5778 new GrantUri(userId, uri, modeFlags), modeFlags); 5779 } 5780 } 5781 5782 @Override showWaitingForDebugger(IApplicationThread who, boolean waiting)5783 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 5784 synchronized (mProcLock) { 5785 final ProcessRecord app = who != null ? getRecordForAppLOSP(who) : null; 5786 if (app == null) return; 5787 5788 Message msg = Message.obtain(); 5789 msg.what = WAIT_FOR_DEBUGGER_UI_MSG; 5790 msg.obj = app; 5791 msg.arg1 = waiting ? 1 : 0; 5792 mUiHandler.sendMessage(msg); 5793 } 5794 } 5795 5796 @Override getMemoryInfo(ActivityManager.MemoryInfo outInfo)5797 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 5798 mProcessList.getMemoryInfo(outInfo); 5799 } 5800 5801 // ========================================================= 5802 // TASK MANAGEMENT 5803 // ========================================================= 5804 5805 @Override getTasks(int maxNum)5806 public List<RunningTaskInfo> getTasks(int maxNum) { 5807 return mActivityTaskManager.getTasks(maxNum); 5808 } 5809 5810 @Override cancelTaskWindowTransition(int taskId)5811 public void cancelTaskWindowTransition(int taskId) { 5812 mActivityTaskManager.cancelTaskWindowTransition(taskId); 5813 } 5814 5815 @Override setTaskResizeable(int taskId, int resizeableMode)5816 public void setTaskResizeable(int taskId, int resizeableMode) { 5817 mActivityTaskManager.setTaskResizeable(taskId, resizeableMode); 5818 } 5819 5820 @Override resizeTask(int taskId, Rect bounds, int resizeMode)5821 public void resizeTask(int taskId, Rect bounds, int resizeMode) { 5822 mActivityTaskManager.resizeTask(taskId, bounds, resizeMode); 5823 } 5824 5825 @Override getTaskBounds(int taskId)5826 public Rect getTaskBounds(int taskId) { 5827 return mActivityTaskManager.getTaskBounds(taskId); 5828 } 5829 5830 @Override removeTask(int taskId)5831 public boolean removeTask(int taskId) { 5832 return mActivityTaskManager.removeTask(taskId); 5833 } 5834 5835 @Override moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)5836 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, 5837 int flags, Bundle bOptions) { 5838 mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions); 5839 } 5840 5841 /** 5842 * Attempts to move a task backwards in z-order (the order of activities within the task is 5843 * unchanged). 5844 * 5845 * There are several possible results of this call: 5846 * - if the task is locked, then we will show the lock toast 5847 * - if there is a task behind the provided task, then that task is made visible and resumed as 5848 * this task is moved to the back 5849 * - otherwise, if there are no other tasks in the stack: 5850 * - if this task is in the pinned stack, then we remove the stack completely, which will 5851 * have the effect of moving the task to the top or bottom of the fullscreen stack 5852 * (depending on whether it is visible) 5853 * - otherwise, we simply return home and hide this task 5854 * 5855 * @param token A reference to the activity we wish to move 5856 * @param nonRoot If false then this only works if the activity is the root 5857 * of a task; if true it will work for any activity in a task. 5858 * @return Returns true if the move completed, false if not. 5859 */ 5860 @Override moveActivityTaskToBack(IBinder token, boolean nonRoot)5861 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 5862 return ActivityClient.getInstance().moveActivityTaskToBack(token, nonRoot); 5863 } 5864 5865 @Override moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)5866 public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) { 5867 mActivityTaskManager.moveTaskToRootTask(taskId, rootTaskId, toTop); 5868 } 5869 5870 @Override getRecentTasks(int maxNum, int flags, int userId)5871 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, 5872 int userId) { 5873 return mActivityTaskManager.getRecentTasks(maxNum, flags, userId); 5874 } 5875 5876 @Override getAllRootTaskInfos()5877 public List<RootTaskInfo> getAllRootTaskInfos() { 5878 return mActivityTaskManager.getAllRootTaskInfos(); 5879 } 5880 5881 @Override getTaskForActivity(IBinder token, boolean onlyRoot)5882 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 5883 return ActivityClient.getInstance().getTaskForActivity(token, onlyRoot); 5884 } 5885 5886 @Override updateDeviceOwner(String packageName)5887 public void updateDeviceOwner(String packageName) { 5888 final int callingUid = Binder.getCallingUid(); 5889 if (callingUid != 0 && callingUid != SYSTEM_UID) { 5890 throw new SecurityException("updateDeviceOwner called from non-system process"); 5891 } 5892 synchronized (this) { 5893 mDeviceOwnerName = packageName; 5894 } 5895 } 5896 5897 @Override updateLockTaskPackages(int userId, String[] packages)5898 public void updateLockTaskPackages(int userId, String[] packages) { 5899 mActivityTaskManager.updateLockTaskPackages(userId, packages); 5900 } 5901 5902 @Override isInLockTaskMode()5903 public boolean isInLockTaskMode() { 5904 return mActivityTaskManager.isInLockTaskMode(); 5905 } 5906 5907 @Override getLockTaskModeState()5908 public int getLockTaskModeState() { 5909 return mActivityTaskManager.getLockTaskModeState(); 5910 } 5911 5912 @Override startSystemLockTaskMode(int taskId)5913 public void startSystemLockTaskMode(int taskId) throws RemoteException { 5914 mActivityTaskManager.startSystemLockTaskMode(taskId); 5915 } 5916 5917 /** 5918 * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The 5919 * PackageManager could be unavailable at construction time and therefore needs to be accessed 5920 * on demand. 5921 */ 5922 @VisibleForTesting getPackageManager()5923 public IPackageManager getPackageManager() { 5924 return AppGlobals.getPackageManager(); 5925 } 5926 5927 @VisibleForTesting getPackageManagerInternal()5928 public PackageManagerInternal getPackageManagerInternal() { 5929 // Intentionally hold no locks: in case of race conditions, the mPackageManagerInt will 5930 // be set to the same value anyway. 5931 if (mPackageManagerInt == null) { 5932 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class); 5933 } 5934 return mPackageManagerInt; 5935 } 5936 getPermissionManagerInternal()5937 private PermissionManagerServiceInternal getPermissionManagerInternal() { 5938 // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will 5939 // be set to the same value anyway. 5940 if (mPermissionManagerInt == null) { 5941 mPermissionManagerInt = 5942 LocalServices.getService(PermissionManagerServiceInternal.class); 5943 } 5944 return mPermissionManagerInt; 5945 } 5946 getTestUtilityServiceLocked()5947 private TestUtilityService getTestUtilityServiceLocked() { 5948 if (mTestUtilityService == null) { 5949 mTestUtilityService = 5950 LocalServices.getService(TestUtilityService.class); 5951 } 5952 return mTestUtilityService; 5953 } 5954 5955 @Override appNotResponding(final String reason)5956 public void appNotResponding(final String reason) { 5957 final int callingPid = Binder.getCallingPid(); 5958 5959 synchronized (mPidsSelfLocked) { 5960 final ProcessRecord app = mPidsSelfLocked.get(callingPid); 5961 if (app == null) { 5962 throw new SecurityException("Unknown process: " + callingPid); 5963 } 5964 5965 mAnrHelper.appNotResponding(app, null, app.info, null, null, false, 5966 "App requested: " + reason); 5967 } 5968 } 5969 startPersistentApps(int matchFlags)5970 void startPersistentApps(int matchFlags) { 5971 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return; 5972 5973 synchronized (this) { 5974 try { 5975 final List<ApplicationInfo> apps = AppGlobals.getPackageManager() 5976 .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList(); 5977 for (ApplicationInfo app : apps) { 5978 if (!"android".equals(app.packageName)) { 5979 addAppLocked(app, null, false, null /* ABI override */, 5980 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 5981 } 5982 } 5983 } catch (RemoteException ex) { 5984 } 5985 } 5986 } 5987 5988 // ========================================================= 5989 // CONTENT PROVIDERS 5990 // ========================================================= 5991 getContentProviderHelper()5992 public ContentProviderHelper getContentProviderHelper() { 5993 return mCpHelper; 5994 } 5995 5996 @Override getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)5997 public final ContentProviderHolder getContentProvider( 5998 IApplicationThread caller, String callingPackage, String name, int userId, 5999 boolean stable) { 6000 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProvider: ", name); 6001 try { 6002 return mCpHelper.getContentProvider(caller, callingPackage, name, userId, stable); 6003 } finally { 6004 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6005 } 6006 } 6007 6008 @Override getContentProviderExternal( String name, int userId, IBinder token, String tag)6009 public ContentProviderHolder getContentProviderExternal( 6010 String name, int userId, IBinder token, String tag) { 6011 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProviderExternal: ", name); 6012 try { 6013 return mCpHelper.getContentProviderExternal(name, userId, token, tag); 6014 } finally { 6015 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6016 } 6017 } 6018 6019 /** 6020 * Drop a content provider from a ProcessRecord's bookkeeping 6021 */ 6022 @Override removeContentProvider(IBinder connection, boolean stable)6023 public void removeContentProvider(IBinder connection, boolean stable) { 6024 mCpHelper.removeContentProvider(connection, stable); 6025 } 6026 6027 /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */ 6028 @Deprecated 6029 @Override removeContentProviderExternal(String name, IBinder token)6030 public void removeContentProviderExternal(String name, IBinder token) { 6031 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternal: ", name); 6032 try { 6033 removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId()); 6034 } finally { 6035 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6036 } 6037 } 6038 6039 @Override removeContentProviderExternalAsUser(String name, IBinder token, int userId)6040 public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) { 6041 traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternalAsUser: ", name); 6042 try { 6043 mCpHelper.removeContentProviderExternalAsUser(name, token, userId); 6044 } finally { 6045 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6046 } 6047 } 6048 6049 @Override publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)6050 public final void publishContentProviders(IApplicationThread caller, 6051 List<ContentProviderHolder> providers) { 6052 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 6053 final int maxLength = 256; 6054 final StringBuilder sb = new StringBuilder(maxLength); 6055 sb.append("publishContentProviders: "); 6056 if (providers != null) { 6057 boolean first = true; 6058 for (int i = 0, size = providers.size(); i < size; i++) { 6059 final ContentProviderHolder holder = providers.get(i); 6060 if (holder != null && holder.info != null && holder.info.authority != null) { 6061 final int len = holder.info.authority.length(); 6062 if (sb.length() + len > maxLength) { 6063 sb.append("[[TRUNCATED]]"); 6064 break; 6065 } 6066 if (!first) { 6067 sb.append(';'); 6068 } else { 6069 first = false; 6070 } 6071 sb.append(holder.info.authority); 6072 } 6073 } 6074 } 6075 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString()); 6076 } 6077 try { 6078 mCpHelper.publishContentProviders(caller, providers); 6079 } finally { 6080 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 6081 } 6082 } 6083 6084 @Override refContentProvider(IBinder connection, int stable, int unstable)6085 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 6086 return mCpHelper.refContentProvider(connection, stable, unstable); 6087 } 6088 6089 @Override unstableProviderDied(IBinder connection)6090 public void unstableProviderDied(IBinder connection) { 6091 mCpHelper.unstableProviderDied(connection); 6092 } 6093 6094 @Override appNotRespondingViaProvider(IBinder connection)6095 public void appNotRespondingViaProvider(IBinder connection) { 6096 mCpHelper.appNotRespondingViaProvider(connection); 6097 } 6098 6099 /** 6100 * Allows apps to retrieve the MIME type of a URI. 6101 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 6102 * users, then it does not need permission to access the ContentProvider. 6103 * Either, it needs cross-user uri grants. 6104 * 6105 * CTS tests for this functionality can be run with "runtest cts-appsecurity". 6106 * 6107 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/ 6108 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java 6109 * 6110 * @deprecated -- use getProviderMimeTypeAsync. 6111 */ 6112 @Deprecated 6113 @Override getProviderMimeType(Uri uri, int userId)6114 public String getProviderMimeType(Uri uri, int userId) { 6115 return mCpHelper.getProviderMimeType(uri, userId); 6116 } 6117 6118 /** 6119 * Allows apps to retrieve the MIME type of a URI. 6120 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 6121 * users, then it does not need permission to access the ContentProvider. 6122 * Either way, it needs cross-user uri grants. 6123 */ 6124 @Override getProviderMimeTypeAsync(Uri uri, int userId, RemoteCallback resultCallback)6125 public void getProviderMimeTypeAsync(Uri uri, int userId, RemoteCallback resultCallback) { 6126 mCpHelper.getProviderMimeTypeAsync(uri, userId, resultCallback); 6127 } 6128 6129 // ========================================================= 6130 // GLOBAL MANAGEMENT 6131 // ========================================================= 6132 6133 @GuardedBy(anyOf = {"this", "mProcLock"}) uidOnBackgroundAllowlistLOSP(final int uid)6134 private boolean uidOnBackgroundAllowlistLOSP(final int uid) { 6135 final int appId = UserHandle.getAppId(uid); 6136 final int[] allowlist = mBackgroundAppIdAllowlist; 6137 for (int i = 0, len = allowlist.length; i < len; i++) { 6138 if (appId == allowlist[i]) { 6139 return true; 6140 } 6141 } 6142 return false; 6143 } 6144 6145 @Override isBackgroundRestricted(String packageName)6146 public boolean isBackgroundRestricted(String packageName) { 6147 final int callingUid = Binder.getCallingUid(); 6148 final IPackageManager pm = AppGlobals.getPackageManager(); 6149 try { 6150 final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 6151 UserHandle.getUserId(callingUid)); 6152 if (packageUid != callingUid) { 6153 throw new IllegalArgumentException("Uid " + callingUid 6154 + " cannot query restriction state for package " + packageName); 6155 } 6156 } catch (RemoteException exc) { 6157 // Ignore. 6158 } 6159 return isBackgroundRestrictedNoCheck(callingUid, packageName); 6160 } 6161 isBackgroundRestrictedNoCheck(final int uid, final String packageName)6162 boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) { 6163 final int mode = getAppOpsManager().checkOpNoThrow(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, 6164 uid, packageName); 6165 return mode != AppOpsManager.MODE_ALLOWED; 6166 } 6167 6168 @Override backgroundAllowlistUid(final int uid)6169 public void backgroundAllowlistUid(final int uid) { 6170 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 6171 throw new SecurityException("Only the OS may call backgroundAllowlistUid()"); 6172 } 6173 6174 if (DEBUG_BACKGROUND_CHECK) { 6175 Slog.i(TAG, "Adding uid " + uid + " to bg uid allowlist"); 6176 } 6177 synchronized (this) { 6178 synchronized (mProcLock) { 6179 final int num = mBackgroundAppIdAllowlist.length; 6180 int[] newList = new int[num + 1]; 6181 System.arraycopy(mBackgroundAppIdAllowlist, 0, newList, 0, num); 6182 newList[num] = UserHandle.getAppId(uid); 6183 mBackgroundAppIdAllowlist = newList; 6184 } 6185 } 6186 } 6187 6188 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)6189 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 6190 String abiOverride, int zygotePolicyFlags) { 6191 return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */, 6192 abiOverride, zygotePolicyFlags); 6193 } 6194 6195 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags)6196 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 6197 boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags) { 6198 return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks, 6199 false /* disableTestApiChecks */, abiOverride, zygotePolicyFlags); 6200 } 6201 6202 // TODO: Move to ProcessList? 6203 @GuardedBy("this") addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)6204 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 6205 boolean disableHiddenApiChecks, boolean disableTestApiChecks, 6206 String abiOverride, int zygotePolicyFlags) { 6207 ProcessRecord app; 6208 if (!isolated) { 6209 app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName, 6210 info.uid); 6211 } else { 6212 app = null; 6213 } 6214 6215 if (app == null) { 6216 app = mProcessList.newProcessRecordLocked(info, customProcess, isolated, 0, 6217 new HostingRecord("added application", 6218 customProcess != null ? customProcess : info.processName)); 6219 updateLruProcessLocked(app, false, null); 6220 updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN); 6221 } 6222 6223 // Report usage as process is persistent and being started. 6224 mUsageStatsService.reportEvent(info.packageName, UserHandle.getUserId(app.uid), 6225 Event.APP_COMPONENT_USED); 6226 6227 // This package really, really can not be stopped. 6228 try { 6229 AppGlobals.getPackageManager().setPackageStoppedState( 6230 info.packageName, false, UserHandle.getUserId(app.uid)); 6231 } catch (RemoteException e) { 6232 } catch (IllegalArgumentException e) { 6233 Slog.w(TAG, "Failed trying to unstop package " 6234 + info.packageName + ": " + e); 6235 } 6236 6237 if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 6238 app.setPersistent(true); 6239 app.mState.setMaxAdj(ProcessList.PERSISTENT_PROC_ADJ); 6240 } 6241 if (app.getThread() == null && mPersistentStartingProcesses.indexOf(app) < 0) { 6242 mPersistentStartingProcesses.add(app); 6243 mProcessList.startProcessLocked(app, new HostingRecord("added application", 6244 customProcess != null ? customProcess : app.processName), 6245 zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks, 6246 abiOverride); 6247 } 6248 6249 return app; 6250 } 6251 unhandledBack()6252 public void unhandledBack() { 6253 mActivityTaskManager.unhandledBack(); 6254 } 6255 6256 // TODO: Move to ContentProviderHelper? openContentUri(String uriString)6257 public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException { 6258 enforceNotIsolatedCaller("openContentUri"); 6259 final int userId = UserHandle.getCallingUserId(); 6260 final Uri uri = Uri.parse(uriString); 6261 String name = uri.getAuthority(); 6262 ContentProviderHolder cph = mCpHelper.getContentProviderExternalUnchecked(name, null, 6263 Binder.getCallingUid(), "*opencontent*", userId); 6264 ParcelFileDescriptor pfd = null; 6265 if (cph != null) { 6266 try { 6267 // This method is exposed to the VNDK and to avoid changing its 6268 // signature we just use the first package in the UID. For shared 6269 // UIDs we may blame the wrong app but that is Okay as they are 6270 // in the same security/privacy sandbox. 6271 final int uid = Binder.getCallingUid(); 6272 // Here we handle some of the special UIDs (mediaserver, systemserver, etc) 6273 final String packageName = AppOpsManager.resolvePackageName(uid, 6274 /*packageName*/ null); 6275 final AndroidPackage androidPackage; 6276 if (packageName != null) { 6277 androidPackage = mPackageManagerInt.getPackage(packageName); 6278 } else { 6279 androidPackage = mPackageManagerInt.getPackage(uid); 6280 } 6281 if (androidPackage == null) { 6282 Log.e(TAG, "Cannot find package for uid: " + uid); 6283 return null; 6284 } 6285 final AttributionSource attributionSource = new AttributionSource( 6286 Binder.getCallingUid(), androidPackage.getPackageName(), null); 6287 pfd = cph.provider.openFile(attributionSource, uri, "r", null); 6288 } catch (FileNotFoundException e) { 6289 // do nothing; pfd will be returned null 6290 } finally { 6291 // Ensure we're done with the provider. 6292 mCpHelper.removeContentProviderExternalUnchecked(name, null, userId); 6293 } 6294 } else { 6295 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 6296 } 6297 return pfd; 6298 } 6299 reportGlobalUsageEvent(int event)6300 void reportGlobalUsageEvent(int event) { 6301 final int currentUserId = mUserController.getCurrentUserId(); 6302 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, currentUserId, event); 6303 int[] profiles = mUserController.getCurrentProfileIds(); 6304 if (profiles != null) { 6305 for (int i = profiles.length - 1; i >= 0; i--) { 6306 if (profiles[i] == currentUserId) { 6307 continue; 6308 } 6309 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, profiles[i], event); 6310 } 6311 } 6312 } 6313 reportCurWakefulnessUsageEvent()6314 void reportCurWakefulnessUsageEvent() { 6315 reportGlobalUsageEvent(mWakefulness.get() == PowerManagerInternal.WAKEFULNESS_AWAKE 6316 ? UsageEvents.Event.SCREEN_INTERACTIVE 6317 : UsageEvents.Event.SCREEN_NON_INTERACTIVE); 6318 } 6319 onWakefulnessChanged(int wakefulness)6320 void onWakefulnessChanged(int wakefulness) { 6321 synchronized (this) { 6322 boolean wasAwake = mWakefulness.getAndSet(wakefulness) 6323 == PowerManagerInternal.WAKEFULNESS_AWAKE; 6324 boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE; 6325 6326 if (wasAwake != isAwake) { 6327 // Also update state in a special way for running foreground services UI. 6328 mServices.updateScreenStateLocked(isAwake); 6329 reportCurWakefulnessUsageEvent(); 6330 mActivityTaskManager.onScreenAwakeChanged(isAwake); 6331 mOomAdjProfiler.onWakefulnessChanged(wakefulness); 6332 } 6333 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 6334 } 6335 } 6336 6337 @Override notifyCleartextNetwork(int uid, byte[] firstPacket)6338 public void notifyCleartextNetwork(int uid, byte[] firstPacket) { 6339 mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget(); 6340 } 6341 6342 @Override shutdown(int timeout)6343 public boolean shutdown(int timeout) { 6344 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 6345 != PackageManager.PERMISSION_GRANTED) { 6346 throw new SecurityException("Requires permission " 6347 + android.Manifest.permission.SHUTDOWN); 6348 } 6349 6350 final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout); 6351 6352 mAppOpsService.shutdown(); 6353 if (mUsageStatsService != null) { 6354 mUsageStatsService.prepareShutdown(); 6355 } 6356 mBatteryStatsService.shutdown(); 6357 mProcessStats.shutdown(); 6358 6359 return timedout; 6360 } 6361 6362 @Override notifyLockedProfile(@serIdInt int userId)6363 public void notifyLockedProfile(@UserIdInt int userId) { 6364 mAtmInternal.notifyLockedProfile(userId, mUserController.getCurrentUserId()); 6365 } 6366 6367 @Override startConfirmDeviceCredentialIntent(Intent intent, Bundle options)6368 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) { 6369 mAtmInternal.startConfirmDeviceCredentialIntent(intent, options); 6370 } 6371 6372 @Override stopAppSwitches()6373 public void stopAppSwitches() { 6374 mActivityTaskManager.stopAppSwitches(); 6375 } 6376 6377 @Override resumeAppSwitches()6378 public void resumeAppSwitches() { 6379 mActivityTaskManager.resumeAppSwitches(); 6380 } 6381 setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)6382 public void setDebugApp(String packageName, boolean waitForDebugger, 6383 boolean persistent) { 6384 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 6385 "setDebugApp()"); 6386 6387 final long ident = Binder.clearCallingIdentity(); 6388 try { 6389 // Note that this is not really thread safe if there are multiple 6390 // callers into it at the same time, but that's not a situation we 6391 // care about. 6392 if (persistent) { 6393 final ContentResolver resolver = mContext.getContentResolver(); 6394 Settings.Global.putString( 6395 resolver, Settings.Global.DEBUG_APP, 6396 packageName); 6397 Settings.Global.putInt( 6398 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 6399 waitForDebugger ? 1 : 0); 6400 } 6401 6402 synchronized (this) { 6403 if (!persistent) { 6404 mOrigDebugApp = mDebugApp; 6405 mOrigWaitForDebugger = mWaitForDebugger; 6406 } 6407 mDebugApp = packageName; 6408 mWaitForDebugger = waitForDebugger; 6409 mDebugTransient = !persistent; 6410 if (packageName != null) { 6411 forceStopPackageLocked(packageName, -1, false, false, true, true, 6412 false, UserHandle.USER_ALL, "set debug app"); 6413 } 6414 } 6415 } finally { 6416 Binder.restoreCallingIdentity(ident); 6417 } 6418 } 6419 6420 /** 6421 * Set or remove an agent to be run whenever an app with the given process name starts. 6422 * 6423 * This method will not check whether the given process name matches a debuggable app. That 6424 * would require scanning all current packages, and a rescan when new packages are installed 6425 * or updated. 6426 * 6427 * Instead, do the check when an application is started and matched to a stored agent. 6428 * 6429 * @param packageName the process name of the app. 6430 * @param agent the agent string to be used, or null to remove any previously set agent. 6431 */ 6432 @Override setAgentApp(@onNull String packageName, @Nullable String agent)6433 public void setAgentApp(@NonNull String packageName, @Nullable String agent) { 6434 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 6435 // its own permission. 6436 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 6437 != PackageManager.PERMISSION_GRANTED) { 6438 throw new SecurityException( 6439 "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER); 6440 } 6441 6442 synchronized (mAppProfiler.mProfilerLock) { 6443 mAppProfiler.setAgentAppLPf(packageName, agent); 6444 } 6445 } 6446 setTrackAllocationApp(ApplicationInfo app, String processName)6447 void setTrackAllocationApp(ApplicationInfo app, String processName) { 6448 if (!Build.IS_DEBUGGABLE) { 6449 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 6450 throw new SecurityException("Process not debuggable: " + app.packageName); 6451 } 6452 } 6453 6454 synchronized (mProcLock) { 6455 mTrackAllocationApp = processName; 6456 } 6457 } 6458 setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo)6459 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) { 6460 synchronized (mAppProfiler.mProfilerLock) { 6461 if (!Build.IS_DEBUGGABLE) { 6462 boolean isAppDebuggable = (app.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 6463 boolean isAppProfileable = app.isProfileableByShell(); 6464 if (!isAppDebuggable && !isAppProfileable) { 6465 throw new SecurityException("Process not debuggable, " 6466 + "and not profileable by shell: " + app.packageName); 6467 } 6468 } 6469 mAppProfiler.setProfileAppLPf(processName, profilerInfo); 6470 } 6471 } 6472 setNativeDebuggingAppLocked(ApplicationInfo app, String processName)6473 void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) { 6474 if (!Build.IS_DEBUGGABLE) { 6475 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 6476 throw new SecurityException("Process not debuggable: " + app.packageName); 6477 } 6478 } 6479 mNativeDebuggingApp = processName; 6480 } 6481 6482 @Override setAlwaysFinish(boolean enabled)6483 public void setAlwaysFinish(boolean enabled) { 6484 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 6485 "setAlwaysFinish()"); 6486 6487 final long ident = Binder.clearCallingIdentity(); 6488 try { 6489 Settings.Global.putInt( 6490 mContext.getContentResolver(), 6491 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 6492 6493 synchronized (this) { 6494 mAlwaysFinishActivities = enabled; 6495 } 6496 } finally { 6497 Binder.restoreCallingIdentity(ident); 6498 } 6499 } 6500 6501 @Override setActivityController(IActivityController controller, boolean imAMonkey)6502 public void setActivityController(IActivityController controller, boolean imAMonkey) { 6503 if (controller != null) { 6504 Binder.allowBlocking(controller.asBinder()); 6505 } 6506 mActivityTaskManager.setActivityController(controller, imAMonkey); 6507 } 6508 6509 @Override setUserIsMonkey(boolean userIsMonkey)6510 public void setUserIsMonkey(boolean userIsMonkey) { 6511 synchronized (mProcLock) { 6512 synchronized (mPidsSelfLocked) { 6513 final int callingPid = Binder.getCallingPid(); 6514 ProcessRecord proc = mPidsSelfLocked.get(callingPid); 6515 if (proc == null) { 6516 throw new SecurityException("Unknown process: " + callingPid); 6517 } 6518 if (proc.getActiveInstrumentation() == null 6519 || proc.getActiveInstrumentation().mUiAutomationConnection == null) { 6520 throw new SecurityException("Only an instrumentation process " 6521 + "with a UiAutomation can call setUserIsMonkey"); 6522 } 6523 } 6524 mUserIsMonkey = userIsMonkey; 6525 } 6526 } 6527 6528 @Override isUserAMonkey()6529 public boolean isUserAMonkey() { 6530 synchronized (mProcLock) { 6531 // If there is a controller also implies the user is a monkey. 6532 return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey(); 6533 } 6534 } 6535 6536 @Override requestSystemServerHeapDump()6537 public void requestSystemServerHeapDump() { 6538 if (!Build.IS_DEBUGGABLE) { 6539 Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build"); 6540 return; 6541 } 6542 if (Binder.getCallingUid() != SYSTEM_UID) { 6543 // This also intentionally excludes secondary profiles from calling this. 6544 throw new SecurityException( 6545 "Only the system process is allowed to request a system heap dump"); 6546 } 6547 ProcessRecord pr; 6548 synchronized (mPidsSelfLocked) { 6549 pr = mPidsSelfLocked.get(myPid()); 6550 } 6551 if (pr == null) { 6552 Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid()); 6553 return; 6554 } 6555 synchronized (mAppProfiler.mProfilerLock) { 6556 mAppProfiler.startHeapDumpLPf(pr.mProfile, true); 6557 } 6558 } 6559 6560 /** 6561 * Takes a bugreport using bug report API ({@code BugreportManager}) with no pre-set 6562 * title and description 6563 */ 6564 @Override requestBugReport(@ugreportParams.BugreportMode int bugreportType)6565 public void requestBugReport(@BugreportParams.BugreportMode int bugreportType) { 6566 requestBugReportWithDescription(null, null, bugreportType); 6567 } 6568 6569 /** 6570 * Takes a bugreport using bug report API ({@code BugreportManager}) which gets 6571 * triggered by sending a broadcast to Shell. 6572 */ 6573 @Override requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType)6574 public void requestBugReportWithDescription(@Nullable String shareTitle, 6575 @Nullable String shareDescription, int bugreportType) { 6576 String type = null; 6577 switch (bugreportType) { 6578 case BugreportParams.BUGREPORT_MODE_FULL: 6579 type = "bugreportfull"; 6580 break; 6581 case BugreportParams.BUGREPORT_MODE_INTERACTIVE: 6582 type = "bugreportplus"; 6583 break; 6584 case BugreportParams.BUGREPORT_MODE_REMOTE: 6585 type = "bugreportremote"; 6586 break; 6587 case BugreportParams.BUGREPORT_MODE_WEAR: 6588 type = "bugreportwear"; 6589 break; 6590 case BugreportParams.BUGREPORT_MODE_TELEPHONY: 6591 type = "bugreporttelephony"; 6592 break; 6593 case BugreportParams.BUGREPORT_MODE_WIFI: 6594 type = "bugreportwifi"; 6595 break; 6596 default: 6597 throw new IllegalArgumentException( 6598 "Provided bugreport type is not correct, value: " 6599 + bugreportType); 6600 } 6601 // Always log caller, even if it does not have permission to dump. 6602 Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid()); 6603 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 6604 6605 if (!TextUtils.isEmpty(shareTitle)) { 6606 if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) { 6607 String errorStr = "shareTitle should be less than " 6608 + MAX_BUGREPORT_TITLE_SIZE + " characters"; 6609 throw new IllegalArgumentException(errorStr); 6610 } 6611 if (!TextUtils.isEmpty(shareDescription)) { 6612 if (shareDescription.length() > MAX_BUGREPORT_DESCRIPTION_SIZE) { 6613 String errorStr = "shareDescription should be less than " 6614 + MAX_BUGREPORT_DESCRIPTION_SIZE + " characters"; 6615 throw new IllegalArgumentException(errorStr); 6616 } 6617 } 6618 Slog.d(TAG, "Bugreport notification title " + shareTitle 6619 + " description " + shareDescription); 6620 } 6621 // Create intent to trigger Bugreport API via Shell 6622 Intent triggerShellBugreport = new Intent(); 6623 triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED); 6624 triggerShellBugreport.setPackage(SHELL_APP_PACKAGE); 6625 triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType); 6626 triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 6627 triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 6628 if (shareTitle != null) { 6629 triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle); 6630 } 6631 if (shareDescription != null) { 6632 triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription); 6633 } 6634 final long identity = Binder.clearCallingIdentity(); 6635 try { 6636 // Send broadcast to shell to trigger bugreport using Bugreport API 6637 mContext.sendBroadcastAsUser(triggerShellBugreport, UserHandle.SYSTEM); 6638 } finally { 6639 Binder.restoreCallingIdentity(identity); 6640 } 6641 } 6642 6643 /** 6644 * Takes a telephony bugreport with title and description 6645 */ 6646 @Override requestTelephonyBugReport(String shareTitle, String shareDescription)6647 public void requestTelephonyBugReport(String shareTitle, String shareDescription) { 6648 requestBugReportWithDescription(shareTitle, shareDescription, 6649 BugreportParams.BUGREPORT_MODE_TELEPHONY); 6650 } 6651 6652 /** 6653 * Takes a minimal bugreport of Wifi-related state with pre-set title and description 6654 */ 6655 @Override requestWifiBugReport(String shareTitle, String shareDescription)6656 public void requestWifiBugReport(String shareTitle, String shareDescription) { 6657 requestBugReportWithDescription(shareTitle, shareDescription, 6658 BugreportParams.BUGREPORT_MODE_WIFI); 6659 } 6660 6661 /** 6662 * Takes an interactive bugreport with a progress notification 6663 */ 6664 @Override requestInteractiveBugReport()6665 public void requestInteractiveBugReport() { 6666 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE); 6667 } 6668 6669 /** 6670 * Takes an interactive bugreport with a progress notification. Also, shows the given title and 6671 * description on the final share notification 6672 */ 6673 @Override requestInteractiveBugReportWithDescription(String shareTitle, String shareDescription)6674 public void requestInteractiveBugReportWithDescription(String shareTitle, 6675 String shareDescription) { 6676 requestBugReportWithDescription(shareTitle, shareDescription, 6677 BugreportParams.BUGREPORT_MODE_INTERACTIVE); 6678 } 6679 6680 /** 6681 * Takes a bugreport with minimal user interference 6682 */ 6683 @Override requestFullBugReport()6684 public void requestFullBugReport() { 6685 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_FULL); 6686 } 6687 6688 /** 6689 * Takes a bugreport remotely 6690 */ 6691 @Override requestRemoteBugReport()6692 public void requestRemoteBugReport() { 6693 requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE); 6694 } 6695 6696 /** 6697 * Launches a bugreport-whitelisted app to handle a bugreport. 6698 * 6699 * <p>Allows a bug report handler app to take bugreports on the user's behalf. The handler can 6700 * be predefined in the config, meant to be launched with the primary user. The user can 6701 * override this with a different (or same) handler app on possibly a different user. This is 6702 * useful for capturing bug reports from work profile, for instance. 6703 * 6704 * @return true if there is a bugreport-whitelisted app to handle a bugreport, or false 6705 * otherwise. 6706 */ 6707 @Override launchBugReportHandlerApp()6708 public boolean launchBugReportHandlerApp() { 6709 if (!BugReportHandlerUtil.isBugReportHandlerEnabled(mContext)) { 6710 return false; 6711 } 6712 6713 // Always log caller, even if it does not have permission to dump. 6714 Slog.i(TAG, "launchBugReportHandlerApp requested by UID " + Binder.getCallingUid()); 6715 enforceCallingPermission(android.Manifest.permission.DUMP, 6716 "launchBugReportHandlerApp"); 6717 6718 return BugReportHandlerUtil.launchBugReportHandlerApp(mContext); 6719 } 6720 6721 /** 6722 * Get packages of bugreport-whitelisted apps to handle a bug report. 6723 * 6724 * @return packages of bugreport-whitelisted apps to handle a bug report. 6725 */ 6726 @Override getBugreportWhitelistedPackages()6727 public List<String> getBugreportWhitelistedPackages() { 6728 enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING, 6729 "getBugreportWhitelistedPackages"); 6730 return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages()); 6731 } 6732 registerProcessObserver(IProcessObserver observer)6733 public void registerProcessObserver(IProcessObserver observer) { 6734 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 6735 "registerProcessObserver()"); 6736 mProcessList.registerProcessObserver(observer); 6737 } 6738 6739 @Override unregisterProcessObserver(IProcessObserver observer)6740 public void unregisterProcessObserver(IProcessObserver observer) { 6741 mProcessList.unregisterProcessObserver(observer); 6742 } 6743 6744 @Override getUidProcessState(int uid, String callingPackage)6745 public int getUidProcessState(int uid, String callingPackage) { 6746 if (!hasUsageStatsPermission(callingPackage)) { 6747 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 6748 "getUidProcessState"); 6749 } 6750 6751 synchronized (mProcLock) { 6752 return mProcessList.getUidProcStateLOSP(uid); 6753 } 6754 } 6755 6756 @Override getUidProcessCapabilities(int uid, String callingPackage)6757 public @ProcessCapability int getUidProcessCapabilities(int uid, String callingPackage) { 6758 if (!hasUsageStatsPermission(callingPackage)) { 6759 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 6760 "getUidProcessState"); 6761 } 6762 6763 synchronized (mProcLock) { 6764 return mProcessList.getUidProcessCapabilityLOSP(uid); 6765 } 6766 } 6767 6768 @Override registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)6769 public void registerUidObserver(IUidObserver observer, int which, int cutpoint, 6770 String callingPackage) { 6771 if (!hasUsageStatsPermission(callingPackage)) { 6772 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 6773 "registerUidObserver"); 6774 } 6775 mUidObserverController.register(observer, which, cutpoint, callingPackage, 6776 Binder.getCallingUid()); 6777 } 6778 6779 @Override unregisterUidObserver(IUidObserver observer)6780 public void unregisterUidObserver(IUidObserver observer) { 6781 mUidObserverController.unregister(observer); 6782 } 6783 6784 @Override isUidActive(int uid, String callingPackage)6785 public boolean isUidActive(int uid, String callingPackage) { 6786 if (!hasUsageStatsPermission(callingPackage)) { 6787 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 6788 "isUidActive"); 6789 } 6790 synchronized (mProcLock) { 6791 if (isUidActiveLOSP(uid)) { 6792 return true; 6793 } 6794 } 6795 return mInternal.isPendingTopUid(uid); 6796 } 6797 6798 @GuardedBy(anyOf = {"this", "mProcLock"}) isUidActiveLOSP(int uid)6799 boolean isUidActiveLOSP(int uid) { 6800 final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 6801 return uidRecord != null && !uidRecord.isSetIdle(); 6802 } 6803 6804 @Override setPersistentVrThread(int tid)6805 public void setPersistentVrThread(int tid) { 6806 mActivityTaskManager.setPersistentVrThread(tid); 6807 } 6808 6809 /** 6810 * Schedule the given thread a normal scheduling priority. 6811 * 6812 * @param tid the tid of the thread to adjust the scheduling of. 6813 * @param suppressLogs {@code true} if any error logging should be disabled. 6814 * 6815 * @return {@code true} if this succeeded. 6816 */ scheduleAsRegularPriority(int tid, boolean suppressLogs)6817 public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) { 6818 try { 6819 Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0); 6820 return true; 6821 } catch (IllegalArgumentException e) { 6822 if (!suppressLogs) { 6823 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 6824 } 6825 } catch (SecurityException e) { 6826 if (!suppressLogs) { 6827 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 6828 } 6829 } 6830 return false; 6831 } 6832 6833 /** 6834 * Schedule the given thread an FIFO scheduling priority. 6835 * 6836 * @param tid the tid of the thread to adjust the scheduling of. 6837 * @param suppressLogs {@code true} if any error logging should be disabled. 6838 * 6839 * @return {@code true} if this succeeded. 6840 */ scheduleAsFifoPriority(int tid, boolean suppressLogs)6841 public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) { 6842 try { 6843 Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1); 6844 return true; 6845 } catch (IllegalArgumentException e) { 6846 if (!suppressLogs) { 6847 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 6848 } 6849 } catch (SecurityException e) { 6850 if (!suppressLogs) { 6851 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e); 6852 } 6853 } 6854 return false; 6855 } 6856 6857 @Override setRenderThread(int tid)6858 public void setRenderThread(int tid) { 6859 synchronized (mProcLock) { 6860 ProcessRecord proc; 6861 int pid = Binder.getCallingPid(); 6862 if (pid == Process.myPid()) { 6863 demoteSystemServerRenderThread(tid); 6864 return; 6865 } 6866 synchronized (mPidsSelfLocked) { 6867 proc = mPidsSelfLocked.get(pid); 6868 } 6869 if (proc != null && proc.getRenderThreadTid() == 0 && tid > 0) { 6870 // ensure the tid belongs to the process 6871 if (!isThreadInProcess(pid, tid)) { 6872 throw new IllegalArgumentException( 6873 "Render thread does not belong to process"); 6874 } 6875 proc.setRenderThreadTid(tid); 6876 if (DEBUG_OOM_ADJ) { 6877 Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid); 6878 } 6879 // promote to FIFO now 6880 if (proc.mState.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) { 6881 if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band"); 6882 if (mUseFifoUiScheduling) { 6883 setThreadScheduler(proc.getRenderThreadTid(), 6884 SCHED_FIFO | SCHED_RESET_ON_FORK, 1); 6885 } else { 6886 setThreadPriority(proc.getRenderThreadTid(), THREAD_PRIORITY_TOP_APP_BOOST); 6887 } 6888 } 6889 } else { 6890 if (DEBUG_OOM_ADJ) { 6891 Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " 6892 + "PID: " + pid + ", TID: " + tid + " FIFO: " + mUseFifoUiScheduling); 6893 } 6894 } 6895 } 6896 } 6897 6898 /** 6899 * We only use RenderThread in system_server to store task snapshots to the disk, which should 6900 * happen in the background. Thus, demote render thread from system_server to a lower priority. 6901 * 6902 * @param tid the tid of the RenderThread 6903 */ demoteSystemServerRenderThread(int tid)6904 private void demoteSystemServerRenderThread(int tid) { 6905 setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND); 6906 } 6907 6908 @Override isVrModePackageEnabled(ComponentName packageName)6909 public boolean isVrModePackageEnabled(ComponentName packageName) { 6910 mActivityTaskManager.enforceSystemHasVrFeature(); 6911 6912 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); 6913 6914 return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) == 6915 VrManagerInternal.NO_ERROR; 6916 } 6917 isTopActivityImmersive()6918 public boolean isTopActivityImmersive() { 6919 return mActivityTaskManager.isTopActivityImmersive(); 6920 } 6921 6922 @Override isTopOfTask(IBinder token)6923 public boolean isTopOfTask(IBinder token) { 6924 return ActivityClient.getInstance().isTopOfTask(token); 6925 } 6926 6927 @Override setHasTopUi(boolean hasTopUi)6928 public void setHasTopUi(boolean hasTopUi) throws RemoteException { 6929 if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) { 6930 String msg = "Permission Denial: setHasTopUi() from pid=" 6931 + Binder.getCallingPid() 6932 + ", uid=" + Binder.getCallingUid() 6933 + " requires " + permission.INTERNAL_SYSTEM_WINDOW; 6934 Slog.w(TAG, msg); 6935 throw new SecurityException(msg); 6936 } 6937 final int pid = Binder.getCallingPid(); 6938 final long origId = Binder.clearCallingIdentity(); 6939 try { 6940 synchronized (this) { 6941 boolean changed = false; 6942 ProcessRecord pr; 6943 synchronized (mPidsSelfLocked) { 6944 pr = mPidsSelfLocked.get(pid); 6945 if (pr == null) { 6946 Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid); 6947 return; 6948 } 6949 if (pr.mState.hasTopUi() != hasTopUi) { 6950 if (DEBUG_OOM_ADJ) { 6951 Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid); 6952 } 6953 pr.mState.setHasTopUi(hasTopUi); 6954 changed = true; 6955 } 6956 } 6957 if (changed) { 6958 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 6959 } 6960 } 6961 } finally { 6962 Binder.restoreCallingIdentity(origId); 6963 } 6964 } 6965 enterSafeMode()6966 public final void enterSafeMode() { 6967 synchronized(this) { 6968 // It only makes sense to do this before the system is ready 6969 // and started launching other packages. 6970 if (!mSystemReady) { 6971 try { 6972 AppGlobals.getPackageManager().enterSafeMode(); 6973 } catch (RemoteException e) { 6974 } 6975 } 6976 6977 mSafeMode = true; 6978 } 6979 } 6980 showSafeModeOverlay()6981 public final void showSafeModeOverlay() { 6982 View v = LayoutInflater.from(mContext).inflate( 6983 com.android.internal.R.layout.safe_mode, null); 6984 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 6985 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 6986 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 6987 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 6988 lp.gravity = Gravity.BOTTOM | Gravity.START; 6989 lp.format = v.getBackground().getOpacity(); 6990 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 6991 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 6992 lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS; 6993 ((WindowManager)mContext.getSystemService( 6994 Context.WINDOW_SERVICE)).addView(v, lp); 6995 } 6996 6997 @Override noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)6998 public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, 6999 String sourcePkg, String tag) { 7000 if (workSource != null && workSource.isEmpty()) { 7001 workSource = null; 7002 } 7003 7004 if (sourceUid <= 0 && workSource == null) { 7005 // Try and derive a UID to attribute things to based on the caller. 7006 if (sender != null) { 7007 if (!(sender instanceof PendingIntentRecord)) { 7008 return; 7009 } 7010 7011 final PendingIntentRecord rec = (PendingIntentRecord) sender; 7012 final int callerUid = Binder.getCallingUid(); 7013 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 7014 } else { 7015 // TODO(narayan): Should we throw an exception in this case ? It means that we 7016 // haven't been able to derive a UID to attribute things to. 7017 return; 7018 } 7019 } 7020 7021 int standbyBucket = 0; 7022 7023 mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag); 7024 if (workSource != null) { 7025 String workSourcePackage = workSource.getPackageName(0); 7026 int workSourceUid = workSource.getAttributionUid(); 7027 if (workSourcePackage == null) { 7028 workSourcePackage = sourcePkg; 7029 workSourceUid = sourceUid; 7030 } 7031 7032 if (mUsageStatsService != null) { 7033 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage, 7034 UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime()); 7035 } 7036 7037 FrameworkStatsLog.write(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag, 7038 sourcePkg, standbyBucket); 7039 if (DEBUG_POWER) { 7040 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 7041 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 7042 + standbyBucket + " wsName=" + workSourcePackage + ")]"); 7043 } 7044 } else { 7045 if (mUsageStatsService != null) { 7046 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg, 7047 UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime()); 7048 } 7049 FrameworkStatsLog.write_non_chained(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, sourceUid, 7050 null, tag, sourcePkg, standbyBucket); 7051 if (DEBUG_POWER) { 7052 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid 7053 + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket=" 7054 + standbyBucket + "]"); 7055 } 7056 } 7057 7058 } 7059 7060 @Override noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)7061 public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, 7062 String tag) { 7063 if (workSource != null && workSource.isEmpty()) { 7064 workSource = null; 7065 } 7066 7067 if (sourceUid <= 0 && workSource == null) { 7068 // Try and derive a UID to attribute things to based on the caller. 7069 if (sender != null) { 7070 if (!(sender instanceof PendingIntentRecord)) { 7071 return; 7072 } 7073 7074 final PendingIntentRecord rec = (PendingIntentRecord) sender; 7075 final int callerUid = Binder.getCallingUid(); 7076 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 7077 } else { 7078 // TODO(narayan): Should we throw an exception in this case ? It means that we 7079 // haven't been able to derive a UID to attribute things to. 7080 return; 7081 } 7082 } 7083 7084 if (DEBUG_POWER) { 7085 Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource + 7086 ", tag=" + tag + "]"); 7087 } 7088 7089 mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid); 7090 } 7091 7092 @Override noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)7093 public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, 7094 String tag) { 7095 if (workSource != null && workSource.isEmpty()) { 7096 workSource = null; 7097 } 7098 7099 if (sourceUid <= 0 && workSource == null) { 7100 // Try and derive a UID to attribute things to based on the caller. 7101 if (sender != null) { 7102 if (!(sender instanceof PendingIntentRecord)) { 7103 return; 7104 } 7105 7106 final PendingIntentRecord rec = (PendingIntentRecord) sender; 7107 final int callerUid = Binder.getCallingUid(); 7108 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid; 7109 } else { 7110 // TODO(narayan): Should we throw an exception in this case ? It means that we 7111 // haven't been able to derive a UID to attribute things to. 7112 return; 7113 } 7114 } 7115 7116 if (DEBUG_POWER) { 7117 Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource + 7118 ", tag=" + tag + "]"); 7119 } 7120 7121 mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid); 7122 } 7123 killPids(int[] pids, String pReason, boolean secure)7124 public boolean killPids(int[] pids, String pReason, boolean secure) { 7125 if (Binder.getCallingUid() != SYSTEM_UID) { 7126 throw new SecurityException("killPids only available to the system"); 7127 } 7128 final String reason = (pReason == null) ? "Unknown" : pReason; 7129 // XXX Note: don't acquire main activity lock here, because the window 7130 // manager calls in with its locks held. 7131 7132 boolean killed = false; 7133 final ArrayList<ProcessRecord> killCandidates = new ArrayList<>(); 7134 synchronized (mPidsSelfLocked) { 7135 int worstType = 0; 7136 for (int i = 0; i < pids.length; i++) { 7137 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 7138 if (proc != null) { 7139 int type = proc.mState.getSetAdj(); 7140 if (type > worstType) { 7141 worstType = type; 7142 } 7143 } 7144 } 7145 7146 // If the worst oom_adj is somewhere in the cached proc LRU range, 7147 // then constrain it so we will kill all cached procs. 7148 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 7149 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 7150 worstType = ProcessList.CACHED_APP_MIN_ADJ; 7151 } 7152 7153 // If this is not a secure call, don't let it kill processes that 7154 // are important. 7155 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 7156 worstType = ProcessList.SERVICE_ADJ; 7157 } 7158 7159 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 7160 for (int i = 0; i < pids.length; i++) { 7161 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 7162 if (proc == null) { 7163 continue; 7164 } 7165 int adj = proc.mState.getSetAdj(); 7166 if (adj >= worstType && !proc.isKilledByAm()) { 7167 killCandidates.add(proc); 7168 killed = true; 7169 } 7170 } 7171 } 7172 if (!killCandidates.isEmpty()) { 7173 mHandler.post(() -> { 7174 synchronized (ActivityManagerService.this) { 7175 for (int i = 0, size = killCandidates.size(); i < size; i++) { 7176 killCandidates.get(i).killLocked(reason, 7177 ApplicationExitInfo.REASON_OTHER, 7178 ApplicationExitInfo.SUBREASON_KILL_PID, true); 7179 } 7180 } 7181 }); 7182 } 7183 return killed; 7184 } 7185 7186 @Override killUid(int appId, int userId, String reason)7187 public void killUid(int appId, int userId, String reason) { 7188 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 7189 synchronized (this) { 7190 final long identity = Binder.clearCallingIdentity(); 7191 try { 7192 synchronized (mProcLock) { 7193 mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId, 7194 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 7195 true /* callerWillRestart */, true /* doit */, 7196 true /* evenPersistent */, false /* setRemoved */, 7197 ApplicationExitInfo.REASON_OTHER, 7198 ApplicationExitInfo.SUBREASON_KILL_UID, 7199 reason != null ? reason : "kill uid"); 7200 } 7201 } finally { 7202 Binder.restoreCallingIdentity(identity); 7203 } 7204 } 7205 } 7206 7207 @Override killUidForPermissionChange(int appId, int userId, String reason)7208 public void killUidForPermissionChange(int appId, int userId, String reason) { 7209 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 7210 synchronized (this) { 7211 final long identity = Binder.clearCallingIdentity(); 7212 try { 7213 synchronized (mProcLock) { 7214 mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId, 7215 ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */, 7216 true /* callerWillRestart */, true /* doit */, 7217 true /* evenPersistent */, false /* setRemoved */, 7218 ApplicationExitInfo.REASON_PERMISSION_CHANGE, 7219 ApplicationExitInfo.SUBREASON_UNKNOWN, 7220 reason != null ? reason : "kill uid"); 7221 } 7222 } finally { 7223 Binder.restoreCallingIdentity(identity); 7224 } 7225 } 7226 } 7227 7228 @Override killProcessesBelowForeground(String reason)7229 public boolean killProcessesBelowForeground(String reason) { 7230 if (Binder.getCallingUid() != SYSTEM_UID) { 7231 throw new SecurityException("killProcessesBelowForeground() only available to system"); 7232 } 7233 7234 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 7235 } 7236 killProcessesBelowAdj(int belowAdj, String reason)7237 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 7238 if (Binder.getCallingUid() != SYSTEM_UID) { 7239 throw new SecurityException("killProcessesBelowAdj() only available to system"); 7240 } 7241 7242 boolean killed = false; 7243 synchronized (this) { 7244 synchronized (mProcLock) { 7245 synchronized (mPidsSelfLocked) { 7246 final int size = mPidsSelfLocked.size(); 7247 for (int i = 0; i < size; i++) { 7248 final int pid = mPidsSelfLocked.keyAt(i); 7249 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 7250 if (proc == null) continue; 7251 7252 final int adj = proc.mState.getSetAdj(); 7253 if (adj > belowAdj && !proc.isKilledByAm()) { 7254 proc.killLocked(reason, ApplicationExitInfo.REASON_PERMISSION_CHANGE, 7255 true); 7256 killed = true; 7257 } 7258 } 7259 } 7260 } 7261 } 7262 return killed; 7263 } 7264 7265 /** 7266 * Similar to {@link #killPids} but killing will be delayed until the device is idle 7267 * and the given process is imperceptible. 7268 */ 7269 @Override killProcessesWhenImperceptible(int[] pids, String reason)7270 public void killProcessesWhenImperceptible(int[] pids, String reason) { 7271 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 7272 != PackageManager.PERMISSION_GRANTED) { 7273 throw new SecurityException("Requires permission " 7274 + android.Manifest.permission.FORCE_STOP_PACKAGES); 7275 } 7276 int callerUid = Binder.getCallingUid(); 7277 final long iden = Binder.clearCallingIdentity(); 7278 try { 7279 mProcessList.killProcessesWhenImperceptible(pids, reason, callerUid); 7280 } finally { 7281 Binder.restoreCallingIdentity(iden); 7282 } 7283 } 7284 7285 @Override hang(final IBinder who, boolean allowRestart)7286 public void hang(final IBinder who, boolean allowRestart) { 7287 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7288 != PackageManager.PERMISSION_GRANTED) { 7289 throw new SecurityException("Requires permission " 7290 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7291 } 7292 7293 final IBinder.DeathRecipient death = new DeathRecipient() { 7294 @Override 7295 public void binderDied() { 7296 synchronized (this) { 7297 notifyAll(); 7298 } 7299 } 7300 }; 7301 7302 try { 7303 who.linkToDeath(death, 0); 7304 } catch (RemoteException e) { 7305 Slog.w(TAG, "hang: given caller IBinder is already dead."); 7306 return; 7307 } 7308 7309 synchronized (this) { 7310 Watchdog.getInstance().setAllowRestart(allowRestart); 7311 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 7312 synchronized (death) { 7313 while (who.isBinderAlive()) { 7314 try { 7315 death.wait(); 7316 } catch (InterruptedException e) { 7317 } 7318 } 7319 } 7320 Watchdog.getInstance().setAllowRestart(true); 7321 } 7322 } 7323 7324 @Override restart()7325 public void restart() { 7326 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7327 != PackageManager.PERMISSION_GRANTED) { 7328 throw new SecurityException("Requires permission " 7329 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7330 } 7331 7332 Log.i(TAG, "Sending shutdown broadcast..."); 7333 7334 BroadcastReceiver br = new BroadcastReceiver() { 7335 @Override public void onReceive(Context context, Intent intent) { 7336 // Now the broadcast is done, finish up the low-level shutdown. 7337 Log.i(TAG, "Shutting down activity manager..."); 7338 shutdown(10000); 7339 Log.i(TAG, "Shutdown complete, restarting!"); 7340 killProcess(myPid()); 7341 System.exit(10); 7342 } 7343 }; 7344 7345 // First send the high-level shut down broadcast. 7346 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 7347 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 7348 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 7349 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 7350 mContext.sendOrderedBroadcastAsUser(intent, 7351 UserHandle.ALL, null, br, mHandler, 0, null, null); 7352 */ 7353 br.onReceive(mContext, intent); 7354 } 7355 7356 @Override performIdleMaintenance()7357 public void performIdleMaintenance() { 7358 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7359 != PackageManager.PERMISSION_GRANTED) { 7360 throw new SecurityException("Requires permission " 7361 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7362 } 7363 7364 synchronized (mProcLock) { 7365 final long now = SystemClock.uptimeMillis(); 7366 final long timeSinceLastIdle = now - mLastIdleTime; 7367 7368 // Compact all non-zygote processes to freshen up the page cache. 7369 mOomAdjuster.mCachedAppOptimizer.compactAllSystem(); 7370 7371 final long lowRamSinceLastIdle = mAppProfiler.getLowRamTimeSinceIdleLPr(now); 7372 mLastIdleTime = now; 7373 mAppProfiler.updateLowRamTimestampLPr(now); 7374 7375 StringBuilder sb = new StringBuilder(128); 7376 sb.append("Idle maintenance over "); 7377 TimeUtils.formatDuration(timeSinceLastIdle, sb); 7378 sb.append(" low RAM for "); 7379 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 7380 Slog.i(TAG, sb.toString()); 7381 7382 // If at least 1/3 of our time since the last idle period has been spent 7383 // with RAM low, then we want to kill processes. 7384 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 7385 // If the processes' memory has increased by more than 1% of the total memory, 7386 // or 10 MB, whichever is greater, then the processes' are eligible to be killed. 7387 final long totalMemoryInKb = getTotalMemory() / 1000; 7388 final long memoryGrowthThreshold = 7389 Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD); 7390 mProcessList.forEachLruProcessesLOSP(false, proc -> { 7391 if (proc.getThread() == null) { 7392 return; 7393 } 7394 final ProcessProfileRecord pr = proc.mProfile; 7395 final ProcessStateRecord state = proc.mState; 7396 final int setProcState = state.getSetProcState(); 7397 if (state.isNotCachedSinceIdle()) { 7398 if (setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE 7399 && setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 7400 final long initialIdlePss, lastPss, lastSwapPss; 7401 synchronized (mAppProfiler.mProfilerLock) { 7402 initialIdlePss = pr.getInitialIdlePss(); 7403 lastPss = pr.getLastPss(); 7404 lastSwapPss = pr.getLastSwapPss(); 7405 } 7406 if (doKilling && initialIdlePss != 0 7407 && lastPss > (initialIdlePss * 3 / 2) 7408 && lastPss > (initialIdlePss + memoryGrowthThreshold)) { 7409 final StringBuilder sb2 = new StringBuilder(128); 7410 sb2.append("Kill"); 7411 sb2.append(proc.processName); 7412 sb2.append(" in idle maint: pss="); 7413 sb2.append(lastPss); 7414 sb2.append(", swapPss="); 7415 sb2.append(lastSwapPss); 7416 sb2.append(", initialPss="); 7417 sb2.append(initialIdlePss); 7418 sb2.append(", period="); 7419 TimeUtils.formatDuration(timeSinceLastIdle, sb2); 7420 sb2.append(", lowRamPeriod="); 7421 TimeUtils.formatDuration(lowRamSinceLastIdle, sb2); 7422 Slog.wtfQuiet(TAG, sb2.toString()); 7423 mHandler.post(() -> { 7424 synchronized (ActivityManagerService.this) { 7425 proc.killLocked("idle maint (pss " + lastPss 7426 + " from " + initialIdlePss + ")", 7427 ApplicationExitInfo.REASON_OTHER, 7428 ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE, 7429 true); 7430 } 7431 }); 7432 } 7433 } 7434 } else if (setProcState < ActivityManager.PROCESS_STATE_HOME 7435 && setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) { 7436 state.setNotCachedSinceIdle(true); 7437 synchronized (mAppProfiler.mProfilerLock) { 7438 pr.setInitialIdlePss(0); 7439 mAppProfiler.updateNextPssTimeLPf( 7440 state.getSetProcState(), proc.mProfile, now, true); 7441 } 7442 } 7443 }); 7444 } 7445 } 7446 7447 @Override sendIdleJobTrigger()7448 public void sendIdleJobTrigger() { 7449 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 7450 != PackageManager.PERMISSION_GRANTED) { 7451 throw new SecurityException("Requires permission " 7452 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7453 } 7454 7455 final long ident = Binder.clearCallingIdentity(); 7456 try { 7457 Intent intent = new Intent(ACTION_TRIGGER_IDLE) 7458 .setPackage("android") 7459 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 7460 broadcastIntent(null, intent, null, null, 0, null, null, null, 7461 OP_NONE, null, false, false, UserHandle.USER_ALL); 7462 } finally { 7463 Binder.restoreCallingIdentity(ident); 7464 } 7465 } 7466 retrieveSettings()7467 private void retrieveSettings() { 7468 final ContentResolver resolver = mContext.getContentResolver(); 7469 mActivityTaskManager.retrieveSettings(resolver); 7470 7471 final String debugApp = Settings.Global.getString(resolver, DEBUG_APP); 7472 final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0; 7473 final boolean alwaysFinishActivities = 7474 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0; 7475 final long waitForNetworkTimeoutMs = Settings.Global.getLong(resolver, 7476 NETWORK_ACCESS_TIMEOUT_MS, NETWORK_ACCESS_TIMEOUT_DEFAULT_MS); 7477 mHiddenApiBlacklist.registerObserver(); 7478 mPlatformCompat.registerContentObserver(); 7479 7480 mAppProfiler.retrieveSettings(); 7481 7482 final Resources res; 7483 synchronized (this) { 7484 mDebugApp = mOrigDebugApp = debugApp; 7485 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 7486 mAlwaysFinishActivities = alwaysFinishActivities; 7487 // Load resources only after the current configuration has been set. 7488 res = mContext.getResources(); 7489 final boolean userSwitchUiEnabled = !res.getBoolean( 7490 com.android.internal.R.bool.config_customUserSwitchUi); 7491 final int maxRunningUsers = res.getInteger( 7492 com.android.internal.R.integer.config_multiuserMaxRunningUsers); 7493 final boolean delayUserDataLocking = res.getBoolean( 7494 com.android.internal.R.bool.config_multiuserDelayUserDataLocking); 7495 mUserController.setInitialConfig(userSwitchUiEnabled, maxRunningUsers, 7496 delayUserDataLocking); 7497 mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs; 7498 } 7499 mAppErrors.loadAppsNotReportingCrashesFromConfig(res.getString( 7500 com.android.internal.R.string.config_appsNotReportingCrashes)); 7501 } 7502 7503 /** 7504 * Ready. Set. Go! 7505 */ systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t)7506 public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) { 7507 t.traceBegin("PhaseActivityManagerReady"); 7508 mSystemServiceManager.preSystemReady(); 7509 synchronized(this) { 7510 if (mSystemReady) { 7511 // If we're done calling all the receivers, run the next "boot phase" passed in 7512 // by the SystemServer 7513 if (goingCallback != null) { 7514 goingCallback.run(); 7515 } 7516 t.traceEnd(); // PhaseActivityManagerReady 7517 return; 7518 } 7519 7520 t.traceBegin("controllersReady"); 7521 mLocalDeviceIdleController = 7522 LocalServices.getService(DeviceIdleInternal.class); 7523 mActivityTaskManager.onSystemReady(); 7524 // Make sure we have the current profile info, since it is needed for security checks. 7525 mUserController.onSystemReady(); 7526 mAppOpsService.systemReady(); 7527 mProcessList.onSystemReady(); 7528 mSystemReady = true; 7529 t.traceEnd(); 7530 } 7531 7532 try { 7533 sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface( 7534 ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE)) 7535 .getSerial(); 7536 } catch (RemoteException e) {} 7537 7538 t.traceBegin("killProcesses"); 7539 ArrayList<ProcessRecord> procsToKill = null; 7540 synchronized(mPidsSelfLocked) { 7541 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 7542 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 7543 if (!isAllowedWhileBooting(proc.info)){ 7544 if (procsToKill == null) { 7545 procsToKill = new ArrayList<ProcessRecord>(); 7546 } 7547 procsToKill.add(proc); 7548 } 7549 } 7550 } 7551 7552 synchronized(this) { 7553 if (procsToKill != null) { 7554 for (int i = procsToKill.size() - 1; i >= 0; i--) { 7555 ProcessRecord proc = procsToKill.get(i); 7556 Slog.i(TAG, "Removing system update proc: " + proc); 7557 mProcessList.removeProcessLocked(proc, true, false, 7558 ApplicationExitInfo.REASON_OTHER, 7559 ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE, 7560 "system update done"); 7561 } 7562 } 7563 7564 // Now that we have cleaned up any update processes, we 7565 // are ready to start launching real processes and know that 7566 // we won't trample on them any more. 7567 mProcessesReady = true; 7568 } 7569 t.traceEnd(); // KillProcesses 7570 7571 Slog.i(TAG, "System now ready"); 7572 7573 EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis()); 7574 7575 t.traceBegin("updateTopComponentForFactoryTest"); 7576 mAtmInternal.updateTopComponentForFactoryTest(); 7577 t.traceEnd(); 7578 7579 t.traceBegin("registerActivityLaunchObserver"); 7580 mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver); 7581 t.traceEnd(); 7582 7583 t.traceBegin("watchDeviceProvisioning"); 7584 watchDeviceProvisioning(mContext); 7585 t.traceEnd(); 7586 7587 t.traceBegin("retrieveSettings"); 7588 retrieveSettings(); 7589 t.traceEnd(); 7590 7591 t.traceBegin("Ugm.onSystemReady"); 7592 mUgmInternal.onSystemReady(); 7593 t.traceEnd(); 7594 7595 t.traceBegin("updateForceBackgroundCheck"); 7596 final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class); 7597 if (pmi != null) { 7598 pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK, 7599 state -> updateForceBackgroundCheck(state.batterySaverEnabled)); 7600 updateForceBackgroundCheck( 7601 pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled); 7602 } else { 7603 Slog.wtf(TAG, "PowerManagerInternal not found."); 7604 } 7605 t.traceEnd(); 7606 7607 if (goingCallback != null) goingCallback.run(); 7608 7609 t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks 7610 // Check the current user here as a user can be started inside goingCallback.run() from 7611 // other system services. 7612 final int currentUserId = mUserController.getCurrentUserId(); 7613 Slog.i(TAG, "Current user:" + currentUserId); 7614 if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) { 7615 // User other than system user has started. Make sure that system user is already 7616 // started before switching user. 7617 throw new RuntimeException("System user not started while current user is:" 7618 + currentUserId); 7619 } 7620 t.traceEnd(); 7621 7622 t.traceBegin("ActivityManagerStartApps"); 7623 mBatteryStatsService.onSystemReady(); 7624 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 7625 Integer.toString(currentUserId), currentUserId); 7626 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 7627 Integer.toString(currentUserId), currentUserId); 7628 7629 // On Automotive, at this point the system user has already been started and unlocked, 7630 // and some of the tasks we do here have already been done. So skip those in that case. 7631 // TODO(b/132262830): this workdound shouldn't be necessary once we move the 7632 // headless-user start logic to UserManager-land 7633 final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM; 7634 7635 if (bootingSystemUser) { 7636 mSystemServiceManager.onUserStarting(t, currentUserId); 7637 } 7638 7639 synchronized (this) { 7640 // Only start up encryption-aware persistent apps; once user is 7641 // unlocked we'll come back around and start unaware apps 7642 t.traceBegin("startPersistentApps"); 7643 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE); 7644 t.traceEnd(); 7645 7646 // Start up initial activity. 7647 mBooting = true; 7648 // Enable home activity for system user, so that the system can always boot. We don't 7649 // do this when the system user is not setup since the setup wizard should be the one 7650 // to handle home activity in this case. 7651 if (UserManager.isSplitSystemUser() && 7652 Settings.Secure.getInt(mContext.getContentResolver(), 7653 Settings.Secure.USER_SETUP_COMPLETE, 0) != 0 7654 || SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) { 7655 t.traceBegin("enableHomeActivity"); 7656 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class); 7657 try { 7658 AppGlobals.getPackageManager().setComponentEnabledSetting(cName, 7659 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0, 7660 UserHandle.USER_SYSTEM); 7661 } catch (RemoteException e) { 7662 throw e.rethrowAsRuntimeException(); 7663 } 7664 t.traceEnd(); 7665 } 7666 7667 if (bootingSystemUser) { 7668 t.traceBegin("startHomeOnAllDisplays"); 7669 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady"); 7670 t.traceEnd(); 7671 } 7672 7673 t.traceBegin("showSystemReadyErrorDialogs"); 7674 mAtmInternal.showSystemReadyErrorDialogsIfNeeded(); 7675 t.traceEnd(); 7676 7677 7678 if (bootingSystemUser) { 7679 t.traceBegin("sendUserStartBroadcast"); 7680 final int callingUid = Binder.getCallingUid(); 7681 final int callingPid = Binder.getCallingPid(); 7682 final long ident = Binder.clearCallingIdentity(); 7683 try { 7684 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 7685 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 7686 | Intent.FLAG_RECEIVER_FOREGROUND); 7687 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); 7688 broadcastIntentLocked(null, null, null, intent, 7689 null, null, 0, null, null, null, null, OP_NONE, 7690 null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid, 7691 currentUserId); 7692 intent = new Intent(Intent.ACTION_USER_STARTING); 7693 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 7694 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); 7695 broadcastIntentLocked(null, null, null, intent, null, 7696 new IIntentReceiver.Stub() { 7697 @Override 7698 public void performReceive(Intent intent, int resultCode, 7699 String data, Bundle extras, boolean ordered, boolean sticky, 7700 int sendingUser) {} 7701 }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, null, OP_NONE, 7702 null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid, 7703 UserHandle.USER_ALL); 7704 } catch (Throwable e) { 7705 Slog.wtf(TAG, "Failed sending first user broadcasts", e); 7706 } finally { 7707 Binder.restoreCallingIdentity(ident); 7708 } 7709 t.traceEnd(); 7710 } else { 7711 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user " 7712 + currentUserId); 7713 } 7714 7715 t.traceBegin("resumeTopActivities"); 7716 mAtmInternal.resumeTopActivities(false /* scheduleIdle */); 7717 t.traceEnd(); 7718 7719 if (bootingSystemUser) { 7720 t.traceBegin("sendUserSwitchBroadcasts"); 7721 mUserController.sendUserSwitchBroadcasts(-1, currentUserId); 7722 t.traceEnd(); 7723 } 7724 7725 t.traceBegin("setBinderProxies"); 7726 BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK, 7727 BINDER_PROXY_LOW_WATERMARK); 7728 BinderInternal.nSetBinderProxyCountEnabled(true); 7729 BinderInternal.setBinderProxyCountCallback( 7730 (uid) -> { 7731 Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid " 7732 + Process.myUid()); 7733 BinderProxy.dumpProxyDebugInfo(); 7734 if (uid == Process.SYSTEM_UID) { 7735 Slog.i(TAG, "Skipping kill (uid is SYSTEM)"); 7736 } else { 7737 killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid), 7738 "Too many Binders sent to SYSTEM"); 7739 } 7740 }, mHandler); 7741 t.traceEnd(); // setBinderProxies 7742 7743 t.traceEnd(); // ActivityManagerStartApps 7744 t.traceEnd(); // PhaseActivityManagerReady 7745 } 7746 } 7747 watchDeviceProvisioning(Context context)7748 private void watchDeviceProvisioning(Context context) { 7749 // setting system property based on whether device is provisioned 7750 7751 if (isDeviceProvisioned(context)) { 7752 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 7753 } else { 7754 // watch for device provisioning change 7755 context.getContentResolver().registerContentObserver( 7756 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false, 7757 new ContentObserver(new Handler(Looper.getMainLooper())) { 7758 @Override 7759 public void onChange(boolean selfChange) { 7760 if (isDeviceProvisioned(context)) { 7761 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1"); 7762 context.getContentResolver().unregisterContentObserver(this); 7763 } 7764 } 7765 }); 7766 } 7767 } 7768 isDeviceProvisioned(Context context)7769 private boolean isDeviceProvisioned(Context context) { 7770 return Settings.Global.getInt(context.getContentResolver(), 7771 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 7772 } 7773 startBroadcastObservers()7774 private void startBroadcastObservers() { 7775 for (BroadcastQueue queue : mBroadcastQueues) { 7776 queue.start(mContext.getContentResolver()); 7777 } 7778 } 7779 updateForceBackgroundCheck(boolean enabled)7780 private void updateForceBackgroundCheck(boolean enabled) { 7781 synchronized (this) { 7782 synchronized (mProcLock) { 7783 if (mForceBackgroundCheck != enabled) { 7784 mForceBackgroundCheck = enabled; 7785 7786 if (DEBUG_BACKGROUND_CHECK) { 7787 Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled")); 7788 } 7789 7790 if (mForceBackgroundCheck) { 7791 // Stop background services for idle UIDs. 7792 mProcessList.doStopUidForIdleUidsLocked(); 7793 } 7794 } 7795 } 7796 } 7797 } 7798 killAppAtUsersRequest(ProcessRecord app)7799 void killAppAtUsersRequest(ProcessRecord app) { 7800 synchronized (this) { 7801 mAppErrors.killAppAtUserRequestLocked(app); 7802 } 7803 } 7804 skipCurrentReceiverLocked(ProcessRecord app)7805 void skipCurrentReceiverLocked(ProcessRecord app) { 7806 for (BroadcastQueue queue : mBroadcastQueues) { 7807 queue.skipCurrentReceiverLocked(app); 7808 } 7809 } 7810 7811 /** 7812 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 7813 * The application process will exit immediately after this call returns. 7814 * @param app object of the crashing app, null for the system server 7815 * @param crashInfo describing the exception 7816 */ handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)7817 public void handleApplicationCrash(IBinder app, 7818 ApplicationErrorReport.ParcelableCrashInfo crashInfo) { 7819 ProcessRecord r = findAppProcess(app, "Crash"); 7820 final String processName = app == null ? "system_server" 7821 : (r == null ? "unknown" : r.processName); 7822 7823 handleApplicationCrashInner("crash", r, processName, crashInfo); 7824 } 7825 7826 /* Native crash reporting uses this inner version because it needs to be somewhat 7827 * decoupled from the AM-managed cleanup lifecycle 7828 */ handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)7829 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 7830 ApplicationErrorReport.CrashInfo crashInfo) { 7831 float loadingProgress = 1; 7832 IncrementalMetrics incrementalMetrics = null; 7833 // Obtain Incremental information if available 7834 if (r != null && r.info != null && r.info.packageName != null) { 7835 IncrementalStatesInfo incrementalStatesInfo = 7836 mPackageManagerInt.getIncrementalStatesInfo(r.info.packageName, r.uid, 7837 r.userId); 7838 if (incrementalStatesInfo != null) { 7839 loadingProgress = incrementalStatesInfo.getProgress(); 7840 } 7841 final String codePath = r.info.getCodePath(); 7842 if (codePath != null && !codePath.isEmpty() 7843 && IncrementalManager.isIncrementalPath(codePath)) { 7844 // Report in the main log about the incremental package 7845 Slog.e(TAG, "App crashed on incremental package " + r.info.packageName 7846 + " which is " + ((int) (loadingProgress * 100)) + "% loaded."); 7847 final IBinder incrementalService = ServiceManager.getService( 7848 Context.INCREMENTAL_SERVICE); 7849 if (incrementalService != null) { 7850 final IncrementalManager incrementalManager = new IncrementalManager( 7851 IIncrementalService.Stub.asInterface(incrementalService)); 7852 incrementalMetrics = incrementalManager.getMetrics(codePath); 7853 } 7854 } 7855 } 7856 7857 EventLogTags.writeAmCrash(Binder.getCallingPid(), 7858 UserHandle.getUserId(Binder.getCallingUid()), processName, 7859 r == null ? -1 : r.info.flags, 7860 crashInfo.exceptionClassName, 7861 crashInfo.exceptionMessage, 7862 crashInfo.throwFileName, 7863 crashInfo.throwLineNumber); 7864 7865 FrameworkStatsLog.write(FrameworkStatsLog.APP_CRASH_OCCURRED, 7866 (r != null) ? r.uid : -1, 7867 eventType, 7868 processName, 7869 (r != null) ? r.getPid() : -1, 7870 (r != null && r.info != null) ? r.info.packageName : "", 7871 (r != null && r.info != null) ? (r.info.isInstantApp() 7872 ? FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE 7873 : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE) 7874 : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE, 7875 r != null ? (r.isInterestingToUserLocked() 7876 ? FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND 7877 : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND) 7878 : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN, 7879 processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER 7880 : (r != null) ? r.getProcessClassEnum() 7881 : ServerProtoEnums.ERROR_SOURCE_UNKNOWN, 7882 incrementalMetrics != null /* isIncremental */, loadingProgress, 7883 incrementalMetrics != null ? incrementalMetrics.getMillisSinceOldestPendingRead() 7884 : -1, 7885 incrementalMetrics != null ? incrementalMetrics.getStorageHealthStatusCode() 7886 : -1, 7887 incrementalMetrics != null ? incrementalMetrics.getDataLoaderStatusCode() 7888 : -1, 7889 incrementalMetrics != null && incrementalMetrics.getReadLogsEnabled(), 7890 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastDataLoaderBind() 7891 : -1, 7892 incrementalMetrics != null ? incrementalMetrics.getDataLoaderBindDelayMillis() 7893 : -1, 7894 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReads() 7895 : -1, 7896 incrementalMetrics != null ? incrementalMetrics.getTotalFailedReads() 7897 : -1, 7898 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorUid() 7899 : -1, 7900 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastReadError() 7901 : -1, 7902 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorNumber() 7903 : 0, 7904 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReadsDurationMillis() 7905 : -1 7906 ); 7907 7908 final int relaunchReason = r == null ? RELAUNCH_REASON_NONE 7909 : r.getWindowProcessController().computeRelaunchReason(); 7910 final String relaunchReasonString = relaunchReasonToString(relaunchReason); 7911 if (crashInfo.crashTag == null) { 7912 crashInfo.crashTag = relaunchReasonString; 7913 } else { 7914 crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString; 7915 } 7916 7917 addErrorToDropBox( 7918 eventType, r, processName, null, null, null, null, null, null, crashInfo, 7919 new Float(loadingProgress), incrementalMetrics, null); 7920 7921 mAppErrors.crashApplication(r, crashInfo); 7922 } 7923 handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)7924 public void handleApplicationStrictModeViolation( 7925 IBinder app, 7926 int penaltyMask, 7927 StrictMode.ViolationInfo info) { 7928 // We're okay if the ProcessRecord is missing; it probably means that 7929 // we're reporting a violation from the system process itself. 7930 final ProcessRecord r = findAppProcess(app, "StrictMode"); 7931 7932 if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) { 7933 Integer stackFingerprint = info.hashCode(); 7934 boolean logIt = true; 7935 synchronized (mAlreadyLoggedViolatedStacks) { 7936 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 7937 logIt = false; 7938 // TODO: sub-sample into EventLog for these, with 7939 // the info.durationMillis? Then we'd get 7940 // the relative pain numbers, without logging all 7941 // the stack traces repeatedly. We'd want to do 7942 // likewise in the client code, which also does 7943 // dup suppression, before the Binder call. 7944 } else { 7945 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 7946 mAlreadyLoggedViolatedStacks.clear(); 7947 } 7948 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 7949 } 7950 } 7951 if (logIt) { 7952 logStrictModeViolationToDropBox(r, info); 7953 } 7954 } 7955 7956 if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) { 7957 AppErrorResult result = new AppErrorResult(); 7958 final long origId = Binder.clearCallingIdentity(); 7959 try { 7960 Message msg = Message.obtain(); 7961 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG; 7962 HashMap<String, Object> data = new HashMap<String, Object>(); 7963 data.put("result", result); 7964 data.put("app", r); 7965 data.put("info", info); 7966 msg.obj = data; 7967 mUiHandler.sendMessage(msg); 7968 } finally { 7969 Binder.restoreCallingIdentity(origId); 7970 } 7971 int res = result.get(); 7972 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 7973 } 7974 } 7975 7976 // Depending on the policy in effect, there could be a bunch of 7977 // these in quick succession so we try to batch these together to 7978 // minimize disk writes, number of dropbox entries, and maximize 7979 // compression, by having more fewer, larger records. logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)7980 private void logStrictModeViolationToDropBox( 7981 ProcessRecord process, 7982 StrictMode.ViolationInfo info) { 7983 if (info == null) { 7984 return; 7985 } 7986 final boolean isSystemApp = process == null || 7987 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 7988 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 7989 final String processName = process == null ? "unknown" : process.processName; 7990 final DropBoxManager dbox = (DropBoxManager) 7991 mContext.getSystemService(Context.DROPBOX_SERVICE); 7992 7993 // Exit early if the dropbox isn't configured to accept this report type. 7994 final String dropboxTag = processClass(process) + "_strictmode"; 7995 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 7996 7997 final StringBuilder sb = new StringBuilder(1024); 7998 synchronized (sb) { 7999 appendDropBoxProcessHeaders(process, processName, sb); 8000 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 8001 sb.append("System-App: ").append(isSystemApp).append("\n"); 8002 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 8003 if (info.violationNumThisLoop != 0) { 8004 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 8005 } 8006 if (info.numAnimationsRunning != 0) { 8007 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 8008 } 8009 if (info.broadcastIntentAction != null) { 8010 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n"); 8011 } 8012 if (info.durationMillis != -1) { 8013 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 8014 } 8015 if (info.numInstances != -1) { 8016 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 8017 } 8018 if (info.tags != null) { 8019 for (String tag : info.tags) { 8020 sb.append("Span-Tag: ").append(tag).append("\n"); 8021 } 8022 } 8023 sb.append("\n"); 8024 sb.append(info.getStackTrace()); 8025 sb.append("\n"); 8026 if (info.getViolationDetails() != null) { 8027 sb.append(info.getViolationDetails()); 8028 sb.append("\n"); 8029 } 8030 } 8031 8032 final String res = sb.toString(); 8033 IoThread.getHandler().post(() -> { 8034 dbox.addText(dropboxTag, res); 8035 }); 8036 } 8037 8038 /** 8039 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 8040 * @param app object of the crashing app, null for the system server 8041 * @param tag reported by the caller 8042 * @param system whether this wtf is coming from the system 8043 * @param crashInfo describing the context of the error 8044 * @return true if the process should exit immediately (WTF is fatal) 8045 */ 8046 @Override handleApplicationWtf(@ullable final IBinder app, @Nullable final String tag, boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)8047 public boolean handleApplicationWtf(@Nullable final IBinder app, @Nullable final String tag, 8048 boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, 8049 int immediateCallerPid) { 8050 final int callingUid = Binder.getCallingUid(); 8051 final int callingPid = Binder.getCallingPid(); 8052 8053 // Internal callers in RuntimeInit should always generate a crashInfo. 8054 Preconditions.checkNotNull(crashInfo); 8055 8056 // If this is coming from the system, we could very well have low-level 8057 // system locks held, so we want to do this all asynchronously. And we 8058 // never want this to become fatal, so there is that too. 8059 // 8060 // Note: "callingPid == Process.myPid())" wouldn't be reliable because even if the caller 8061 // is within the system server, if it calls Log.wtf() without clearning the calling 8062 // identity, callingPid would still be of a remote caller. So we explicltly pass the 8063 // process PID from the caller. 8064 if (system || (immediateCallerPid == Process.myPid())) { 8065 mHandler.post(new Runnable() { 8066 @Override public void run() { 8067 handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo); 8068 } 8069 }); 8070 return false; 8071 } 8072 8073 final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag, 8074 crashInfo); 8075 8076 final boolean isFatal = Build.IS_ENG || Settings.Global 8077 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0; 8078 final boolean isSystem = (r == null) || r.isPersistent(); 8079 8080 if (isFatal && !isSystem) { 8081 mAppErrors.crashApplication(r, crashInfo); 8082 return true; 8083 } else { 8084 return false; 8085 } 8086 } 8087 handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo)8088 ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, 8089 @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo) { 8090 final ProcessRecord r = findAppProcess(app, "WTF"); 8091 final String processName = app == null ? "system_server" 8092 : (r == null ? "unknown" : r.processName); 8093 8094 EventLogTags.writeAmWtf(UserHandle.getUserId(callingUid), callingPid, 8095 processName, r == null ? -1 : r.info.flags, tag, 8096 crashInfo == null ? "unknown" : crashInfo.exceptionMessage); 8097 8098 FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, callingUid, tag, processName, 8099 callingPid, (r != null) ? r.getProcessClassEnum() : 0); 8100 8101 addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo, 8102 null, null, null); 8103 8104 return r; 8105 } 8106 8107 /** 8108 * Schedule to handle any pending system_server WTFs. 8109 */ schedulePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)8110 public void schedulePendingSystemServerWtfs( 8111 final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) { 8112 mHandler.post(() -> handlePendingSystemServerWtfs(list)); 8113 } 8114 8115 /** 8116 * Handle any pending system_server WTFs, add into the dropbox 8117 */ handlePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)8118 private void handlePendingSystemServerWtfs( 8119 final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) { 8120 ProcessRecord proc; 8121 synchronized (mPidsSelfLocked) { 8122 proc = mPidsSelfLocked.get(MY_PID); 8123 } 8124 for (Pair<String, ApplicationErrorReport.CrashInfo> p = list.poll(); 8125 p != null; p = list.poll()) { 8126 addErrorToDropBox("wtf", proc, "system_server", null, null, null, p.first, null, null, 8127 p.second, null, null, null); 8128 } 8129 } 8130 8131 /** 8132 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 8133 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 8134 */ findAppProcess(IBinder app, String reason)8135 private ProcessRecord findAppProcess(IBinder app, String reason) { 8136 if (app == null) { 8137 return null; 8138 } 8139 8140 synchronized (mProcLock) { 8141 return mProcessList.findAppProcessLOSP(app, reason); 8142 } 8143 } 8144 8145 /** 8146 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 8147 * to append various headers to the dropbox log text. 8148 */ appendDropBoxProcessHeaders(ProcessRecord process, String processName, final StringBuilder sb)8149 void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 8150 final StringBuilder sb) { 8151 // Watchdog thread ends up invoking this function (with 8152 // a null ProcessRecord) to add the stack file to dropbox. 8153 // Do not acquire a lock on this (am) in such cases, as it 8154 // could cause a potential deadlock, if and when watchdog 8155 // is invoked due to unavailability of lock on am and it 8156 // would prevent watchdog from killing system_server. 8157 if (process == null) { 8158 sb.append("Process: ").append(processName).append("\n"); 8159 return; 8160 } 8161 // Note: ProcessRecord 'process' is guarded by the service 8162 // instance. (notably process.pkgList, which could otherwise change 8163 // concurrently during execution of this method) 8164 synchronized (mProcLock) { 8165 sb.append("Process: ").append(processName).append("\n"); 8166 sb.append("PID: ").append(process.getPid()).append("\n"); 8167 sb.append("UID: ").append(process.uid).append("\n"); 8168 int flags = process.info.flags; 8169 final IPackageManager pm = AppGlobals.getPackageManager(); 8170 sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n"); 8171 final int callingUserId = UserHandle.getCallingUserId(); 8172 process.getPkgList().forEachPackage(pkg -> { 8173 sb.append("Package: ").append(pkg); 8174 try { 8175 final PackageInfo pi = pm.getPackageInfo(pkg, 0, callingUserId); 8176 if (pi != null) { 8177 sb.append(" v").append(pi.getLongVersionCode()); 8178 if (pi.versionName != null) { 8179 sb.append(" (").append(pi.versionName).append(")"); 8180 } 8181 } 8182 } catch (RemoteException e) { 8183 Slog.e(TAG, "Error getting package info: " + pkg, e); 8184 } 8185 sb.append("\n"); 8186 }); 8187 if (process.info.isInstantApp()) { 8188 sb.append("Instant-App: true\n"); 8189 } 8190 } 8191 } 8192 processClass(ProcessRecord process)8193 private static String processClass(ProcessRecord process) { 8194 if (process == null || process.getPid() == MY_PID) { 8195 return "system_server"; 8196 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8197 return "system_app"; 8198 } else { 8199 return "data_app"; 8200 } 8201 } 8202 8203 private final ArrayMap<String, long[]> mErrorClusterRecords = new ArrayMap<>(); 8204 8205 /** 8206 * Write a description of an error (crash, WTF, ANR) to the drop box. 8207 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 8208 * @param process which caused the error, null means the system server 8209 * @param activityShortComponentName which triggered the error, null if unknown 8210 * @param parentShortComponentName activity related to the error, null if unknown 8211 * @param parentProcess parent process 8212 * @param subject line related to the error, null if absent 8213 * @param report in long form describing the error, null if absent 8214 * @param dataFile text file to include in the report, null if none 8215 * @param crashInfo giving an application stack trace, null if absent 8216 * @param loadingProgress the loading progress of an installed package, range in [0, 1]. 8217 * @param incrementalMetrics metrics for apps installed on Incremental. 8218 * @param errorId a unique id to append to the dropbox headers. 8219 */ 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)8220 public void addErrorToDropBox(String eventType, 8221 ProcessRecord process, String processName, String activityShortComponentName, 8222 String parentShortComponentName, ProcessRecord parentProcess, 8223 String subject, final String report, final File dataFile, 8224 final ApplicationErrorReport.CrashInfo crashInfo, 8225 @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics, 8226 @Nullable UUID errorId) { 8227 // NOTE -- this must never acquire the ActivityManagerService lock, 8228 // otherwise the watchdog may be prevented from resetting the system. 8229 8230 // Bail early if not published yet 8231 if (ServiceManager.getService(Context.DROPBOX_SERVICE) == null) return; 8232 final DropBoxManager dbox = mContext.getSystemService(DropBoxManager.class); 8233 8234 // Exit early if the dropbox isn't configured to accept this report type. 8235 final String dropboxTag = processClass(process) + "_" + eventType; 8236 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 8237 8238 // Rate-limit how often we're willing to do the heavy lifting below to 8239 // collect and record logs; currently 5 logs per 10 second period per eventType. 8240 final long now = SystemClock.elapsedRealtime(); 8241 synchronized (mErrorClusterRecords) { 8242 long[] errRecord = mErrorClusterRecords.get(eventType); 8243 if (errRecord == null) { 8244 errRecord = new long[2]; // [0]: startTime, [1]: count 8245 mErrorClusterRecords.put(eventType, errRecord); 8246 } 8247 if (now - errRecord[0] > 10 * DateUtils.SECOND_IN_MILLIS) { 8248 errRecord[0] = now; 8249 errRecord[1] = 1L; 8250 } else { 8251 if (errRecord[1]++ >= 5) return; 8252 } 8253 } 8254 8255 final StringBuilder sb = new StringBuilder(1024); 8256 appendDropBoxProcessHeaders(process, processName, sb); 8257 if (process != null) { 8258 sb.append("Foreground: ") 8259 .append(process.isInterestingToUserLocked() ? "Yes" : "No") 8260 .append("\n"); 8261 if (process.getStartTime() > 0) { 8262 long runtimeMillis = SystemClock.elapsedRealtime() - process.getStartTime(); 8263 sb.append("Process-Runtime: ").append(runtimeMillis).append("\n"); 8264 } 8265 } 8266 if (activityShortComponentName != null) { 8267 sb.append("Activity: ").append(activityShortComponentName).append("\n"); 8268 } 8269 if (parentShortComponentName != null) { 8270 if (parentProcess != null && parentProcess.getPid() != process.getPid()) { 8271 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n"); 8272 } 8273 if (!parentShortComponentName.equals(activityShortComponentName)) { 8274 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n"); 8275 } 8276 } 8277 if (subject != null) { 8278 sb.append("Subject: ").append(subject).append("\n"); 8279 } 8280 if (errorId != null) { 8281 sb.append("ErrorId: ").append(errorId.toString()).append("\n"); 8282 } 8283 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 8284 if (Debug.isDebuggerConnected()) { 8285 sb.append("Debugger: Connected\n"); 8286 } 8287 if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) { 8288 sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n"); 8289 } 8290 if (loadingProgress != null) { 8291 sb.append("Loading-Progress: ").append(loadingProgress.floatValue()).append("\n"); 8292 } 8293 if (incrementalMetrics != null) { 8294 sb.append("Incremental: Yes").append("\n"); 8295 final long millisSinceOldestPendingRead = 8296 incrementalMetrics.getMillisSinceOldestPendingRead(); 8297 if (millisSinceOldestPendingRead > 0) { 8298 sb.append("Millis-Since-Oldest-Pending-Read: ").append( 8299 millisSinceOldestPendingRead).append("\n"); 8300 } 8301 } 8302 sb.append("\n"); 8303 8304 // Do the rest in a worker thread to avoid blocking the caller on I/O 8305 // (After this point, we shouldn't access AMS internal data structures.) 8306 Thread worker = new Thread("Error dump: " + dropboxTag) { 8307 @Override 8308 public void run() { 8309 if (report != null) { 8310 sb.append(report); 8311 } 8312 8313 String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 8314 String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag; 8315 int lines = Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0); 8316 int dropboxMaxSize = Settings.Global.getInt( 8317 mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE); 8318 int maxDataFileSize = dropboxMaxSize - sb.length() 8319 - lines * RESERVED_BYTES_PER_LOGCAT_LINE; 8320 8321 if (dataFile != null && maxDataFileSize > 0) { 8322 try { 8323 sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize, 8324 "\n\n[[TRUNCATED]]")); 8325 } catch (IOException e) { 8326 Slog.e(TAG, "Error reading " + dataFile, e); 8327 } 8328 } 8329 if (crashInfo != null && crashInfo.stackTrace != null) { 8330 sb.append(crashInfo.stackTrace); 8331 } 8332 8333 if (lines > 0) { 8334 sb.append("\n"); 8335 8336 // Merge several logcat streams, and take the last N lines 8337 InputStreamReader input = null; 8338 try { 8339 java.lang.Process logcat = new ProcessBuilder( 8340 "/system/bin/timeout", "-k", "15s", "10s", 8341 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system", 8342 "-b", "main", "-b", "crash", "-t", String.valueOf(lines)) 8343 .redirectErrorStream(true).start(); 8344 8345 try { logcat.getOutputStream().close(); } catch (IOException e) {} 8346 try { logcat.getErrorStream().close(); } catch (IOException e) {} 8347 input = new InputStreamReader(logcat.getInputStream()); 8348 8349 int num; 8350 char[] buf = new char[8192]; 8351 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num); 8352 } catch (IOException e) { 8353 Slog.e(TAG, "Error running logcat", e); 8354 } finally { 8355 if (input != null) try { input.close(); } catch (IOException e) {} 8356 } 8357 } 8358 8359 dbox.addText(dropboxTag, sb.toString()); 8360 } 8361 }; 8362 8363 if (process == null) { 8364 // If process is null, we are being called from some internal code 8365 // and may be about to die -- run this synchronously. 8366 final int oldMask = StrictMode.allowThreadDiskWritesMask(); 8367 try { 8368 worker.run(); 8369 } finally { 8370 StrictMode.setThreadPolicyMask(oldMask); 8371 } 8372 } else { 8373 worker.start(); 8374 } 8375 } 8376 8377 @Override getProcessesInErrorState()8378 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 8379 enforceNotIsolatedCaller("getProcessesInErrorState"); 8380 // assume our apps are happy - lazy create the list 8381 final List<ActivityManager.ProcessErrorStateInfo>[] errList = new List[1]; 8382 8383 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 8384 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 8385 int userId = UserHandle.getUserId(Binder.getCallingUid()); 8386 8387 synchronized (mProcLock) { 8388 // iterate across all processes 8389 mProcessList.forEachLruProcessesLOSP(false, app -> { 8390 if (!allUsers && app.userId != userId) { 8391 return; 8392 } 8393 final ProcessErrorStateRecord errState = app.mErrorState; 8394 final boolean crashing = errState.isCrashing(); 8395 final boolean notResponding = errState.isNotResponding(); 8396 if ((app.getThread() != null) && (crashing || notResponding)) { 8397 // This one's in trouble, so we'll generate a report for it 8398 // crashes are higher priority (in case there's a crash *and* an anr) 8399 ActivityManager.ProcessErrorStateInfo report = null; 8400 if (crashing) { 8401 report = errState.getCrashingReport(); 8402 } else if (notResponding) { 8403 report = errState.getNotRespondingReport(); 8404 } 8405 8406 if (report != null) { 8407 if (errList[0] == null) { 8408 errList[0] = new ArrayList<>(1); 8409 } 8410 errList[0].add(report); 8411 } else { 8412 Slog.w(TAG, "Missing app error report, app = " + app.processName + 8413 " crashing = " + crashing + 8414 " notResponding = " + notResponding); 8415 } 8416 } 8417 }); 8418 } 8419 8420 return errList[0]; 8421 } 8422 8423 @Override getRunningAppProcesses()8424 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 8425 enforceNotIsolatedCaller("getRunningAppProcesses"); 8426 8427 final int callingUid = Binder.getCallingUid(); 8428 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 8429 8430 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 8431 callingUid) == PackageManager.PERMISSION_GRANTED; 8432 final int userId = UserHandle.getUserId(callingUid); 8433 final boolean allUids = mAtmInternal.isGetTasksAllowed( 8434 "getRunningAppProcesses", Binder.getCallingPid(), callingUid); 8435 8436 synchronized (mProcLock) { 8437 // Iterate across all processes 8438 return mProcessList.getRunningAppProcessesLOSP(allUsers, userId, allUids, 8439 callingUid, clientTargetSdk); 8440 } 8441 } 8442 8443 @Override getRunningExternalApplications()8444 public List<ApplicationInfo> getRunningExternalApplications() { 8445 enforceNotIsolatedCaller("getRunningExternalApplications"); 8446 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 8447 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 8448 if (runningApps != null && runningApps.size() > 0) { 8449 Set<String> extList = new HashSet<String>(); 8450 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 8451 if (app.pkgList != null) { 8452 for (String pkg : app.pkgList) { 8453 extList.add(pkg); 8454 } 8455 } 8456 } 8457 IPackageManager pm = AppGlobals.getPackageManager(); 8458 for (String pkg : extList) { 8459 try { 8460 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 8461 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 8462 retList.add(info); 8463 } 8464 } catch (RemoteException e) { 8465 } 8466 } 8467 } 8468 return retList; 8469 } 8470 8471 @Override getHistoricalProcessExitReasons( String packageName, int pid, int maxNum, int userId)8472 public ParceledListSlice<ApplicationExitInfo> getHistoricalProcessExitReasons( 8473 String packageName, int pid, int maxNum, int userId) { 8474 enforceNotIsolatedCaller("getHistoricalProcessExitReasons"); 8475 8476 // For the simplification, we don't support USER_ALL nor USER_CURRENT here. 8477 if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) { 8478 throw new IllegalArgumentException("Unsupported userId"); 8479 } 8480 8481 final int callingPid = Binder.getCallingPid(); 8482 final int callingUid = Binder.getCallingUid(); 8483 final int callingUserId = UserHandle.getCallingUserId(); 8484 mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL, 8485 "getHistoricalProcessExitReasons", null); 8486 8487 NativeTombstoneManager tombstoneService = LocalServices.getService( 8488 NativeTombstoneManager.class); 8489 8490 final ArrayList<ApplicationExitInfo> results = new ArrayList<ApplicationExitInfo>(); 8491 if (!TextUtils.isEmpty(packageName)) { 8492 final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid, 8493 "getHistoricalProcessExitReasons"); 8494 if (uid != INVALID_UID) { 8495 mProcessList.mAppExitInfoTracker.getExitInfo( 8496 packageName, uid, pid, maxNum, results); 8497 tombstoneService.collectTombstones(results, uid, pid, maxNum); 8498 } 8499 } else { 8500 // If no package name is given, use the caller's uid as the filter uid. 8501 mProcessList.mAppExitInfoTracker.getExitInfo( 8502 packageName, callingUid, pid, maxNum, results); 8503 tombstoneService.collectTombstones(results, callingUid, pid, maxNum); 8504 } 8505 8506 return new ParceledListSlice<ApplicationExitInfo>(results); 8507 } 8508 8509 @Override setProcessStateSummary(@ullable byte[] state)8510 public void setProcessStateSummary(@Nullable byte[] state) { 8511 if (state != null && state.length > MAX_STATE_DATA_SIZE) { 8512 throw new IllegalArgumentException("Data size is too large"); 8513 } 8514 mProcessList.mAppExitInfoTracker.setProcessStateSummary(Binder.getCallingUid(), 8515 Binder.getCallingPid(), state); 8516 } 8517 8518 /** 8519 * Check if the calling process has the permission to dump given package, 8520 * throw SecurityException if it doesn't have the permission. 8521 * 8522 * @return The UID of the given package, or {@link android.os.Process#INVALID_UID} 8523 * if the package is not found. 8524 */ enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, String function)8525 int enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, 8526 String function) { 8527 final long identity = Binder.clearCallingIdentity(); 8528 int uid = INVALID_UID; 8529 try { 8530 uid = mPackageManagerInt.getPackageUid(packageName, 8531 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId); 8532 } finally { 8533 Binder.restoreCallingIdentity(identity); 8534 } 8535 // If the uid is Process.INVALID_UID, the below 'if' check will be always true 8536 if (UserHandle.getAppId(uid) != UserHandle.getAppId(callingUid)) { 8537 // Requires the DUMP permission if the target package doesn't belong 8538 // to the caller or it doesn't exist. 8539 enforceCallingPermission(android.Manifest.permission.DUMP, function); 8540 } 8541 return uid; 8542 } 8543 8544 @Override getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)8545 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) { 8546 if (outState == null) { 8547 throw new IllegalArgumentException("outState is null"); 8548 } 8549 enforceNotIsolatedCaller("getMyMemoryState"); 8550 8551 final int callingUid = Binder.getCallingUid(); 8552 final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid); 8553 8554 synchronized (mProcLock) { 8555 ProcessRecord proc; 8556 synchronized (mPidsSelfLocked) { 8557 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 8558 } 8559 if (proc != null) { 8560 mProcessList.fillInProcMemInfoLOSP(proc, outState, clientTargetSdk); 8561 } 8562 } 8563 } 8564 8565 @Override getMemoryTrimLevel()8566 public @MemFactor int getMemoryTrimLevel() { 8567 enforceNotIsolatedCaller("getMyMemoryState"); 8568 synchronized (this) { 8569 return mAppProfiler.getLastMemoryLevelLocked(); 8570 } 8571 } 8572 setMemFactorOverride(@emFactor int level)8573 void setMemFactorOverride(@MemFactor int level) { 8574 synchronized (this) { 8575 if (level == mAppProfiler.getLastMemoryLevelLocked()) { 8576 return; 8577 } 8578 8579 mAppProfiler.setMemFactorOverrideLocked(level); 8580 // Kick off an oom adj update since we forced a mem factor update. 8581 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 8582 } 8583 } 8584 8585 /** 8586 * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}. 8587 */ setServiceRestartBackoffEnabled(@onNull String packageName, boolean enable, @NonNull String reason)8588 void setServiceRestartBackoffEnabled(@NonNull String packageName, boolean enable, 8589 @NonNull String reason) { 8590 synchronized (this) { 8591 mServices.setServiceRestartBackoffEnabledLocked(packageName, enable, reason); 8592 } 8593 } 8594 8595 /** 8596 * @return {@code false} if the given package has been disable from enforcing the service 8597 * restart backoff policy, used by {@link ActivityManagerShellCommand}. 8598 */ isServiceRestartBackoffEnabled(@onNull String packageName)8599 boolean isServiceRestartBackoffEnabled(@NonNull String packageName) { 8600 synchronized (this) { 8601 return mServices.isServiceRestartBackoffEnabledLocked(packageName); 8602 } 8603 } 8604 8605 @Override onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)8606 public void onShellCommand(FileDescriptor in, FileDescriptor out, 8607 FileDescriptor err, String[] args, ShellCallback callback, 8608 ResultReceiver resultReceiver) { 8609 (new ActivityManagerShellCommand(this, false)).exec( 8610 this, in, out, err, args, callback, resultReceiver); 8611 } 8612 8613 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)8614 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 8615 PriorityDump.dump(mPriorityDumper, fd, pw, args); 8616 } 8617 dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies)8618 private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, 8619 boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, 8620 int dumpAppId, boolean dumpProxies) { 8621 8622 ActiveServices.ServiceDumper sdumper; 8623 8624 synchronized(this) { 8625 mConstants.dump(pw); 8626 synchronized (mProcLock) { 8627 mOomAdjuster.dumpCachedAppOptimizerSettings(pw); 8628 } 8629 mOomAdjuster.dumpCacheOomRankerSettings(pw); 8630 pw.println(); 8631 if (dumpAll) { 8632 pw.println("-------------------------------------------------------------------------------"); 8633 8634 } 8635 dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 8636 pw.println(); 8637 if (dumpAll) { 8638 pw.println("-------------------------------------------------------------------------------"); 8639 8640 } 8641 mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage); 8642 pw.println(); 8643 if (dumpAll) { 8644 pw.println("-------------------------------------------------------------------------------"); 8645 } 8646 dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 8647 pw.println(); 8648 if (dumpAll) { 8649 pw.println("-------------------------------------------------------------------------------"); 8650 } 8651 if (dumpAll || dumpPackage != null) { 8652 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 8653 pw.println(); 8654 if (dumpAll) { 8655 pw.println("-------------------------------------------------------------------------------"); 8656 } 8657 } 8658 mCpHelper.dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 8659 pw.println(); 8660 if (dumpAll) { 8661 pw.println("-------------------------------------------------------------------------------"); 8662 } 8663 dumpPermissions(fd, pw, args, opti, dumpAll, dumpPackage); 8664 pw.println(); 8665 sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage); 8666 if (!dumpClient) { 8667 if (dumpAll) { 8668 pw.println("-------------------------------------------------------------------------------"); 8669 } 8670 sdumper.dumpLocked(); 8671 } 8672 } 8673 // We drop the lock here because we can't call dumpWithClient() with the lock held; 8674 // if the caller wants a consistent state for the !dumpClient case, it can call this 8675 // method with the lock held. 8676 if (dumpClient) { 8677 if (dumpAll) { 8678 pw.println("-------------------------------------------------------------------------------"); 8679 } 8680 sdumper.dumpWithClient(); 8681 } 8682 if (dumpPackage == null && dumpProxies) { 8683 // Intentionally dropping the lock for this, because dumpBinderProxies() will make many 8684 // outgoing binder calls to retrieve interface descriptors; while that is system code, 8685 // there is nothing preventing an app from overriding this implementation by talking to 8686 // the binder driver directly, and hang up system_server in the process. So, dump 8687 // without locks held, and even then only when there is an unreasonably large number of 8688 // proxies in the first place. 8689 pw.println(); 8690 if (dumpAll) { 8691 pw.println("-------------------------------------------------------------------------------"); 8692 } 8693 dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */); 8694 } 8695 synchronized(this) { 8696 pw.println(); 8697 if (dumpAll) { 8698 pw.println("-------------------------------------------------------------------------------"); 8699 } 8700 mAtmInternal.dump( 8701 DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 8702 pw.println(); 8703 if (dumpAll) { 8704 pw.println("-------------------------------------------------------------------------------"); 8705 } 8706 mAtmInternal.dump( 8707 DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 8708 pw.println(); 8709 if (dumpAll) { 8710 pw.println("-------------------------------------------------------------------------------"); 8711 } 8712 mAtmInternal.dump( 8713 DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 8714 if (dumpPackage == null) { 8715 pw.println(); 8716 if (dumpAll) { 8717 pw.println("-------------------------------------------------------------------------------"); 8718 } 8719 mAtmInternal.dump( 8720 DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 8721 } 8722 // Activities section is dumped as part of the Critical priority dump. Exclude the 8723 // section if priority is Normal. 8724 if (!dumpNormalPriority) { 8725 pw.println(); 8726 if (dumpAll) { 8727 pw.println("-------------------------------------------------------------------------------"); 8728 } 8729 mAtmInternal.dump( 8730 DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 8731 } 8732 if (mAssociations.size() > 0) { 8733 pw.println(); 8734 if (dumpAll) { 8735 pw.println("-------------------------------------------------------------------------------"); 8736 } 8737 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 8738 } 8739 pw.println(); 8740 if (dumpAll) { 8741 pw.println("-------------------------------------------------------------------------------"); 8742 } 8743 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage); 8744 if (dumpPackage == null) { 8745 pw.println(); 8746 if (dumpAll) { 8747 pw.println("-------------------------------------------------------------------------------"); 8748 } 8749 mOomAdjProfiler.dump(pw); 8750 pw.println(); 8751 if (dumpAll) { 8752 pw.println("-------------------------------------------------------------------------------"); 8753 } 8754 dumpLmkLocked(pw); 8755 } 8756 pw.println(); 8757 if (dumpAll) { 8758 pw.println("-------------------------------------------------------------------------------"); 8759 } 8760 synchronized (mProcLock) { 8761 mProcessList.dumpProcessesLSP(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId); 8762 } 8763 pw.println(); 8764 if (dumpAll) { 8765 pw.println("-------------------------------------------------------------------------------"); 8766 } 8767 dumpUsers(pw); 8768 } 8769 } 8770 8771 /** 8772 * Wrapper function to print out debug data filtered by specified arguments. 8773 */ doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)8774 private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) { 8775 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 8776 8777 boolean dumpAll = false; 8778 boolean dumpClient = false; 8779 boolean dumpCheckin = false; 8780 boolean dumpCheckinFormat = false; 8781 boolean dumpNormalPriority = false; 8782 boolean dumpVisibleStacksOnly = false; 8783 boolean dumpFocusedStackOnly = false; 8784 String dumpPackage = null; 8785 8786 int opti = 0; 8787 while (opti < args.length) { 8788 String opt = args[opti]; 8789 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 8790 break; 8791 } 8792 opti++; 8793 if ("-a".equals(opt)) { 8794 dumpAll = true; 8795 } else if ("-c".equals(opt)) { 8796 dumpClient = true; 8797 } else if ("-v".equals(opt)) { 8798 dumpVisibleStacksOnly = true; 8799 } else if ("-f".equals(opt)) { 8800 dumpFocusedStackOnly = true; 8801 } else if ("-p".equals(opt)) { 8802 if (opti < args.length) { 8803 dumpPackage = args[opti]; 8804 opti++; 8805 } else { 8806 pw.println("Error: -p option requires package argument"); 8807 return; 8808 } 8809 dumpClient = true; 8810 } else if ("--checkin".equals(opt)) { 8811 dumpCheckin = dumpCheckinFormat = true; 8812 } else if ("-C".equals(opt)) { 8813 dumpCheckinFormat = true; 8814 } else if ("--normal-priority".equals(opt)) { 8815 dumpNormalPriority = true; 8816 } else if ("-h".equals(opt)) { 8817 ActivityManagerShellCommand.dumpHelp(pw, true); 8818 return; 8819 } else { 8820 pw.println("Unknown argument: " + opt + "; use -h for help"); 8821 } 8822 } 8823 8824 final long origId = Binder.clearCallingIdentity(); 8825 8826 if (useProto) { 8827 final ProtoOutputStream proto = new ProtoOutputStream(fd); 8828 String cmd = opti < args.length ? args[opti] : ""; 8829 opti++; 8830 8831 if ("activities".equals(cmd) || "a".equals(cmd)) { 8832 // output proto is ActivityManagerServiceDumpActivitiesProto 8833 mAtmInternal.writeActivitiesToProto(proto); 8834 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 8835 // output proto is ActivityManagerServiceDumpBroadcastsProto 8836 synchronized (this) { 8837 writeBroadcastsToProtoLocked(proto); 8838 } 8839 } else if ("provider".equals(cmd)) { 8840 String[] newArgs; 8841 String name; 8842 if (opti >= args.length) { 8843 name = null; 8844 newArgs = EMPTY_STRING_ARRAY; 8845 } else { 8846 name = args[opti]; 8847 opti++; 8848 newArgs = new String[args.length - opti]; 8849 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 8850 args.length - opti); 8851 } 8852 if (!mCpHelper.dumpProviderProto(fd, pw, name, newArgs)) { 8853 pw.println("No providers match: " + name); 8854 pw.println("Use -h for help."); 8855 } 8856 } else if ("service".equals(cmd)) { 8857 // output proto is ActivityManagerServiceDumpServicesProto 8858 mServices.dumpDebug(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 8859 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 8860 if (opti < args.length) { 8861 dumpPackage = args[opti]; 8862 opti++; 8863 } 8864 // output proto is ProcessProto 8865 synchronized (this) { 8866 synchronized (mProcLock) { 8867 mProcessList.writeProcessesToProtoLSP(proto, dumpPackage); 8868 } 8869 } 8870 } else { 8871 // default option, dump everything, output is ActivityManagerServiceProto 8872 synchronized (this) { 8873 long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES); 8874 mAtmInternal.writeActivitiesToProto(proto); 8875 proto.end(activityToken); 8876 8877 long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS); 8878 writeBroadcastsToProtoLocked(proto); 8879 proto.end(broadcastToken); 8880 8881 long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES); 8882 mServices.dumpDebug(proto, 8883 ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES); 8884 proto.end(serviceToken); 8885 8886 long processToken = proto.start(ActivityManagerServiceProto.PROCESSES); 8887 synchronized (mProcLock) { 8888 mProcessList.writeProcessesToProtoLSP(proto, dumpPackage); 8889 } 8890 proto.end(processToken); 8891 } 8892 } 8893 proto.flush(); 8894 Binder.restoreCallingIdentity(origId); 8895 return; 8896 } 8897 8898 int dumpAppId = getAppId(dumpPackage); 8899 boolean more = false; 8900 // Is the caller requesting to dump a particular piece of data? 8901 if (opti < args.length) { 8902 String cmd = args[opti]; 8903 opti++; 8904 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd) 8905 || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd) 8906 || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd) 8907 || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd) 8908 || DUMP_TOP_RESUMED_ACTIVITY.equals(cmd)) { 8909 mAtmInternal.dump( 8910 cmd, fd, pw, args, opti, true /* dumpAll */, dumpClient, dumpPackage); 8911 } else if ("binder-proxies".equals(cmd)) { 8912 if (opti >= args.length) { 8913 dumpBinderProxies(pw, 0 /* minToDump */); 8914 } else { 8915 String uid = args[opti]; 8916 opti++; 8917 // Ensure Binder Proxy Count is as up to date as possible 8918 System.gc(); 8919 System.runFinalization(); 8920 System.gc(); 8921 pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid))); 8922 } 8923 } else if ("allowed-associations".equals(cmd)) { 8924 if (opti < args.length) { 8925 dumpPackage = args[opti]; 8926 opti++; 8927 } 8928 synchronized (this) { 8929 dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage); 8930 } 8931 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 8932 if (opti < args.length) { 8933 dumpPackage = args[opti]; 8934 opti++; 8935 } 8936 synchronized (this) { 8937 dumpBroadcastsLocked(fd, pw, args, opti, true, dumpPackage); 8938 } 8939 } else if ("broadcast-stats".equals(cmd)) { 8940 if (opti < args.length) { 8941 dumpPackage = args[opti]; 8942 opti++; 8943 } 8944 synchronized (this) { 8945 if (dumpCheckinFormat) { 8946 dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, 8947 dumpPackage); 8948 } else { 8949 dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage); 8950 } 8951 } 8952 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 8953 if (opti < args.length) { 8954 dumpPackage = args[opti]; 8955 opti++; 8956 } 8957 mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage); 8958 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 8959 if (opti < args.length) { 8960 dumpPackage = args[opti]; 8961 opti++; 8962 } 8963 synchronized (this) { 8964 synchronized (mProcLock) { 8965 mProcessList.dumpProcessesLSP( 8966 fd, pw, args, opti, true, dumpPackage, dumpAppId); 8967 } 8968 } 8969 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 8970 synchronized (this) { 8971 mProcessList.dumpOomLocked(fd, pw, false, args, opti, true, dumpPackage, true); 8972 } 8973 } else if ("lmk".equals(cmd)) { 8974 synchronized (this) { 8975 dumpLmkLocked(pw); 8976 } 8977 } else if ("lru".equals(cmd)) { 8978 synchronized (this) { 8979 mProcessList.dumpLruLocked(pw, dumpPackage, null); 8980 } 8981 } else if ("permissions".equals(cmd) || "perm".equals(cmd)) { 8982 dumpPermissions(fd, pw, args, opti, true, dumpPackage); 8983 } else if ("provider".equals(cmd)) { 8984 String[] newArgs; 8985 String name; 8986 if (opti >= args.length) { 8987 name = null; 8988 newArgs = EMPTY_STRING_ARRAY; 8989 } else { 8990 name = args[opti]; 8991 opti++; 8992 newArgs = new String[args.length - opti]; 8993 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti); 8994 } 8995 if (!mCpHelper.dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 8996 pw.println("No providers match: " + name); 8997 pw.println("Use -h for help."); 8998 } 8999 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 9000 synchronized (this) { 9001 mCpHelper.dumpProvidersLocked(fd, pw, args, opti, true, dumpPackage); 9002 } 9003 } else if ("service".equals(cmd)) { 9004 String[] newArgs; 9005 String name; 9006 int[] users = null; 9007 if (opti >= args.length) { 9008 name = null; 9009 newArgs = EMPTY_STRING_ARRAY; 9010 } else { 9011 name = args[opti]; 9012 opti++; 9013 if ("--user".equals(name) && opti < args.length) { 9014 int userId = UserHandle.parseUserArg(args[opti]); 9015 opti++; 9016 if (userId != UserHandle.USER_ALL) { 9017 if (userId == UserHandle.USER_CURRENT) { 9018 userId = getCurrentUser().id; 9019 } 9020 users = new int[] { userId }; 9021 } 9022 name = args[opti]; 9023 opti++; 9024 } 9025 newArgs = new String[args.length - opti]; 9026 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 9027 args.length - opti); 9028 } 9029 if (!mServices.dumpService(fd, pw, name, users, newArgs, 0, dumpAll)) { 9030 pw.println("No services match: " + name); 9031 pw.println("Use -h for help."); 9032 } 9033 } else if ("package".equals(cmd)) { 9034 String[] newArgs; 9035 if (opti >= args.length) { 9036 pw.println("package: no package name specified"); 9037 pw.println("Use -h for help."); 9038 } else { 9039 dumpPackage = args[opti]; 9040 opti++; 9041 newArgs = new String[args.length - opti]; 9042 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 9043 args.length - opti); 9044 args = newArgs; 9045 opti = 0; 9046 more = true; 9047 } 9048 } else if ("associations".equals(cmd) || "as".equals(cmd)) { 9049 synchronized (this) { 9050 dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage); 9051 } 9052 } else if ("settings".equals(cmd)) { 9053 synchronized (this) { 9054 mConstants.dump(pw); 9055 } 9056 synchronized (mProcLock) { 9057 mOomAdjuster.dumpCachedAppOptimizerSettings(pw); 9058 mOomAdjuster.dumpCacheOomRankerSettings(pw); 9059 } 9060 } else if ("services".equals(cmd) || "s".equals(cmd)) { 9061 if (dumpClient) { 9062 ActiveServices.ServiceDumper dumper; 9063 synchronized (this) { 9064 dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true, 9065 dumpPackage); 9066 } 9067 dumper.dumpWithClient(); 9068 } else { 9069 synchronized (this) { 9070 mServices.newServiceDumperLocked(fd, pw, args, opti, true, 9071 dumpPackage).dumpLocked(); 9072 } 9073 } 9074 } else if ("locks".equals(cmd)) { 9075 LockGuard.dump(fd, pw, args); 9076 } else if ("users".equals(cmd)) { 9077 dumpUsers(pw); 9078 } else if ("exit-info".equals(cmd)) { 9079 if (opti < args.length) { 9080 dumpPackage = args[opti]; 9081 opti++; 9082 } 9083 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage); 9084 } else { 9085 // Dumping a single activity? 9086 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll, 9087 dumpVisibleStacksOnly, dumpFocusedStackOnly)) { 9088 ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true); 9089 int res = shell.exec(this, null, fd, null, args, null, 9090 new ResultReceiver(null)); 9091 if (res < 0) { 9092 pw.println("Bad activity command, or no activities match: " + cmd); 9093 pw.println("Use -h for help."); 9094 } 9095 } 9096 } 9097 if (!more) { 9098 Binder.restoreCallingIdentity(origId); 9099 return; 9100 } 9101 } 9102 9103 // No piece of data specified, dump everything. 9104 if (dumpCheckinFormat) { 9105 dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage); 9106 } else { 9107 if (dumpClient) { 9108 // dumpEverything() will take the lock when needed, and momentarily drop 9109 // it for dumping client state. 9110 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient, 9111 dumpNormalPriority, dumpAppId, true /* dumpProxies */); 9112 } else { 9113 // Take the lock here, so we get a consistent state for the entire dump; 9114 // dumpEverything() will take the lock as well, which is fine for everything 9115 // except dumping proxies, which can take a long time; exclude them. 9116 synchronized(this) { 9117 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient, 9118 dumpNormalPriority, dumpAppId, false /* dumpProxies */); 9119 } 9120 } 9121 } 9122 Binder.restoreCallingIdentity(origId); 9123 } 9124 dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)9125 void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 9126 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 9127 pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)"); 9128 9129 int dumpUid = 0; 9130 if (dumpPackage != null) { 9131 IPackageManager pm = AppGlobals.getPackageManager(); 9132 try { 9133 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0); 9134 } catch (RemoteException e) { 9135 } 9136 } 9137 9138 boolean printedAnything = false; 9139 9140 final long now = SystemClock.uptimeMillis(); 9141 9142 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 9143 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 9144 = mAssociations.valueAt(i1); 9145 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 9146 SparseArray<ArrayMap<String, Association>> sourceUids 9147 = targetComponents.valueAt(i2); 9148 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) { 9149 ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3); 9150 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 9151 Association ass = sourceProcesses.valueAt(i4); 9152 if (dumpPackage != null) { 9153 if (!ass.mTargetComponent.getPackageName().equals(dumpPackage) 9154 && UserHandle.getAppId(ass.mSourceUid) != dumpUid) { 9155 continue; 9156 } 9157 } 9158 printedAnything = true; 9159 pw.print(" "); 9160 pw.print(ass.mTargetProcess); 9161 pw.print("/"); 9162 UserHandle.formatUid(pw, ass.mTargetUid); 9163 pw.print(" <- "); 9164 pw.print(ass.mSourceProcess); 9165 pw.print("/"); 9166 UserHandle.formatUid(pw, ass.mSourceUid); 9167 pw.println(); 9168 pw.print(" via "); 9169 pw.print(ass.mTargetComponent.flattenToShortString()); 9170 pw.println(); 9171 pw.print(" "); 9172 long dur = ass.mTime; 9173 if (ass.mNesting > 0) { 9174 dur += now - ass.mStartTime; 9175 } 9176 TimeUtils.formatDuration(dur, pw); 9177 pw.print(" ("); 9178 pw.print(ass.mCount); 9179 pw.print(" times)"); 9180 pw.print(" "); 9181 for (int i=0; i<ass.mStateTimes.length; i++) { 9182 long amt = ass.mStateTimes[i]; 9183 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 9184 amt += now - ass.mLastStateUptime; 9185 } 9186 if (amt != 0) { 9187 pw.print(" "); 9188 pw.print(ProcessList.makeProcStateString( 9189 i + ActivityManager.MIN_PROCESS_STATE)); 9190 pw.print("="); 9191 TimeUtils.formatDuration(amt, pw); 9192 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) { 9193 pw.print("*"); 9194 } 9195 } 9196 } 9197 pw.println(); 9198 if (ass.mNesting > 0) { 9199 pw.print(" Currently active: "); 9200 TimeUtils.formatDuration(now - ass.mStartTime, pw); 9201 pw.println(); 9202 } 9203 } 9204 } 9205 } 9206 9207 } 9208 9209 if (!printedAnything) { 9210 pw.println(" (nothing)"); 9211 } 9212 } 9213 getAppId(String dumpPackage)9214 int getAppId(String dumpPackage) { 9215 if (dumpPackage != null) { 9216 try { 9217 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 9218 dumpPackage, 0); 9219 return UserHandle.getAppId(info.uid); 9220 } catch (NameNotFoundException e) { 9221 e.printStackTrace(); 9222 } 9223 } 9224 return -1; 9225 } 9226 dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)9227 void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) { 9228 final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50); 9229 9230 pw.println(header); 9231 for (int i = 0; i < proxyCounts.length; i++) { 9232 pw.println(" #" + (i + 1) + ": " + proxyCounts[i]); 9233 } 9234 } 9235 dumpBinderProxiesCounts(PrintWriter pw, String header)9236 boolean dumpBinderProxiesCounts(PrintWriter pw, String header) { 9237 SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts(); 9238 if(counts != null) { 9239 pw.println(header); 9240 for (int i = 0; i < counts.size(); i++) { 9241 final int uid = counts.keyAt(i); 9242 final int binderCount = counts.valueAt(i); 9243 pw.print(" UID "); 9244 pw.print(uid); 9245 pw.print(", binder count = "); 9246 pw.print(binderCount); 9247 pw.print(", package(s)= "); 9248 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid); 9249 if (pkgNames != null) { 9250 for (int j = 0; j < pkgNames.length; j++) { 9251 pw.print(pkgNames[j]); 9252 pw.print("; "); 9253 } 9254 } else { 9255 pw.print("NO PACKAGE NAME FOUND"); 9256 } 9257 pw.println(); 9258 } 9259 return true; 9260 } 9261 return false; 9262 } 9263 dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)9264 void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) { 9265 pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)"); 9266 final int proxyCount = BinderProxy.getProxyCount(); 9267 if (proxyCount >= minCountToDumpInterfaces) { 9268 dumpBinderProxyInterfaceCounts(pw, 9269 "Top proxy interface names held by SYSTEM"); 9270 } else { 9271 pw.print("Not dumping proxy interface counts because size (" 9272 + Integer.toString(proxyCount) + ") looks reasonable"); 9273 pw.println(); 9274 } 9275 dumpBinderProxiesCounts(pw, 9276 " Counts of Binder Proxies held by SYSTEM"); 9277 } 9278 9279 @GuardedBy("this") dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep)9280 boolean dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep) { 9281 final int size = mActiveInstrumentation.size(); 9282 if (size > 0) { 9283 boolean printed = false; 9284 for (int i = 0; i < size; i++) { 9285 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 9286 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 9287 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 9288 continue; 9289 } 9290 if (!printed) { 9291 if (needSep) { 9292 pw.println(); 9293 } 9294 pw.println(" Active instrumentation:"); 9295 printed = true; 9296 needSep = true; 9297 } 9298 pw.print(" Instrumentation #"); pw.print(i); pw.print(": "); 9299 pw.println(ai); 9300 ai.dump(pw, " "); 9301 } 9302 } 9303 return needSep; 9304 } 9305 9306 @GuardedBy({"this", "mProcLock"}) dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep)9307 void dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, 9308 boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep) { 9309 if (dumpAll || dumpPackage != null) { 9310 final SparseArray<ProcessRecord> pidToProcess = new SparseArray<>(); 9311 synchronized (mPidsSelfLocked) { 9312 boolean printed = false; 9313 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 9314 ProcessRecord r = mPidsSelfLocked.valueAt(i); 9315 pidToProcess.put(r.getPid(), r); 9316 if (dumpPackage != null && !r.getPkgList().containsKey(dumpPackage)) { 9317 continue; 9318 } 9319 if (!printed) { 9320 if (needSep) pw.println(); 9321 needSep = true; 9322 pw.println(" PID mappings:"); 9323 printed = true; 9324 } 9325 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 9326 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 9327 } 9328 } 9329 9330 synchronized (sActiveProcessInfoSelfLocked) { 9331 boolean printed = false; 9332 for (int i = 0, size = sActiveProcessInfoSelfLocked.size(); i < size; i++) { 9333 ProcessInfo info = sActiveProcessInfoSelfLocked.valueAt(i); 9334 ProcessRecord r = pidToProcess.get(sActiveProcessInfoSelfLocked.keyAt(i)); 9335 if (r != null && dumpPackage != null 9336 && !r.getPkgList().containsKey(dumpPackage)) { 9337 continue; 9338 } 9339 if (!printed) { 9340 if (needSep) pw.println(); 9341 needSep = true; 9342 pw.println(" Active process infos:"); 9343 printed = true; 9344 } 9345 pw.print(" Pinfo PID #"); pw.print(sActiveProcessInfoSelfLocked.keyAt(i)); 9346 pw.println(":"); 9347 pw.print(" name="); pw.println(info.name); 9348 if (info.deniedPermissions != null) { 9349 for (int j = 0; j < info.deniedPermissions.size(); j++) { 9350 pw.print(" deny: "); 9351 pw.println(info.deniedPermissions.valueAt(i)); 9352 } 9353 } 9354 } 9355 } 9356 } 9357 9358 if (dumpAll) { 9359 mPhantomProcessList.dump(pw, " "); 9360 } 9361 9362 if (mImportantProcesses.size() > 0) { 9363 synchronized (mPidsSelfLocked) { 9364 boolean printed = false; 9365 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) { 9366 ProcessRecord r = mPidsSelfLocked.get(mImportantProcesses.valueAt(i).pid); 9367 if (dumpPackage != null && (r == null 9368 || !r.getPkgList().containsKey(dumpPackage))) { 9369 continue; 9370 } 9371 if (!printed) { 9372 if (needSep) pw.println(); 9373 needSep = true; 9374 pw.println(" Foreground Processes:"); 9375 printed = true; 9376 } 9377 pw.print(" PID #"); pw.print(mImportantProcesses.keyAt(i)); 9378 pw.print(": "); pw.println(mImportantProcesses.valueAt(i)); 9379 } 9380 } 9381 } 9382 9383 if (mPersistentStartingProcesses.size() > 0) { 9384 if (needSep) pw.println(); 9385 needSep = true; 9386 pw.println(" Persisent processes that are starting:"); 9387 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 9388 "Starting Norm", "Restarting PERS", dumpPackage); 9389 } 9390 9391 if (mProcessList.mRemovedProcesses.size() > 0) { 9392 if (needSep) pw.println(); 9393 needSep = true; 9394 pw.println(" Processes that are being removed:"); 9395 dumpProcessList(pw, this, mProcessList.mRemovedProcesses, " ", 9396 "Removed Norm", "Removed PERS", dumpPackage); 9397 } 9398 9399 if (mProcessesOnHold.size() > 0) { 9400 if (needSep) pw.println(); 9401 needSep = true; 9402 pw.println(" Processes that are on old until the system is ready:"); 9403 dumpProcessList(pw, this, mProcessesOnHold, " ", 9404 "OnHold Norm", "OnHold PERS", dumpPackage); 9405 } 9406 9407 needSep = mAppErrors.dumpLPr(fd, pw, needSep, dumpPackage); 9408 9409 needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep, 9410 mAppProfiler.getTestPssMode(), mWakefulness.get()); 9411 9412 if (dumpAll && mProcessList.mPendingStarts.size() > 0) { 9413 if (needSep) pw.println(); 9414 needSep = true; 9415 pw.println(" mPendingStarts: "); 9416 for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) { 9417 pw.println(" " + mProcessList.mPendingStarts.keyAt(i) + ": " 9418 + mProcessList.mPendingStarts.valueAt(i)); 9419 } 9420 } 9421 if (dumpAll) { 9422 mUidObserverController.dump(pw, dumpPackage); 9423 9424 pw.println(" mDeviceIdleAllowlist=" + Arrays.toString(mDeviceIdleAllowlist)); 9425 pw.println(" mDeviceIdleExceptIdleAllowlist=" 9426 + Arrays.toString(mDeviceIdleExceptIdleAllowlist)); 9427 pw.println(" mDeviceIdleTempAllowlist=" + Arrays.toString(mDeviceIdleTempAllowlist)); 9428 if (mPendingTempAllowlist.size() > 0) { 9429 pw.println(" mPendingTempAllowlist:"); 9430 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) { 9431 PendingTempAllowlist ptw = mPendingTempAllowlist.valueAt(i); 9432 pw.print(" "); 9433 UserHandle.formatUid(pw, ptw.targetUid); 9434 pw.print(": "); 9435 TimeUtils.formatDuration(ptw.duration, pw); 9436 pw.print(" "); 9437 pw.println(ptw.tag); 9438 pw.print(" "); 9439 pw.print(ptw.type); 9440 pw.print(" "); 9441 pw.print(ptw.reasonCode); 9442 pw.print(" "); 9443 pw.print(ptw.callingUid); 9444 } 9445 } 9446 pw.println(" mFgsStartTempAllowList:"); 9447 final long currentTimeNow = System.currentTimeMillis(); 9448 final long elapsedRealtimeNow = SystemClock.elapsedRealtime(); 9449 mFgsStartTempAllowList.forEach((uid, entry) -> { 9450 pw.print(" " + UserHandle.formatUid(uid) + ": "); 9451 entry.second.dump(pw); 9452 pw.print(" expiration="); 9453 // Convert entry.mExpirationTime, which is an elapsed time since boot, 9454 // to a time since epoch (i.e. System.currentTimeMillis()-based time.) 9455 final long expirationInCurrentTime = 9456 currentTimeNow - elapsedRealtimeNow + entry.first; 9457 TimeUtils.dumpTimeWithDelta(pw, expirationInCurrentTime, currentTimeNow); 9458 pw.println(); 9459 }); 9460 } 9461 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 9462 || mOrigWaitForDebugger) { 9463 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 9464 || dumpPackage.equals(mOrigDebugApp)) { 9465 if (needSep) { 9466 pw.println(); 9467 needSep = false; 9468 } 9469 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 9470 + " mDebugTransient=" + mDebugTransient 9471 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 9472 } 9473 } 9474 synchronized (mAppProfiler.mProfilerLock) { 9475 needSep = mAppProfiler.dumpMemWatchProcessesLPf(pw, needSep); 9476 } 9477 if (mTrackAllocationApp != null) { 9478 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 9479 if (needSep) { 9480 pw.println(); 9481 needSep = false; 9482 } 9483 pw.println(" mTrackAllocationApp=" + mTrackAllocationApp); 9484 } 9485 } 9486 needSep = mAppProfiler.dumpProfileDataLocked(pw, dumpPackage, needSep); 9487 if (mNativeDebuggingApp != null) { 9488 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 9489 if (needSep) { 9490 pw.println(); 9491 needSep = false; 9492 } 9493 pw.println(" mNativeDebuggingApp=" + mNativeDebuggingApp); 9494 } 9495 } 9496 if (dumpPackage == null) { 9497 if (mAlwaysFinishActivities) { 9498 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities); 9499 } 9500 if (dumpAll) { 9501 pw.println(" Total persistent processes: " + numPers); 9502 pw.println(" mProcessesReady=" + mProcessesReady 9503 + " mSystemReady=" + mSystemReady 9504 + " mBooted=" + mBooted 9505 + " mFactoryTest=" + mFactoryTest); 9506 pw.println(" mBooting=" + mBooting 9507 + " mCallFinishBooting=" + mCallFinishBooting 9508 + " mBootAnimationComplete=" + mBootAnimationComplete); 9509 pw.print(" mLastPowerCheckUptime="); 9510 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 9511 pw.println(""); 9512 mOomAdjuster.dumpSequenceNumbersLocked(pw); 9513 mOomAdjuster.dumpProcCountsLocked(pw); 9514 mAppProfiler.dumpMemoryLevelsLocked(pw); 9515 long now = SystemClock.uptimeMillis(); 9516 pw.print(" mLastIdleTime="); 9517 TimeUtils.formatDuration(now, mLastIdleTime, pw); 9518 pw.print(" mLowRamSinceLastIdle="); 9519 TimeUtils.formatDuration( 9520 mAppProfiler.getLowRamTimeSinceIdleLPr(now), pw); 9521 pw.println(); 9522 9523 pw.println(); 9524 pw.println(" ServiceManager statistics:"); 9525 ServiceManager.sStatLogger.dump(pw, " "); 9526 pw.println(); 9527 } 9528 } 9529 pw.println(" mForceBackgroundCheck=" + mForceBackgroundCheck); 9530 } 9531 dumpUsers(PrintWriter pw)9532 private void dumpUsers(PrintWriter pw) { 9533 pw.println("ACTIVITY MANAGER USERS (dumpsys activity users)"); 9534 mUserController.dump(pw); 9535 } 9536 9537 @GuardedBy({"this", "mProcLock"}) writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, int dumpAppId, int numPers)9538 void writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, 9539 int dumpAppId, int numPers) { 9540 for (int i = 0, size = mActiveInstrumentation.size(); i < size; i++) { 9541 ActiveInstrumentation ai = mActiveInstrumentation.get(i); 9542 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage) 9543 && !ai.mTargetInfo.packageName.equals(dumpPackage)) { 9544 continue; 9545 } 9546 ai.dumpDebug(proto, 9547 ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS); 9548 } 9549 9550 mUidObserverController.dumpValidateUidsProto(proto, dumpPackage, dumpAppId, 9551 ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS); 9552 9553 if (dumpPackage != null) { 9554 synchronized (mPidsSelfLocked) { 9555 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 9556 ProcessRecord r = mPidsSelfLocked.valueAt(i); 9557 if (!r.getPkgList().containsKey(dumpPackage)) { 9558 continue; 9559 } 9560 r.dumpDebug(proto, 9561 ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED); 9562 } 9563 } 9564 } 9565 9566 if (mImportantProcesses.size() > 0) { 9567 synchronized (mPidsSelfLocked) { 9568 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) { 9569 ImportanceToken it = mImportantProcesses.valueAt(i); 9570 ProcessRecord r = mPidsSelfLocked.get(it.pid); 9571 if (dumpPackage != null && (r == null 9572 || !r.getPkgList().containsKey(dumpPackage))) { 9573 continue; 9574 } 9575 it.dumpDebug(proto, 9576 ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS); 9577 } 9578 } 9579 } 9580 9581 for (int i = 0, size = mPersistentStartingProcesses.size(); i < size; i++) { 9582 ProcessRecord r = mPersistentStartingProcesses.get(i); 9583 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 9584 continue; 9585 } 9586 r.dumpDebug(proto, 9587 ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS); 9588 } 9589 9590 for (int i = 0, size = mProcessList.mRemovedProcesses.size(); i < size; i++) { 9591 ProcessRecord r = mProcessList.mRemovedProcesses.get(i); 9592 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 9593 continue; 9594 } 9595 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS); 9596 } 9597 9598 for (int i = 0, size = mProcessesOnHold.size(); i < size; i++) { 9599 ProcessRecord r = mProcessesOnHold.get(i); 9600 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 9601 continue; 9602 } 9603 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS); 9604 } 9605 9606 synchronized (mAppProfiler.mProfilerLock) { 9607 mAppProfiler.writeProcessesToGcToProto(proto, 9608 ActivityManagerServiceDumpProcessesProto.GC_PROCS, 9609 dumpPackage); 9610 } 9611 mAppErrors.dumpDebugLPr(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS, 9612 dumpPackage); 9613 mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness.get(), 9614 mAppProfiler.getTestPssMode()); 9615 9616 if (dumpPackage == null) { 9617 mUserController.dumpDebug(proto, 9618 ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER); 9619 } 9620 9621 mUidObserverController.dumpDebug(proto, dumpPackage); 9622 9623 for (int v : mDeviceIdleAllowlist) { 9624 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v); 9625 } 9626 9627 for (int v : mDeviceIdleTempAllowlist) { 9628 proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v); 9629 } 9630 9631 if (mPendingTempAllowlist.size() > 0) { 9632 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) { 9633 mPendingTempAllowlist.valueAt(i).dumpDebug(proto, 9634 ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST); 9635 } 9636 } 9637 9638 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 9639 || mOrigWaitForDebugger) { 9640 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 9641 || dumpPackage.equals(mOrigDebugApp)) { 9642 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG); 9643 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp); 9644 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp); 9645 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient); 9646 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger); 9647 proto.end(debugAppToken); 9648 } 9649 } 9650 9651 synchronized (mAppProfiler.mProfilerLock) { 9652 mAppProfiler.writeMemWatchProcessToProtoLPf(proto); 9653 } 9654 9655 if (mTrackAllocationApp != null) { 9656 if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) { 9657 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP, 9658 mTrackAllocationApp); 9659 } 9660 } 9661 9662 mAppProfiler.writeProfileDataToProtoLocked(proto, dumpPackage); 9663 9664 if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) { 9665 proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp); 9666 } 9667 9668 if (dumpPackage == null) { 9669 proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities); 9670 proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers); 9671 proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady); 9672 proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady); 9673 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted); 9674 proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest); 9675 proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting); 9676 proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting); 9677 proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete); 9678 proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime); 9679 mOomAdjuster.dumpProcessListVariablesLocked(proto); 9680 mAppProfiler.writeMemoryLevelsToProtoLocked(proto); 9681 long now = SystemClock.uptimeMillis(); 9682 ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now); 9683 proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS, 9684 mAppProfiler.getLowRamTimeSinceIdleLPr(now)); 9685 } 9686 } 9687 reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)9688 private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) { 9689 Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj); 9690 if (cnt != null) { 9691 pw.println(" kills at or below oom_adj " + oom_adj + ": " + cnt); 9692 return true; 9693 } 9694 return false; 9695 } 9696 dumpLmkLocked(PrintWriter pw)9697 boolean dumpLmkLocked(PrintWriter pw) { 9698 pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)"); 9699 Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ, 9700 ProcessList.UNKNOWN_ADJ); 9701 if (cnt == null) { 9702 return false; 9703 } 9704 pw.println(" Total number of kills: " + cnt); 9705 9706 return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) && 9707 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) && 9708 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) && 9709 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) && 9710 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) && 9711 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) && 9712 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) && 9713 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) && 9714 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) && 9715 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) && 9716 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) && 9717 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ); 9718 } 9719 9720 public static class ItemMatcher { 9721 ArrayList<ComponentName> components; 9722 ArrayList<String> strings; 9723 ArrayList<Integer> objects; 9724 boolean all; 9725 ItemMatcher()9726 public ItemMatcher() { 9727 all = true; 9728 } 9729 build(String name)9730 public void build(String name) { 9731 ComponentName componentName = ComponentName.unflattenFromString(name); 9732 if (componentName != null) { 9733 if (components == null) { 9734 components = new ArrayList<ComponentName>(); 9735 } 9736 components.add(componentName); 9737 all = false; 9738 } else { 9739 int objectId = 0; 9740 // Not a '/' separated full component name; maybe an object ID? 9741 try { 9742 objectId = Integer.parseInt(name, 16); 9743 if (objects == null) { 9744 objects = new ArrayList<Integer>(); 9745 } 9746 objects.add(objectId); 9747 all = false; 9748 } catch (RuntimeException e) { 9749 // Not an integer; just do string match. 9750 if (strings == null) { 9751 strings = new ArrayList<String>(); 9752 } 9753 strings.add(name); 9754 all = false; 9755 } 9756 } 9757 } 9758 build(String[] args, int opti)9759 public int build(String[] args, int opti) { 9760 for (; opti<args.length; opti++) { 9761 String name = args[opti]; 9762 if ("--".equals(name)) { 9763 return opti+1; 9764 } 9765 build(name); 9766 } 9767 return opti; 9768 } 9769 match(Object object, ComponentName comp)9770 public boolean match(Object object, ComponentName comp) { 9771 if (all) { 9772 return true; 9773 } 9774 if (components != null) { 9775 for (int i=0; i<components.size(); i++) { 9776 if (components.get(i).equals(comp)) { 9777 return true; 9778 } 9779 } 9780 } 9781 if (objects != null) { 9782 for (int i=0; i<objects.size(); i++) { 9783 if (System.identityHashCode(object) == objects.get(i)) { 9784 return true; 9785 } 9786 } 9787 } 9788 if (strings != null) { 9789 String flat = comp.flattenToString(); 9790 for (int i=0; i<strings.size(); i++) { 9791 if (flat.contains(strings.get(i))) { 9792 return true; 9793 } 9794 } 9795 } 9796 return false; 9797 } 9798 } 9799 writeBroadcastsToProtoLocked(ProtoOutputStream proto)9800 void writeBroadcastsToProtoLocked(ProtoOutputStream proto) { 9801 if (mRegisteredReceivers.size() > 0) { 9802 Iterator it = mRegisteredReceivers.values().iterator(); 9803 while (it.hasNext()) { 9804 ReceiverList r = (ReceiverList)it.next(); 9805 r.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST); 9806 } 9807 } 9808 mReceiverResolver.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER); 9809 for (BroadcastQueue q : mBroadcastQueues) { 9810 q.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE); 9811 } 9812 for (int user=0; user<mStickyBroadcasts.size(); user++) { 9813 long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS); 9814 proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user)); 9815 for (Map.Entry<String, ArrayList<Intent>> ent 9816 : mStickyBroadcasts.valueAt(user).entrySet()) { 9817 long actionToken = proto.start(StickyBroadcastProto.ACTIONS); 9818 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey()); 9819 for (Intent intent : ent.getValue()) { 9820 intent.dumpDebug(proto, StickyBroadcastProto.StickyAction.INTENTS, 9821 false, true, true, false); 9822 } 9823 proto.end(actionToken); 9824 } 9825 proto.end(token); 9826 } 9827 9828 long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER); 9829 proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString()); 9830 mHandler.getLooper().dumpDebug(proto, 9831 ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER); 9832 proto.end(handlerToken); 9833 } 9834 dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)9835 void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 9836 int opti, boolean dumpAll, String dumpPackage) { 9837 pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)"); 9838 boolean printed = false; 9839 if (mAllowedAssociations != null) { 9840 for (int i = 0; i < mAllowedAssociations.size(); i++) { 9841 final String pkg = mAllowedAssociations.keyAt(i); 9842 final ArraySet<String> asc = 9843 mAllowedAssociations.valueAt(i).getAllowedPackageAssociations(); 9844 if (!printed) { 9845 pw.println(" Allowed associations (by restricted package):"); 9846 printed = true; 9847 } 9848 pw.print(" * "); 9849 pw.print(pkg); 9850 pw.println(":"); 9851 for (int j = 0; j < asc.size(); j++) { 9852 if (dumpPackage == null || pkg.equals(dumpPackage) 9853 || asc.valueAt(j).equals(dumpPackage)) { 9854 pw.print(" Allow: "); 9855 pw.println(asc.valueAt(j)); 9856 } 9857 } 9858 if (mAllowedAssociations.valueAt(i).isDebuggable()) { 9859 pw.println(" (debuggable)"); 9860 } 9861 } 9862 } 9863 if (!printed) { 9864 pw.println(" (No association restrictions)"); 9865 } 9866 } 9867 dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)9868 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 9869 int opti, boolean dumpAll, String dumpPackage) { 9870 boolean needSep = false; 9871 boolean onlyHistory = false; 9872 boolean printedAnything = false; 9873 9874 if ("history".equals(dumpPackage)) { 9875 if (opti < args.length && "-s".equals(args[opti])) { 9876 dumpAll = false; 9877 } 9878 onlyHistory = true; 9879 dumpPackage = null; 9880 } 9881 9882 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 9883 if (!onlyHistory && dumpAll) { 9884 if (mRegisteredReceivers.size() > 0) { 9885 boolean printed = false; 9886 Iterator it = mRegisteredReceivers.values().iterator(); 9887 while (it.hasNext()) { 9888 ReceiverList r = (ReceiverList)it.next(); 9889 if (dumpPackage != null && (r.app == null || 9890 !dumpPackage.equals(r.app.info.packageName))) { 9891 continue; 9892 } 9893 if (!printed) { 9894 pw.println(" Registered Receivers:"); 9895 needSep = true; 9896 printed = true; 9897 printedAnything = true; 9898 } 9899 pw.print(" * "); pw.println(r); 9900 r.dump(pw, " "); 9901 } 9902 } 9903 9904 if (mReceiverResolver.dump(pw, needSep ? 9905 "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 9906 " ", dumpPackage, false, false)) { 9907 needSep = true; 9908 printedAnything = true; 9909 } 9910 } 9911 9912 for (BroadcastQueue q : mBroadcastQueues) { 9913 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep); 9914 printedAnything |= needSep; 9915 } 9916 9917 needSep = true; 9918 9919 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) { 9920 for (int user=0; user<mStickyBroadcasts.size(); user++) { 9921 if (needSep) { 9922 pw.println(); 9923 } 9924 needSep = true; 9925 printedAnything = true; 9926 pw.print(" Sticky broadcasts for user "); 9927 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":"); 9928 StringBuilder sb = new StringBuilder(128); 9929 for (Map.Entry<String, ArrayList<Intent>> ent 9930 : mStickyBroadcasts.valueAt(user).entrySet()) { 9931 pw.print(" * Sticky action "); pw.print(ent.getKey()); 9932 if (dumpAll) { 9933 pw.println(":"); 9934 ArrayList<Intent> intents = ent.getValue(); 9935 final int N = intents.size(); 9936 for (int i=0; i<N; i++) { 9937 sb.setLength(0); 9938 sb.append(" Intent: "); 9939 intents.get(i).toShortString(sb, false, true, false, false); 9940 pw.println(sb.toString()); 9941 Bundle bundle = intents.get(i).getExtras(); 9942 if (bundle != null) { 9943 pw.print(" "); 9944 pw.println(bundle.toString()); 9945 } 9946 } 9947 } else { 9948 pw.println(""); 9949 } 9950 } 9951 } 9952 } 9953 9954 if (!onlyHistory && dumpAll) { 9955 pw.println(); 9956 for (BroadcastQueue queue : mBroadcastQueues) { 9957 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]=" 9958 + queue.mBroadcastsScheduled); 9959 } 9960 pw.println(" mHandler:"); 9961 mHandler.dump(new PrintWriterPrinter(pw), " "); 9962 needSep = true; 9963 printedAnything = true; 9964 } 9965 9966 if (!printedAnything) { 9967 pw.println(" (nothing)"); 9968 } 9969 } 9970 dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)9971 void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 9972 int opti, boolean dumpAll, String dumpPackage) { 9973 if (mCurBroadcastStats == null) { 9974 return; 9975 } 9976 9977 pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)"); 9978 final long now = SystemClock.elapsedRealtime(); 9979 if (mLastBroadcastStats != null) { 9980 pw.print(" Last stats (from "); 9981 TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw); 9982 pw.print(" to "); 9983 TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw); 9984 pw.print(", "); 9985 TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime 9986 - mLastBroadcastStats.mStartUptime, pw); 9987 pw.println(" uptime):"); 9988 if (!mLastBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 9989 pw.println(" (nothing)"); 9990 } 9991 pw.println(); 9992 } 9993 pw.print(" Current stats (from "); 9994 TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw); 9995 pw.print(" to now, "); 9996 TimeUtils.formatDuration(SystemClock.uptimeMillis() 9997 - mCurBroadcastStats.mStartUptime, pw); 9998 pw.println(" uptime):"); 9999 if (!mCurBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 10000 pw.println(" (nothing)"); 10001 } 10002 } 10003 dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)10004 void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, 10005 int opti, boolean fullCheckin, String dumpPackage) { 10006 if (mCurBroadcastStats == null) { 10007 return; 10008 } 10009 10010 if (mLastBroadcastStats != null) { 10011 mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage); 10012 if (fullCheckin) { 10013 mLastBroadcastStats = null; 10014 return; 10015 } 10016 } 10017 mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage); 10018 if (fullCheckin) { 10019 mCurBroadcastStats = null; 10020 } 10021 } 10022 dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)10023 void dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, 10024 int opti, boolean dumpAll, String dumpPackage) { 10025 10026 pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)"); 10027 10028 mUgmInternal.dump(pw, dumpAll, dumpPackage); 10029 } 10030 dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)10031 private static int dumpProcessList(PrintWriter pw, 10032 ActivityManagerService service, List list, 10033 String prefix, String normalLabel, String persistentLabel, 10034 String dumpPackage) { 10035 int numPers = 0; 10036 for (int i = list.size() - 1; i >= 0; i--) { 10037 ProcessRecord r = (ProcessRecord) list.get(i); 10038 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 10039 continue; 10040 } 10041 pw.println(String.format("%s%s #%2d: %s", 10042 prefix, (r.isPersistent() ? persistentLabel : normalLabel), 10043 i, r.toString())); 10044 if (r.isPersistent()) { 10045 numPers++; 10046 } 10047 } 10048 return numPers; 10049 } 10050 collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)10051 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs, 10052 String[] args) { 10053 synchronized (mProcLock) { 10054 return mProcessList.collectProcessesLOSP(start, allPkgs, args); 10055 } 10056 } 10057 dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)10058 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 10059 PrintWriter pw, String[] args) { 10060 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 10061 if (procs == null) { 10062 pw.println("No process found for: " + args[0]); 10063 return; 10064 } 10065 10066 long uptime = SystemClock.uptimeMillis(); 10067 long realtime = SystemClock.elapsedRealtime(); 10068 pw.println("Applications Graphics Acceleration Info:"); 10069 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 10070 10071 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 10072 ProcessRecord r = procs.get(i); 10073 final int pid = r.getPid(); 10074 final IApplicationThread thread = r.getThread(); 10075 if (thread != null) { 10076 pw.println("\n** Graphics info for pid " + pid + " [" + r.processName + "] **"); 10077 pw.flush(); 10078 try { 10079 TransferPipe tp = new TransferPipe(); 10080 try { 10081 thread.dumpGfxInfo(tp.getWriteFd(), args); 10082 tp.go(fd); 10083 } finally { 10084 tp.kill(); 10085 } 10086 } catch (IOException e) { 10087 pw.println("Failure while dumping the app: " + r); 10088 pw.flush(); 10089 } catch (RemoteException e) { 10090 pw.println("Got a RemoteException while dumping the app " + r); 10091 pw.flush(); 10092 } 10093 } 10094 } 10095 } 10096 dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args)10097 final void dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args) { 10098 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 10099 if (procs == null) { 10100 pw.println("No process found for: " + args[0]); 10101 return; 10102 } 10103 10104 pw.println("Per-process Binder Cache Contents"); 10105 10106 for (int i = procs.size() - 1; i >= 0; i--) { 10107 ProcessRecord r = procs.get(i); 10108 final int pid = r.getPid(); 10109 final IApplicationThread thread = r.getThread(); 10110 if (thread != null) { 10111 pw.println("\n\n** Cache info for pid " + pid + " [" + r.processName + "] **"); 10112 pw.flush(); 10113 if (pid == MY_PID) { 10114 PropertyInvalidatedCache.dumpCacheInfo(fd, args); 10115 continue; 10116 } 10117 try { 10118 TransferPipe tp = new TransferPipe(); 10119 try { 10120 thread.dumpCacheInfo(tp.getWriteFd(), args); 10121 tp.go(fd); 10122 } finally { 10123 tp.kill(); 10124 } 10125 } catch (IOException e) { 10126 pw.println("Failure while dumping the app " + r); 10127 pw.flush(); 10128 } catch (RemoteException e) { 10129 pw.println("Got a RemoteException while dumping the app " + r); 10130 pw.flush(); 10131 } 10132 } 10133 } 10134 } 10135 dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)10136 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 10137 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 10138 if (procs == null) { 10139 pw.println("No process found for: " + args[0]); 10140 return; 10141 } 10142 10143 pw.println("Applications Database Info:"); 10144 10145 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 10146 ProcessRecord r = procs.get(i); 10147 final int pid = r.getPid(); 10148 final IApplicationThread thread = r.getThread(); 10149 if (thread != null) { 10150 pw.println("\n** Database info for pid " + pid + " [" + r.processName + "] **"); 10151 pw.flush(); 10152 try { 10153 TransferPipe tp = new TransferPipe(); 10154 try { 10155 thread.dumpDbInfo(tp.getWriteFd(), args); 10156 tp.go(fd); 10157 } finally { 10158 tp.kill(); 10159 } 10160 } catch (IOException e) { 10161 pw.println("Failure while dumping the app: " + r); 10162 pw.flush(); 10163 } catch (RemoteException e) { 10164 pw.println("Got a RemoteException while dumping the app " + r); 10165 pw.flush(); 10166 } 10167 } 10168 } 10169 } 10170 10171 final static class MemItem { 10172 final boolean isProc; 10173 final String label; 10174 final String shortLabel; 10175 final long pss; 10176 final long swapPss; 10177 final long mRss; 10178 final int id; 10179 final boolean hasActivities; 10180 ArrayList<MemItem> subitems; 10181 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id, boolean hasActivities)10182 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id, 10183 boolean hasActivities) { 10184 this.isProc = true; 10185 this.label = label; 10186 this.shortLabel = shortLabel; 10187 this.pss = pss; 10188 this.swapPss = swapPss; 10189 this.mRss = rss; 10190 this.id = id; 10191 this.hasActivities = hasActivities; 10192 } 10193 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id)10194 MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id) { 10195 this.isProc = false; 10196 this.label = label; 10197 this.shortLabel = shortLabel; 10198 this.pss = pss; 10199 this.swapPss = swapPss; 10200 this.mRss = rss; 10201 this.id = id; 10202 this.hasActivities = false; 10203 } 10204 } 10205 sortMemItems(List<MemItem> items, final boolean pss)10206 private static void sortMemItems(List<MemItem> items, final boolean pss) { 10207 Collections.sort(items, new Comparator<MemItem>() { 10208 @Override 10209 public int compare(MemItem lhs, MemItem rhs) { 10210 long lss = pss ? lhs.pss : lhs.mRss; 10211 long rss = pss ? rhs.pss : rhs.mRss; 10212 if (lss < rss) { 10213 return 1; 10214 } else if (lss > rss) { 10215 return -1; 10216 } 10217 return 0; 10218 } 10219 }); 10220 } 10221 dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, boolean dumpSwapPss)10222 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 10223 ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, 10224 boolean dumpSwapPss) { 10225 if (sort && !isCompact) { 10226 sortMemItems(items, dumpPss); 10227 } 10228 10229 for (int i=0; i<items.size(); i++) { 10230 MemItem mi = items.get(i); 10231 if (!isCompact) { 10232 if (dumpPss && dumpSwapPss) { 10233 pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss), 10234 mi.label, stringifyKBSize(mi.swapPss)); 10235 } else { 10236 pw.printf("%s%s: %s\n", prefix, stringifyKBSize(dumpPss ? mi.pss : mi.mRss), 10237 mi.label); 10238 } 10239 } else if (mi.isProc) { 10240 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 10241 pw.print(","); pw.print(mi.id); pw.print(","); 10242 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(","); 10243 pw.print(dumpSwapPss ? mi.swapPss : "N/A"); 10244 pw.println(mi.hasActivities ? ",a" : ",e"); 10245 } else { 10246 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 10247 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(","); 10248 pw.println(dumpSwapPss ? mi.swapPss : "N/A"); 10249 } 10250 if (mi.subitems != null) { 10251 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 10252 true, isCompact, dumpPss, dumpSwapPss); 10253 } 10254 } 10255 } 10256 dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss)10257 static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, 10258 ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss) { 10259 if (sort) { 10260 sortMemItems(items, dumpPss); 10261 } 10262 10263 for (int i=0; i<items.size(); i++) { 10264 MemItem mi = items.get(i); 10265 final long token = proto.start(fieldId); 10266 10267 proto.write(MemInfoDumpProto.MemItem.TAG, tag); 10268 proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel); 10269 proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc); 10270 proto.write(MemInfoDumpProto.MemItem.ID, mi.id); 10271 proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities); 10272 proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss); 10273 proto.write(MemInfoDumpProto.MemItem.RSS_KB, mi.mRss); 10274 if (dumpSwapPss) { 10275 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss); 10276 } 10277 if (mi.subitems != null) { 10278 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems, 10279 true, dumpPss, dumpSwapPss); 10280 } 10281 proto.end(token); 10282 } 10283 } 10284 10285 // These are in KB. 10286 static final long[] DUMP_MEM_BUCKETS = new long[] { 10287 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 10288 120*1024, 160*1024, 200*1024, 10289 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 10290 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 10291 }; 10292 appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)10293 static final void appendMemBucket(StringBuilder out, long memKB, String label, 10294 boolean stackLike) { 10295 int start = label.lastIndexOf('.'); 10296 if (start >= 0) start++; 10297 else start = 0; 10298 int end = label.length(); 10299 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 10300 if (DUMP_MEM_BUCKETS[i] >= memKB) { 10301 long bucket = DUMP_MEM_BUCKETS[i]/1024; 10302 out.append(bucket); 10303 out.append(stackLike ? "MB." : "MB "); 10304 out.append(label, start, end); 10305 return; 10306 } 10307 } 10308 out.append(memKB/1024); 10309 out.append(stackLike ? "MB." : "MB "); 10310 out.append(label, start, end); 10311 } 10312 10313 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 10314 ProcessList.NATIVE_ADJ, 10315 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, 10316 ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ, 10317 ProcessList.VISIBLE_APP_ADJ, 10318 ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ, 10319 ProcessList.PERCEPTIBLE_MEDIUM_APP_ADJ, 10320 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 10321 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 10322 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ 10323 }; 10324 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 10325 "Native", 10326 "System", "Persistent", "Persistent Service", "Foreground", 10327 "Visible", "Perceptible", "Perceptible Low", "Perceptible Medium", 10328 "Heavy Weight", "Backup", 10329 "A Services", "Home", 10330 "Previous", "B Services", "Cached" 10331 }; 10332 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 10333 "native", 10334 "sys", "pers", "persvc", "fore", 10335 "vis", "percept", "perceptl", "perceptm", 10336 "heavy", "backup", 10337 "servicea", "home", 10338 "prev", "serviceb", "cached" 10339 }; 10340 dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)10341 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 10342 long realtime, boolean isCheckinRequest, boolean isCompact) { 10343 if (isCompact) { 10344 pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION); 10345 } 10346 if (isCheckinRequest || isCompact) { 10347 // short checkin version 10348 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 10349 } else { 10350 pw.println("Applications Memory Usage (in Kilobytes):"); 10351 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 10352 } 10353 } 10354 10355 static final int KSM_SHARED = 0; 10356 static final int KSM_SHARING = 1; 10357 static final int KSM_UNSHARED = 2; 10358 static final int KSM_VOLATILE = 3; 10359 getKsmInfo()10360 static final long[] getKsmInfo() { 10361 long[] longOut = new long[4]; 10362 final int[] SINGLE_LONG_FORMAT = new int[] { 10363 PROC_SPACE_TERM| PROC_OUT_LONG 10364 }; 10365 long[] longTmp = new long[1]; 10366 readProcFile("/sys/kernel/mm/ksm/pages_shared", 10367 SINGLE_LONG_FORMAT, null, longTmp, null); 10368 longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 10369 longTmp[0] = 0; 10370 readProcFile("/sys/kernel/mm/ksm/pages_sharing", 10371 SINGLE_LONG_FORMAT, null, longTmp, null); 10372 longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 10373 longTmp[0] = 0; 10374 readProcFile("/sys/kernel/mm/ksm/pages_unshared", 10375 SINGLE_LONG_FORMAT, null, longTmp, null); 10376 longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 10377 longTmp[0] = 0; 10378 readProcFile("/sys/kernel/mm/ksm/pages_volatile", 10379 SINGLE_LONG_FORMAT, null, longTmp, null); 10380 longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 10381 return longOut; 10382 } 10383 stringifySize(long size, int order)10384 static String stringifySize(long size, int order) { 10385 Locale locale = Locale.US; 10386 switch (order) { 10387 case 1: 10388 return String.format(locale, "%,13d", size); 10389 case 1024: 10390 return String.format(locale, "%,9dK", size / 1024); 10391 case 1024 * 1024: 10392 return String.format(locale, "%,5dM", size / 1024 / 1024); 10393 case 1024 * 1024 * 1024: 10394 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024); 10395 default: 10396 throw new IllegalArgumentException("Invalid size order"); 10397 } 10398 } 10399 stringifyKBSize(long size)10400 static String stringifyKBSize(long size) { 10401 return stringifySize(size * 1024, 1024); 10402 } 10403 10404 // Update this version number if you change the 'compact' format. 10405 private static final int MEMINFO_COMPACT_VERSION = 1; 10406 10407 private static class MemoryUsageDumpOptions { 10408 boolean dumpDetails; 10409 boolean dumpFullDetails; 10410 boolean dumpDalvik; 10411 boolean dumpSummaryOnly; 10412 boolean dumpUnreachable; 10413 boolean oomOnly; 10414 boolean isCompact; 10415 boolean localOnly; 10416 boolean packages; 10417 boolean isCheckinRequest; 10418 boolean dumpSwapPss; 10419 boolean dumpProto; 10420 } 10421 dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)10422 final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 10423 String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) { 10424 MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions(); 10425 opts.dumpDetails = false; 10426 opts.dumpFullDetails = false; 10427 opts.dumpDalvik = false; 10428 opts.dumpSummaryOnly = false; 10429 opts.dumpUnreachable = false; 10430 opts.oomOnly = false; 10431 opts.isCompact = false; 10432 opts.localOnly = false; 10433 opts.packages = false; 10434 opts.isCheckinRequest = false; 10435 opts.dumpSwapPss = false; 10436 opts.dumpProto = asProto; 10437 10438 int opti = 0; 10439 while (opti < args.length) { 10440 String opt = args[opti]; 10441 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 10442 break; 10443 } 10444 opti++; 10445 if ("-a".equals(opt)) { 10446 opts.dumpDetails = true; 10447 opts.dumpFullDetails = true; 10448 opts.dumpDalvik = true; 10449 opts.dumpSwapPss = true; 10450 } else if ("-d".equals(opt)) { 10451 opts.dumpDalvik = true; 10452 } else if ("-c".equals(opt)) { 10453 opts.isCompact = true; 10454 } else if ("-s".equals(opt)) { 10455 opts.dumpDetails = true; 10456 opts.dumpSummaryOnly = true; 10457 } else if ("-S".equals(opt)) { 10458 opts.dumpSwapPss = true; 10459 } else if ("--unreachable".equals(opt)) { 10460 opts.dumpUnreachable = true; 10461 } else if ("--oom".equals(opt)) { 10462 opts.oomOnly = true; 10463 } else if ("--local".equals(opt)) { 10464 opts.localOnly = true; 10465 } else if ("--package".equals(opt)) { 10466 opts.packages = true; 10467 } else if ("--checkin".equals(opt)) { 10468 opts.isCheckinRequest = true; 10469 } else if ("--proto".equals(opt)) { 10470 opts.dumpProto = true; 10471 10472 } else if ("-h".equals(opt)) { 10473 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]"); 10474 pw.println(" -a: include all available information for each process."); 10475 pw.println(" -d: include dalvik details."); 10476 pw.println(" -c: dump in a compact machine-parseable representation."); 10477 pw.println(" -s: dump only summary of application memory usage."); 10478 pw.println(" -S: dump also SwapPss."); 10479 pw.println(" --oom: only show processes organized by oom adj."); 10480 pw.println(" --local: only collect details locally, don't call process."); 10481 pw.println(" --package: interpret process arg as package, dumping all"); 10482 pw.println(" processes that have loaded that package."); 10483 pw.println(" --checkin: dump data for a checkin"); 10484 pw.println(" --proto: dump data to proto"); 10485 pw.println("If [process] is specified it can be the name or "); 10486 pw.println("pid of a specific process to dump."); 10487 return; 10488 } else { 10489 pw.println("Unknown argument: " + opt + "; use -h for help"); 10490 } 10491 } 10492 10493 String[] innerArgs = new String[args.length-opti]; 10494 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 10495 10496 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args); 10497 if (opts.dumpProto) { 10498 dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs); 10499 } else { 10500 dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw); 10501 } 10502 } 10503 dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs, PrintWriter categoryPw)10504 private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, 10505 MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, 10506 ArrayList<ProcessRecord> procs, PrintWriter categoryPw) { 10507 long uptime = SystemClock.uptimeMillis(); 10508 long realtime = SystemClock.elapsedRealtime(); 10509 final long[] tmpLong = new long[3]; 10510 10511 if (procs == null) { 10512 // No Java processes. Maybe they want to print a native process. 10513 String proc = "N/A"; 10514 if (innerArgs.length > 0) { 10515 proc = innerArgs[0]; 10516 if (proc.charAt(0) != '-') { 10517 ArrayList<ProcessCpuTracker.Stats> nativeProcs 10518 = new ArrayList<ProcessCpuTracker.Stats>(); 10519 updateCpuStatsNow(); 10520 int findPid = -1; 10521 try { 10522 findPid = Integer.parseInt(innerArgs[0]); 10523 } catch (NumberFormatException e) { 10524 } 10525 final int fFindPid = findPid; 10526 mAppProfiler.forAllCpuStats((st) -> { 10527 if (st.pid == fFindPid || (st.baseName != null 10528 && st.baseName.equals(innerArgs[0]))) { 10529 nativeProcs.add(st); 10530 } 10531 }); 10532 if (nativeProcs.size() > 0) { 10533 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, 10534 opts.isCheckinRequest, opts.isCompact); 10535 Debug.MemoryInfo mi = null; 10536 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 10537 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 10538 final int pid = r.pid; 10539 if (mi == null) { 10540 mi = new Debug.MemoryInfo(); 10541 } 10542 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 10543 if (!Debug.getMemoryInfo(pid, mi)) { 10544 continue; 10545 } 10546 } else { 10547 long pss = Debug.getPss(pid, tmpLong, null); 10548 if (pss == 0) { 10549 continue; 10550 } 10551 mi.nativePss = (int) pss; 10552 mi.nativePrivateDirty = (int) tmpLong[0]; 10553 mi.nativeRss = (int) tmpLong[2]; 10554 } 10555 if (!opts.isCheckinRequest && opts.dumpDetails) { 10556 pw.println("\n** MEMINFO in pid " + pid + " [" 10557 + r.baseName + "] **"); 10558 } 10559 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, 10560 opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 10561 pid, r.baseName, 0, 0, 0, 0, 0, 0); 10562 if (opts.isCheckinRequest) { 10563 pw.println(); 10564 } 10565 } 10566 return; 10567 } 10568 } 10569 } 10570 pw.println("No process found for: " + proc); 10571 return; 10572 } 10573 10574 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 10575 opts.dumpDetails = true; 10576 } 10577 final int numProcs = procs.size(); 10578 final boolean collectNative = !opts.isCheckinRequest && numProcs > 1 && !opts.packages; 10579 if (collectNative) { 10580 // If we are showing aggregations, also look for native processes to 10581 // include so that our aggregations are more accurate. 10582 updateCpuStatsNow(); 10583 } 10584 10585 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact); 10586 10587 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 10588 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 10589 final long[] ss = new long[INDEX_LAST]; 10590 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 10591 EmptyArray.LONG; 10592 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 10593 EmptyArray.LONG; 10594 long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 10595 EmptyArray.LONG; 10596 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 10597 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 10598 long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 10599 long[] memtrackTmp = new long[4]; 10600 10601 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 10602 long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 10603 long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length]; 10604 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 10605 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 10606 10607 long totalSwapPss = 0; 10608 long totalRss = 0; 10609 long cachedPss = 0; 10610 long cachedSwapPss = 0; 10611 boolean hasSwapPss = false; 10612 10613 Debug.MemoryInfo mi = null; 10614 for (int i = numProcs - 1; i >= 0; i--) { 10615 final ProcessRecord r = procs.get(i); 10616 final IApplicationThread thread; 10617 final int pid; 10618 final int oomAdj; 10619 final boolean hasActivities; 10620 synchronized (mProcLock) { 10621 thread = r.getThread(); 10622 pid = r.getPid(); 10623 oomAdj = r.mState.getSetAdjWithServices(); 10624 hasActivities = r.hasActivities(); 10625 } 10626 if (thread != null) { 10627 if (mi == null) { 10628 mi = new Debug.MemoryInfo(); 10629 } 10630 final int reportType; 10631 final long startTime; 10632 final long endTime; 10633 long memtrackGraphics = 0; 10634 long memtrackGl = 0; 10635 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 10636 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 10637 startTime = SystemClock.currentThreadTimeMillis(); 10638 if (!Debug.getMemoryInfo(pid, mi)) { 10639 continue; 10640 } 10641 endTime = SystemClock.currentThreadTimeMillis(); 10642 hasSwapPss = mi.hasSwappedOutPss; 10643 memtrackGraphics = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS); 10644 memtrackGl = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GL); 10645 } else { 10646 reportType = ProcessStats.ADD_PSS_EXTERNAL; 10647 startTime = SystemClock.currentThreadTimeMillis(); 10648 long pss = Debug.getPss(pid, tmpLong, memtrackTmp); 10649 if (pss == 0) { 10650 continue; 10651 } 10652 mi.dalvikPss = (int) pss; 10653 endTime = SystemClock.currentThreadTimeMillis(); 10654 mi.dalvikPrivateDirty = (int) tmpLong[0]; 10655 mi.dalvikRss = (int) tmpLong[2]; 10656 memtrackGraphics = memtrackTmp[1]; 10657 memtrackGl = memtrackTmp[2]; 10658 } 10659 if (!opts.isCheckinRequest && opts.dumpDetails) { 10660 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 10661 } 10662 if (opts.dumpDetails) { 10663 if (opts.localOnly) { 10664 ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails, 10665 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0); 10666 if (opts.isCheckinRequest) { 10667 pw.println(); 10668 } 10669 } else { 10670 pw.flush(); 10671 try { 10672 TransferPipe tp = new TransferPipe(); 10673 try { 10674 thread.dumpMemInfo(tp.getWriteFd(), 10675 mi, opts.isCheckinRequest, opts.dumpFullDetails, 10676 opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs); 10677 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000); 10678 } finally { 10679 tp.kill(); 10680 } 10681 } catch (IOException e) { 10682 if (!opts.isCheckinRequest) { 10683 pw.println("Got IoException! " + e); 10684 pw.flush(); 10685 } 10686 } catch (RemoteException e) { 10687 if (!opts.isCheckinRequest) { 10688 pw.println("Got RemoteException! " + e); 10689 pw.flush(); 10690 } 10691 } 10692 } 10693 } 10694 10695 final long myTotalPss = mi.getTotalPss(); 10696 final long myTotalUss = mi.getTotalUss(); 10697 final long myTotalRss = mi.getTotalRss(); 10698 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 10699 10700 synchronized (mProcLock) { 10701 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) { 10702 // Record this for posterity if the process has been stable. 10703 r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true, 10704 reportType, endTime - startTime); 10705 r.getPkgList().forEachPackageProcessStats(holder -> { 10706 FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED, 10707 r.info.uid, 10708 holder.state.getName(), 10709 holder.state.getPackage(), 10710 myTotalPss, myTotalUss, myTotalRss, reportType, 10711 endTime-startTime, 10712 holder.appVersion); 10713 }); 10714 } 10715 } 10716 10717 if (!opts.isCheckinRequest && mi != null) { 10718 ss[INDEX_TOTAL_PSS] += myTotalPss; 10719 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 10720 ss[INDEX_TOTAL_RSS] += myTotalRss; 10721 ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics; 10722 ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl; 10723 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 10724 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 10725 myTotalSwapPss, myTotalRss, pid, hasActivities); 10726 procMems.add(pssItem); 10727 procMemsMap.put(pid, pssItem); 10728 10729 ss[INDEX_NATIVE_PSS] += mi.nativePss; 10730 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss; 10731 ss[INDEX_NATIVE_RSS] += mi.nativeRss; 10732 ss[INDEX_DALVIK_PSS] += mi.dalvikPss; 10733 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss; 10734 ss[INDEX_DALVIK_RSS] += mi.dalvikRss; 10735 for (int j=0; j<dalvikSubitemPss.length; j++) { 10736 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 10737 dalvikSubitemSwapPss[j] += 10738 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 10739 dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 10740 } 10741 ss[INDEX_OTHER_PSS] += mi.otherPss; 10742 ss[INDEX_OTHER_RSS] += mi.otherRss; 10743 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss; 10744 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 10745 long mem = mi.getOtherPss(j); 10746 miscPss[j] += mem; 10747 ss[INDEX_OTHER_PSS] -= mem; 10748 mem = mi.getOtherSwappedOutPss(j); 10749 miscSwapPss[j] += mem; 10750 ss[INDEX_OTHER_SWAP_PSS] -= mem; 10751 mem = mi.getOtherRss(j); 10752 miscRss[j] += mem; 10753 ss[INDEX_OTHER_RSS] -= mem; 10754 } 10755 10756 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 10757 cachedPss += myTotalPss; 10758 cachedSwapPss += myTotalSwapPss; 10759 } 10760 10761 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 10762 if (oomIndex == (oomPss.length - 1) 10763 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 10764 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 10765 oomPss[oomIndex] += myTotalPss; 10766 oomSwapPss[oomIndex] += myTotalSwapPss; 10767 if (oomProcs[oomIndex] == null) { 10768 oomProcs[oomIndex] = new ArrayList<MemItem>(); 10769 } 10770 oomProcs[oomIndex].add(pssItem); 10771 oomRss[oomIndex] += myTotalRss; 10772 break; 10773 } 10774 } 10775 } 10776 } 10777 } 10778 10779 long nativeProcTotalPss = 0; 10780 10781 if (collectNative) { 10782 mi = null; 10783 final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1]; 10784 mAppProfiler.forAllCpuStats((st) -> { 10785 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 10786 long memtrackGraphics = 0; 10787 long memtrackGl = 0; 10788 if (memInfos[0] == null) { 10789 memInfos[0] = new Debug.MemoryInfo(); 10790 } 10791 final Debug.MemoryInfo info = memInfos[0]; 10792 if (!brief && !opts.oomOnly) { 10793 if (!Debug.getMemoryInfo(st.pid, info)) { 10794 return; 10795 } 10796 memtrackGraphics = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS); 10797 memtrackGl = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GL); 10798 } else { 10799 long pss = Debug.getPss(st.pid, tmpLong, memtrackTmp); 10800 if (pss == 0) { 10801 return; 10802 } 10803 info.nativePss = (int) pss; 10804 info.nativePrivateDirty = (int) tmpLong[0]; 10805 info.nativeRss = (int) tmpLong[2]; 10806 memtrackGraphics = memtrackTmp[1]; 10807 memtrackGl = memtrackTmp[2]; 10808 } 10809 10810 final long myTotalPss = info.getTotalPss(); 10811 final long myTotalSwapPss = info.getTotalSwappedOutPss(); 10812 final long myTotalRss = info.getTotalRss(); 10813 ss[INDEX_TOTAL_PSS] += myTotalPss; 10814 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 10815 ss[INDEX_TOTAL_RSS] += myTotalRss; 10816 ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss; 10817 ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics; 10818 ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl; 10819 10820 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 10821 st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss, 10822 st.pid, false); 10823 procMems.add(pssItem); 10824 10825 ss[INDEX_NATIVE_PSS] += info.nativePss; 10826 ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss; 10827 ss[INDEX_NATIVE_RSS] += info.nativeRss; 10828 ss[INDEX_DALVIK_PSS] += info.dalvikPss; 10829 ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss; 10830 ss[INDEX_DALVIK_RSS] += info.dalvikRss; 10831 for (int j = 0; j < dalvikSubitemPss.length; j++) { 10832 dalvikSubitemPss[j] += info.getOtherPss( 10833 Debug.MemoryInfo.NUM_OTHER_STATS + j); 10834 dalvikSubitemSwapPss[j] += 10835 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 10836 dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS 10837 + j); 10838 } 10839 ss[INDEX_OTHER_PSS] += info.otherPss; 10840 ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss; 10841 ss[INDEX_OTHER_RSS] += info.otherRss; 10842 for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 10843 long mem = info.getOtherPss(j); 10844 miscPss[j] += mem; 10845 ss[INDEX_OTHER_PSS] -= mem; 10846 mem = info.getOtherSwappedOutPss(j); 10847 miscSwapPss[j] += mem; 10848 ss[INDEX_OTHER_SWAP_PSS] -= mem; 10849 mem = info.getOtherRss(j); 10850 miscRss[j] += mem; 10851 ss[INDEX_OTHER_RSS] -= mem; 10852 } 10853 oomPss[0] += myTotalPss; 10854 oomSwapPss[0] += myTotalSwapPss; 10855 if (oomProcs[0] == null) { 10856 oomProcs[0] = new ArrayList<MemItem>(); 10857 } 10858 oomProcs[0].add(pssItem); 10859 oomRss[0] += myTotalRss; 10860 } 10861 }); 10862 10863 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 10864 10865 catMems.add(new MemItem("Native", "Native", 10866 ss[INDEX_NATIVE_PSS], ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1)); 10867 final int dalvikId = -2; 10868 catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS], 10869 ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId)); 10870 catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS], 10871 ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3)); 10872 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 10873 String label = Debug.MemoryInfo.getOtherLabel(j); 10874 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], j)); 10875 } 10876 if (dalvikSubitemPss.length > 0) { 10877 // Add dalvik subitems. 10878 for (MemItem memItem : catMems) { 10879 int memItemStart = 0, memItemEnd = 0; 10880 if (memItem.id == dalvikId) { 10881 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 10882 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 10883 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 10884 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 10885 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 10886 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 10887 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 10888 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 10889 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 10890 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 10891 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 10892 } else { 10893 continue; // No subitems, continue. 10894 } 10895 memItem.subitems = new ArrayList<MemItem>(); 10896 for (int j=memItemStart; j<=memItemEnd; j++) { 10897 final String name = Debug.MemoryInfo.getOtherLabel( 10898 Debug.MemoryInfo.NUM_OTHER_STATS + j); 10899 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 10900 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j)); 10901 } 10902 } 10903 } 10904 10905 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 10906 for (int j=0; j<oomPss.length; j++) { 10907 if (oomPss[j] != 0) { 10908 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 10909 : DUMP_MEM_OOM_LABEL[j]; 10910 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j], 10911 DUMP_MEM_OOM_ADJ[j]); 10912 item.subitems = oomProcs[j]; 10913 oomMems.add(item); 10914 } 10915 } 10916 if (!opts.isCompact) { 10917 pw.println(); 10918 } 10919 if (!brief && !opts.oomOnly && !opts.isCompact) { 10920 pw.println(); 10921 pw.println("Total RSS by process:"); 10922 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, false, false); 10923 pw.println(); 10924 } 10925 if (!opts.isCompact) { 10926 pw.println("Total RSS by OOM adjustment:"); 10927 } 10928 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, false, false); 10929 if (!brief && !opts.oomOnly) { 10930 PrintWriter out = categoryPw != null ? categoryPw : pw; 10931 if (!opts.isCompact) { 10932 out.println(); 10933 out.println("Total RSS by category:"); 10934 } 10935 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, false, false); 10936 } 10937 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0; 10938 if (!brief && !opts.oomOnly && !opts.isCompact) { 10939 pw.println(); 10940 pw.println("Total PSS by process:"); 10941 dumpMemItems(pw, " ", "proc", procMems, true, opts.isCompact, true, 10942 opts.dumpSwapPss); 10943 pw.println(); 10944 } 10945 if (!opts.isCompact) { 10946 pw.println("Total PSS by OOM adjustment:"); 10947 } 10948 dumpMemItems(pw, " ", "oom", oomMems, false, opts.isCompact, true, opts.dumpSwapPss); 10949 if (!brief && !opts.oomOnly) { 10950 PrintWriter out = categoryPw != null ? categoryPw : pw; 10951 if (!opts.isCompact) { 10952 out.println(); 10953 out.println("Total PSS by category:"); 10954 } 10955 dumpMemItems(out, " ", "cat", catMems, true, opts.isCompact, true, 10956 opts.dumpSwapPss); 10957 } 10958 if (!opts.isCompact) { 10959 pw.println(); 10960 } 10961 MemInfoReader memInfo = new MemInfoReader(); 10962 memInfo.readMemInfo(); 10963 if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) { 10964 synchronized (mProcessStats.mLock) { 10965 final long cachedKb = memInfo.getCachedSizeKb(); 10966 final long freeKb = memInfo.getFreeSizeKb(); 10967 final long zramKb = memInfo.getZramTotalSizeKb(); 10968 final long kernelKb = memInfo.getKernelUsedSizeKb(); 10969 EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, 10970 kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024); 10971 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 10972 ss[INDEX_TOTAL_NATIVE_PSS]); 10973 } 10974 } 10975 if (!brief) { 10976 if (!opts.isCompact) { 10977 pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb())); 10978 pw.print(" (status "); 10979 mAppProfiler.dumpLastMemoryLevelLocked(pw); 10980 pw.print(" Free RAM: "); 10981 pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb() 10982 + memInfo.getFreeSizeKb())); 10983 pw.print(" ("); 10984 pw.print(stringifyKBSize(cachedPss)); 10985 pw.print(" cached pss + "); 10986 pw.print(stringifyKBSize(memInfo.getCachedSizeKb())); 10987 pw.print(" cached kernel + "); 10988 pw.print(stringifyKBSize(memInfo.getFreeSizeKb())); 10989 pw.println(" free)"); 10990 } else { 10991 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 10992 pw.print(cachedPss + memInfo.getCachedSizeKb() 10993 + memInfo.getFreeSizeKb()); pw.print(","); 10994 pw.println(ss[INDEX_TOTAL_PSS] - cachedPss); 10995 } 10996 } 10997 long kernelUsed = memInfo.getKernelUsedSizeKb(); 10998 final long ionHeap = Debug.getIonHeapsSizeKb(); 10999 final long ionPool = Debug.getIonPoolsSizeKb(); 11000 final long dmabufMapped = Debug.getDmabufMappedSizeKb(); 11001 if (ionHeap >= 0 && ionPool >= 0) { 11002 final long ionUnmapped = ionHeap - dmabufMapped; 11003 pw.print(" ION: "); 11004 pw.print(stringifyKBSize(ionHeap + ionPool)); 11005 pw.print(" ("); 11006 pw.print(stringifyKBSize(dmabufMapped)); 11007 pw.print(" mapped + "); 11008 pw.print(stringifyKBSize(ionUnmapped)); 11009 pw.print(" unmapped + "); 11010 pw.print(stringifyKBSize(ionPool)); 11011 pw.println(" pools)"); 11012 kernelUsed += ionUnmapped; 11013 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being 11014 // set on ION VMAs, however it might be included by the memtrack HAL. 11015 // Replace memtrack HAL reported Graphics category with mapped dmabufs 11016 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS]; 11017 ss[INDEX_TOTAL_PSS] += dmabufMapped; 11018 } else { 11019 final long totalExportedDmabuf = Debug.getDmabufTotalExportedKb(); 11020 if (totalExportedDmabuf >= 0) { 11021 final long dmabufUnmapped = totalExportedDmabuf - dmabufMapped; 11022 pw.print("DMA-BUF: "); 11023 pw.print(stringifyKBSize(totalExportedDmabuf)); 11024 pw.print(" ("); 11025 pw.print(stringifyKBSize(dmabufMapped)); 11026 pw.print(" mapped + "); 11027 pw.print(stringifyKBSize(dmabufUnmapped)); 11028 pw.println(" unmapped)"); 11029 // Account unmapped dmabufs as part of kernel memory allocations 11030 kernelUsed += dmabufUnmapped; 11031 // Replace memtrack HAL reported Graphics category with mapped dmabufs 11032 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS]; 11033 ss[INDEX_TOTAL_PSS] += dmabufMapped; 11034 } 11035 11036 // totalDmabufHeapExported is included in totalExportedDmabuf above and hence do not 11037 // need to be added to kernelUsed. 11038 final long totalDmabufHeapExported = Debug.getDmabufHeapTotalExportedKb(); 11039 if (totalDmabufHeapExported >= 0) { 11040 pw.print("DMA-BUF Heaps: "); 11041 pw.println(stringifyKBSize(totalDmabufHeapExported)); 11042 } 11043 11044 final long totalDmabufHeapPool = Debug.getDmabufHeapPoolsSizeKb(); 11045 if (totalDmabufHeapPool >= 0) { 11046 pw.print("DMA-BUF Heaps pool: "); 11047 pw.println(stringifyKBSize(totalDmabufHeapPool)); 11048 } 11049 } 11050 final long gpuUsage = Debug.getGpuTotalUsageKb(); 11051 if (gpuUsage >= 0) { 11052 final long gpuPrivateUsage = Debug.getGpuPrivateMemoryKb(); 11053 if (gpuPrivateUsage >= 0) { 11054 final long gpuDmaBufUsage = gpuUsage - gpuPrivateUsage; 11055 pw.print(" GPU: "); 11056 pw.print(stringifyKBSize(gpuUsage)); 11057 pw.print(" ("); 11058 pw.print(stringifyKBSize(gpuDmaBufUsage)); 11059 pw.print(" dmabuf + "); 11060 pw.print(stringifyKBSize(gpuPrivateUsage)); 11061 pw.println(" private)"); 11062 // Replace memtrack HAL reported GL category with private GPU allocations and 11063 // account it as part of kernel memory allocations 11064 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GL]; 11065 kernelUsed += gpuPrivateUsage; 11066 } else { 11067 pw.print(" GPU: "); pw.println(stringifyKBSize(gpuUsage)); 11068 } 11069 } 11070 11071 // Note: ION/DMA-BUF heap pools are reclaimable and hence, they are included as part of 11072 // memInfo.getCachedSizeKb(). 11073 final long lostRAM = memInfo.getTotalSizeKb() 11074 - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS]) 11075 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 11076 - kernelUsed - memInfo.getZramTotalSizeKb(); 11077 if (!opts.isCompact) { 11078 pw.print(" Used RAM: "); pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss 11079 + kernelUsed)); pw.print(" ("); 11080 pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss)); pw.print(" used pss + "); 11081 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n"); 11082 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM)); 11083 } else { 11084 pw.print("lostram,"); pw.println(lostRAM); 11085 } 11086 if (!brief) { 11087 if (memInfo.getZramTotalSizeKb() != 0) { 11088 if (!opts.isCompact) { 11089 pw.print(" ZRAM: "); 11090 pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb())); 11091 pw.print(" physical used for "); 11092 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb() 11093 - memInfo.getSwapFreeSizeKb())); 11094 pw.print(" in swap ("); 11095 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb())); 11096 pw.println(" total swap)"); 11097 } else { 11098 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 11099 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 11100 pw.println(memInfo.getSwapFreeSizeKb()); 11101 } 11102 } 11103 final long[] ksm = getKsmInfo(); 11104 if (!opts.isCompact) { 11105 if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 11106 || ksm[KSM_VOLATILE] != 0) { 11107 pw.print(" KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING])); 11108 pw.print(" saved from shared "); 11109 pw.print(stringifyKBSize(ksm[KSM_SHARED])); 11110 pw.print(" "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED])); 11111 pw.print(" unshared; "); 11112 pw.print(stringifyKBSize( 11113 ksm[KSM_VOLATILE])); pw.println(" volatile"); 11114 } 11115 pw.print(" Tuning: "); 11116 pw.print(ActivityManager.staticGetMemoryClass()); 11117 pw.print(" (large "); 11118 pw.print(ActivityManager.staticGetLargeMemoryClass()); 11119 pw.print("), oom "); 11120 pw.print(stringifySize( 11121 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024)); 11122 pw.print(", restore limit "); 11123 pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb())); 11124 if (ActivityManager.isLowRamDeviceStatic()) { 11125 pw.print(" (low-ram)"); 11126 } 11127 if (ActivityManager.isHighEndGfx()) { 11128 pw.print(" (high-end-gfx)"); 11129 } 11130 pw.println(); 11131 } else { 11132 pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(","); 11133 pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]); 11134 pw.print(","); pw.println(ksm[KSM_VOLATILE]); 11135 pw.print("tuning,"); 11136 pw.print(ActivityManager.staticGetMemoryClass()); 11137 pw.print(','); 11138 pw.print(ActivityManager.staticGetLargeMemoryClass()); 11139 pw.print(','); 11140 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 11141 if (ActivityManager.isLowRamDeviceStatic()) { 11142 pw.print(",low-ram"); 11143 } 11144 if (ActivityManager.isHighEndGfx()) { 11145 pw.print(",high-end-gfx"); 11146 } 11147 pw.println(); 11148 } 11149 } 11150 } 11151 } 11152 dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)11153 private final void dumpApplicationMemoryUsage(FileDescriptor fd, 11154 MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, 11155 ArrayList<ProcessRecord> procs) { 11156 final long uptimeMs = SystemClock.uptimeMillis(); 11157 final long realtimeMs = SystemClock.elapsedRealtime(); 11158 final long[] tmpLong = new long[3]; 11159 11160 if (procs == null) { 11161 // No Java processes. Maybe they want to print a native process. 11162 String proc = "N/A"; 11163 if (innerArgs.length > 0) { 11164 proc = innerArgs[0]; 11165 if (proc.charAt(0) != '-') { 11166 final ArrayList<ProcessCpuTracker.Stats> nativeProcs 11167 = new ArrayList<ProcessCpuTracker.Stats>(); 11168 updateCpuStatsNow(); 11169 int findPid = -1; 11170 try { 11171 findPid = Integer.parseInt(innerArgs[0]); 11172 } catch (NumberFormatException e) { 11173 } 11174 final int fFindPid = findPid; 11175 mAppProfiler.forAllCpuStats((st) -> { 11176 if (st.pid == fFindPid || (st.baseName != null 11177 && st.baseName.equals(innerArgs[0]))) { 11178 nativeProcs.add(st); 11179 } 11180 }); 11181 if (nativeProcs.size() > 0) { 11182 ProtoOutputStream proto = new ProtoOutputStream(fd); 11183 11184 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 11185 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 11186 Debug.MemoryInfo mi = null; 11187 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 11188 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 11189 final int pid = r.pid; 11190 11191 if (mi == null) { 11192 mi = new Debug.MemoryInfo(); 11193 } 11194 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 11195 if (!Debug.getMemoryInfo(pid, mi)) { 11196 continue; 11197 } 11198 } else { 11199 long pss = Debug.getPss(pid, tmpLong, null); 11200 if (pss == 0) { 11201 continue; 11202 } 11203 mi.nativePss = (int) pss; 11204 mi.nativePrivateDirty = (int) tmpLong[0]; 11205 mi.nativeRss = (int) tmpLong[2]; 11206 } 11207 11208 final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES); 11209 11210 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 11211 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName); 11212 11213 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 11214 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 11215 11216 proto.end(nToken); 11217 } 11218 11219 proto.flush(); 11220 return; 11221 } 11222 } 11223 } 11224 Log.d(TAG, "No process found for: " + innerArgs[0]); 11225 return; 11226 } 11227 11228 if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) { 11229 opts.dumpDetails = true; 11230 } 11231 final int numProcs = procs.size(); 11232 final boolean collectNative = numProcs > 1 && !opts.packages; 11233 if (collectNative) { 11234 // If we are showing aggregations, also look for native processes to 11235 // include so that our aggregations are more accurate. 11236 updateCpuStatsNow(); 11237 } 11238 11239 ProtoOutputStream proto = new ProtoOutputStream(fd); 11240 11241 proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs); 11242 proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs); 11243 11244 final ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 11245 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 11246 final long[] ss = new long[INDEX_LAST]; 11247 long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11248 EmptyArray.LONG; 11249 long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11250 EmptyArray.LONG; 11251 long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 11252 EmptyArray.LONG; 11253 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11254 long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11255 long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 11256 11257 final long[] oomPss = new long[DUMP_MEM_OOM_LABEL.length]; 11258 final long[] oomSwapPss = new long[DUMP_MEM_OOM_LABEL.length]; 11259 final long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length]; 11260 final ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 11261 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 11262 11263 long cachedPss = 0; 11264 long cachedSwapPss = 0; 11265 boolean hasSwapPss = false; 11266 11267 Debug.MemoryInfo mi = null; 11268 for (int i = numProcs - 1; i >= 0; i--) { 11269 final ProcessRecord r = procs.get(i); 11270 final IApplicationThread thread; 11271 final int pid; 11272 final int oomAdj; 11273 final boolean hasActivities; 11274 synchronized (mProcLock) { 11275 thread = r.getThread(); 11276 pid = r.getPid(); 11277 oomAdj = r.mState.getSetAdjWithServices(); 11278 hasActivities = r.hasActivities(); 11279 } 11280 if (thread == null) { 11281 continue; 11282 } 11283 if (mi == null) { 11284 mi = new Debug.MemoryInfo(); 11285 } 11286 final int reportType; 11287 final long startTime; 11288 final long endTime; 11289 if (opts.dumpDetails || (!brief && !opts.oomOnly)) { 11290 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW; 11291 startTime = SystemClock.currentThreadTimeMillis(); 11292 if (!Debug.getMemoryInfo(pid, mi)) { 11293 continue; 11294 } 11295 endTime = SystemClock.currentThreadTimeMillis(); 11296 hasSwapPss = mi.hasSwappedOutPss; 11297 } else { 11298 reportType = ProcessStats.ADD_PSS_EXTERNAL; 11299 startTime = SystemClock.currentThreadTimeMillis(); 11300 long pss = Debug.getPss(pid, tmpLong, null); 11301 if (pss == 0) { 11302 continue; 11303 } 11304 mi.dalvikPss = (int) pss; 11305 endTime = SystemClock.currentThreadTimeMillis(); 11306 mi.dalvikPrivateDirty = (int) tmpLong[0]; 11307 mi.dalvikRss = (int) tmpLong[2]; 11308 } 11309 if (opts.dumpDetails) { 11310 if (opts.localOnly) { 11311 final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES); 11312 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY); 11313 proto.write(MemInfoDumpProto.ProcessMemory.PID, pid); 11314 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName); 11315 ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik, 11316 opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0); 11317 proto.end(mToken); 11318 proto.end(aToken); 11319 } else { 11320 try { 11321 ByteTransferPipe tp = new ByteTransferPipe(); 11322 try { 11323 thread.dumpMemInfoProto(tp.getWriteFd(), 11324 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly, 11325 opts.dumpUnreachable, innerArgs); 11326 proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get()); 11327 } finally { 11328 tp.kill(); 11329 } 11330 } catch (IOException e) { 11331 Log.e(TAG, "Got IOException!", e); 11332 } catch (RemoteException e) { 11333 Log.e(TAG, "Got RemoteException!", e); 11334 } 11335 } 11336 } 11337 11338 final long myTotalPss = mi.getTotalPss(); 11339 final long myTotalUss = mi.getTotalUss(); 11340 final long myTotalRss = mi.getTotalRss(); 11341 final long myTotalSwapPss = mi.getTotalSwappedOutPss(); 11342 11343 synchronized (mProcLock) { 11344 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) { 11345 // Record this for posterity if the process has been stable. 11346 r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true, 11347 reportType, endTime - startTime); 11348 r.getPkgList().forEachPackageProcessStats(holder -> { 11349 FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED, 11350 r.info.uid, 11351 holder.state.getName(), 11352 holder.state.getPackage(), 11353 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime, 11354 holder.appVersion); 11355 }); 11356 } 11357 } 11358 11359 if (!opts.isCheckinRequest && mi != null) { 11360 ss[INDEX_TOTAL_PSS] += myTotalPss; 11361 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 11362 ss[INDEX_TOTAL_RSS] += myTotalRss; 11363 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 11364 (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, 11365 myTotalSwapPss, myTotalRss, pid, hasActivities); 11366 procMems.add(pssItem); 11367 procMemsMap.put(pid, pssItem); 11368 11369 ss[INDEX_NATIVE_PSS] += mi.nativePss; 11370 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss; 11371 ss[INDEX_NATIVE_RSS] += mi.nativeRss; 11372 ss[INDEX_DALVIK_PSS] += mi.dalvikPss; 11373 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss; 11374 ss[INDEX_DALVIK_RSS] += mi.dalvikRss; 11375 for (int j=0; j<dalvikSubitemPss.length; j++) { 11376 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 11377 dalvikSubitemSwapPss[j] += 11378 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 11379 dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 11380 } 11381 ss[INDEX_OTHER_PSS] += mi.otherPss; 11382 ss[INDEX_OTHER_RSS] += mi.otherRss; 11383 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss; 11384 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 11385 long mem = mi.getOtherPss(j); 11386 miscPss[j] += mem; 11387 ss[INDEX_OTHER_PSS] -= mem; 11388 mem = mi.getOtherSwappedOutPss(j); 11389 miscSwapPss[j] += mem; 11390 ss[INDEX_OTHER_SWAP_PSS] -= mem; 11391 mem = mi.getOtherRss(j); 11392 miscRss[j] += mem; 11393 ss[INDEX_OTHER_RSS] -= mem; 11394 } 11395 11396 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 11397 cachedPss += myTotalPss; 11398 cachedSwapPss += myTotalSwapPss; 11399 } 11400 11401 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 11402 if (oomIndex == (oomPss.length - 1) 11403 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] 11404 && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) { 11405 oomPss[oomIndex] += myTotalPss; 11406 oomSwapPss[oomIndex] += myTotalSwapPss; 11407 if (oomProcs[oomIndex] == null) { 11408 oomProcs[oomIndex] = new ArrayList<MemItem>(); 11409 } 11410 oomProcs[oomIndex].add(pssItem); 11411 oomRss[oomIndex] += myTotalRss; 11412 break; 11413 } 11414 } 11415 } 11416 } 11417 11418 long nativeProcTotalPss = 0; 11419 11420 if (collectNative) { 11421 mi = null; 11422 final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1]; 11423 mAppProfiler.forAllCpuStats((st) -> { 11424 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 11425 if (memInfos[0] == null) { 11426 memInfos[0] = new Debug.MemoryInfo(); 11427 } 11428 final Debug.MemoryInfo info = memInfos[0]; 11429 if (!brief && !opts.oomOnly) { 11430 if (!Debug.getMemoryInfo(st.pid, info)) { 11431 return; 11432 } 11433 } else { 11434 long pss = Debug.getPss(st.pid, tmpLong, null); 11435 if (pss == 0) { 11436 return; 11437 } 11438 info.nativePss = (int) pss; 11439 info.nativePrivateDirty = (int) tmpLong[0]; 11440 info.nativeRss = (int) tmpLong[2]; 11441 } 11442 11443 final long myTotalPss = info.getTotalPss(); 11444 final long myTotalSwapPss = info.getTotalSwappedOutPss(); 11445 final long myTotalRss = info.getTotalRss(); 11446 ss[INDEX_TOTAL_PSS] += myTotalPss; 11447 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss; 11448 ss[INDEX_TOTAL_RSS] += myTotalRss; 11449 ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss; 11450 11451 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 11452 st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss, 11453 st.pid, false); 11454 procMems.add(pssItem); 11455 11456 ss[INDEX_NATIVE_PSS] += info.nativePss; 11457 ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss; 11458 ss[INDEX_NATIVE_RSS] += info.nativeRss; 11459 ss[INDEX_DALVIK_PSS] += info.dalvikPss; 11460 ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss; 11461 ss[INDEX_DALVIK_RSS] += info.dalvikRss; 11462 for (int j = 0; j < dalvikSubitemPss.length; j++) { 11463 dalvikSubitemPss[j] += info.getOtherPss( 11464 Debug.MemoryInfo.NUM_OTHER_STATS + j); 11465 dalvikSubitemSwapPss[j] += 11466 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 11467 dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS 11468 + j); 11469 } 11470 ss[INDEX_OTHER_PSS] += info.otherPss; 11471 ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss; 11472 ss[INDEX_OTHER_RSS] += info.otherRss; 11473 for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 11474 long mem = info.getOtherPss(j); 11475 miscPss[j] += mem; 11476 ss[INDEX_OTHER_PSS] -= mem; 11477 mem = info.getOtherSwappedOutPss(j); 11478 miscSwapPss[j] += mem; 11479 ss[INDEX_OTHER_SWAP_PSS] -= mem; 11480 mem = info.getOtherRss(j); 11481 miscRss[j] += mem; 11482 ss[INDEX_OTHER_RSS] -= mem; 11483 } 11484 oomPss[0] += myTotalPss; 11485 oomSwapPss[0] += myTotalSwapPss; 11486 if (oomProcs[0] == null) { 11487 oomProcs[0] = new ArrayList<MemItem>(); 11488 } 11489 oomProcs[0].add(pssItem); 11490 oomRss[0] += myTotalRss; 11491 } 11492 }); 11493 11494 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 11495 11496 catMems.add(new MemItem("Native", "Native", ss[INDEX_NATIVE_PSS], 11497 ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1)); 11498 final int dalvikId = -2; 11499 catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS], 11500 ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId)); 11501 catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS], 11502 ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3)); 11503 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 11504 String label = Debug.MemoryInfo.getOtherLabel(j); 11505 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], j)); 11506 } 11507 if (dalvikSubitemPss.length > 0) { 11508 // Add dalvik subitems. 11509 for (MemItem memItem : catMems) { 11510 int memItemStart = 0, memItemEnd = 0; 11511 if (memItem.id == dalvikId) { 11512 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START; 11513 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END; 11514 } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) { 11515 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START; 11516 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END; 11517 } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) { 11518 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START; 11519 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END; 11520 } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) { 11521 memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START; 11522 memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END; 11523 } else { 11524 continue; // No subitems, continue. 11525 } 11526 memItem.subitems = new ArrayList<MemItem>(); 11527 for (int j=memItemStart; j<=memItemEnd; j++) { 11528 final String name = Debug.MemoryInfo.getOtherLabel( 11529 Debug.MemoryInfo.NUM_OTHER_STATS + j); 11530 memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], 11531 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j)); 11532 } 11533 } 11534 } 11535 11536 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 11537 for (int j=0; j<oomPss.length; j++) { 11538 if (oomPss[j] != 0) { 11539 String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 11540 : DUMP_MEM_OOM_LABEL[j]; 11541 MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j], 11542 DUMP_MEM_OOM_ADJ[j]); 11543 item.subitems = oomProcs[j]; 11544 oomMems.add(item); 11545 } 11546 } 11547 11548 if (!opts.oomOnly) { 11549 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_PROCESS, "proc", 11550 procMems, true, false, false); 11551 } 11552 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_OOM_ADJUSTMENT, "oom", 11553 oomMems, false, false, false); 11554 if (!brief && !opts.oomOnly) { 11555 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_CATEGORY, "cat", 11556 catMems, true, false, false); 11557 } 11558 11559 opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0; 11560 if (!opts.oomOnly) { 11561 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc", 11562 procMems, true, true, opts.dumpSwapPss); 11563 } 11564 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom", 11565 oomMems, false, true, opts.dumpSwapPss); 11566 if (!brief && !opts.oomOnly) { 11567 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat", 11568 catMems, true, true, opts.dumpSwapPss); 11569 } 11570 MemInfoReader memInfo = new MemInfoReader(); 11571 memInfo.readMemInfo(); 11572 if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) { 11573 synchronized (mProcessStats.mLock) { 11574 final long cachedKb = memInfo.getCachedSizeKb(); 11575 final long freeKb = memInfo.getFreeSizeKb(); 11576 final long zramKb = memInfo.getZramTotalSizeKb(); 11577 final long kernelKb = memInfo.getKernelUsedSizeKb(); 11578 EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, 11579 kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024); 11580 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 11581 ss[INDEX_TOTAL_NATIVE_PSS]); 11582 } 11583 } 11584 if (!brief) { 11585 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb()); 11586 proto.write(MemInfoDumpProto.STATUS, mAppProfiler.getLastMemoryLevelLocked()); 11587 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss); 11588 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb()); 11589 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb()); 11590 } 11591 long lostRAM = memInfo.getTotalSizeKb() 11592 - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS]) 11593 - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 11594 - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb(); 11595 proto.write(MemInfoDumpProto.USED_PSS_KB, ss[INDEX_TOTAL_PSS] - cachedPss); 11596 proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb()); 11597 proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM); 11598 if (!brief) { 11599 if (memInfo.getZramTotalSizeKb() != 0) { 11600 proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb()); 11601 proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB, 11602 memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb()); 11603 proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb()); 11604 } 11605 final long[] ksm = getKsmInfo(); 11606 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]); 11607 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]); 11608 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]); 11609 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]); 11610 11611 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass()); 11612 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass()); 11613 proto.write(MemInfoDumpProto.OOM_KB, 11614 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024); 11615 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB, 11616 mProcessList.getCachedRestoreThresholdKb()); 11617 11618 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic()); 11619 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx()); 11620 } 11621 } 11622 11623 proto.flush(); 11624 } 11625 appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)11626 static void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, 11627 long memtrack, String name) { 11628 sb.append(" "); 11629 sb.append(ProcessList.makeOomAdjString(oomAdj, false)); 11630 sb.append(' '); 11631 sb.append(ProcessList.makeProcStateString(procState)); 11632 sb.append(' '); 11633 ProcessList.appendRamKb(sb, pss); 11634 sb.append(": "); 11635 sb.append(name); 11636 if (memtrack > 0) { 11637 sb.append(" ("); 11638 sb.append(stringifyKBSize(memtrack)); 11639 sb.append(" memtrack)"); 11640 } 11641 } 11642 appendMemInfo(StringBuilder sb, ProcessMemInfo mi)11643 static void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) { 11644 appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name); 11645 sb.append(" (pid "); 11646 sb.append(mi.pid); 11647 sb.append(") "); 11648 sb.append(mi.adjType); 11649 sb.append('\n'); 11650 if (mi.adjReason != null) { 11651 sb.append(" "); 11652 sb.append(mi.adjReason); 11653 sb.append('\n'); 11654 } 11655 } 11656 11657 /** 11658 * Searches array of arguments for the specified string 11659 * @param args array of argument strings 11660 * @param value value to search for 11661 * @return true if the value is contained in the array 11662 */ scanArgs(String[] args, String value)11663 private static boolean scanArgs(String[] args, String value) { 11664 if (args != null) { 11665 for (String arg : args) { 11666 if (value.equals(arg)) { 11667 return true; 11668 } 11669 } 11670 } 11671 return false; 11672 } 11673 11674 /** 11675 * Main code for cleaning up a process when it has gone away. This is 11676 * called both as a result of the process dying, or directly when stopping 11677 * a process when running in single process mode. 11678 * 11679 * @return Returns true if the given process has been restarted, so the 11680 * app that was passed in must remain on the process lists. 11681 */ 11682 @GuardedBy("this") cleanUpApplicationRecordLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, int index, boolean replacingPid, boolean fromBinderDied)11683 final boolean cleanUpApplicationRecordLocked(ProcessRecord app, int pid, 11684 boolean restarting, boolean allowRestart, int index, boolean replacingPid, 11685 boolean fromBinderDied) { 11686 boolean restart; 11687 synchronized (mProcLock) { 11688 if (index >= 0) { 11689 removeLruProcessLocked(app); 11690 ProcessList.remove(pid); 11691 } 11692 11693 // We don't want to unlinkDeathRecipient immediately, if it's not called from binder 11694 // and it's not isolated, as we'd need the signal to bookkeeping the dying process list. 11695 restart = app.onCleanupApplicationRecordLSP(mProcessStats, allowRestart, 11696 fromBinderDied || app.isolated /* unlinkDeath */); 11697 11698 // Cancel pending frozen task if there is any. 11699 mOomAdjuster.mCachedAppOptimizer.unscheduleFreezeAppLSP(app); 11700 } 11701 mAppProfiler.onCleanupApplicationRecordLocked(app); 11702 skipCurrentReceiverLocked(app); 11703 updateProcessForegroundLocked(app, false, 0, false); 11704 mServices.killServicesLocked(app, allowRestart); 11705 mPhantomProcessList.onAppDied(pid); 11706 11707 // If the app is undergoing backup, tell the backup manager about it 11708 final BackupRecord backupTarget = mBackupTargets.get(app.userId); 11709 if (backupTarget != null && pid == backupTarget.app.getPid()) { 11710 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App " 11711 + backupTarget.appInfo + " died during backup"); 11712 mHandler.post(new Runnable() { 11713 @Override 11714 public void run(){ 11715 try { 11716 IBackupManager bm = IBackupManager.Stub.asInterface( 11717 ServiceManager.getService(Context.BACKUP_SERVICE)); 11718 bm.agentDisconnectedForUser(app.userId, app.info.packageName); 11719 } catch (RemoteException e) { 11720 // can't happen; backup manager is local 11721 } 11722 } 11723 }); 11724 } 11725 11726 mProcessList.scheduleDispatchProcessDiedLocked(pid, app.info.uid); 11727 11728 // If this is a preceding instance of another process instance 11729 allowRestart = mProcessList.handlePrecedingAppDiedLocked(app); 11730 11731 // If the caller is restarting this app, then leave it in its 11732 // current lists and let the caller take care of it. 11733 if (restarting) { 11734 return false; 11735 } 11736 11737 if (!app.isPersistent() || app.isolated) { 11738 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 11739 "Removing non-persistent process during cleanup: " + app); 11740 if (!replacingPid) { 11741 mProcessList.removeProcessNameLocked(app.processName, app.uid, app); 11742 } 11743 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 11744 } else if (!app.isRemoved()) { 11745 // This app is persistent, so we need to keep its record around. 11746 // If it is not already on the pending app list, add it there 11747 // and start a new process for it. 11748 if (mPersistentStartingProcesses.indexOf(app) < 0) { 11749 mPersistentStartingProcesses.add(app); 11750 restart = true; 11751 } 11752 } 11753 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v( 11754 TAG_CLEANUP, "Clean-up removing on hold: " + app); 11755 mProcessesOnHold.remove(app); 11756 11757 mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController()); 11758 mProcessList.noteProcessDiedLocked(app); 11759 11760 if (restart && allowRestart && !app.isolated) { 11761 // We have components that still need to be running in the 11762 // process, so re-launch it. 11763 if (index < 0) { 11764 ProcessList.remove(pid); 11765 } 11766 11767 // Remove provider publish timeout because we will start a new timeout when the 11768 // restarted process is attaching (if the process contains launching providers). 11769 mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, app); 11770 11771 mProcessList.addProcessNameLocked(app); 11772 app.setPendingStart(false); 11773 mProcessList.startProcessLocked(app, new HostingRecord("restart", app.processName), 11774 ZYGOTE_POLICY_FLAG_EMPTY); 11775 return true; 11776 } else if (pid > 0 && pid != MY_PID) { 11777 // Goodbye! 11778 removePidLocked(pid, app); 11779 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 11780 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 11781 if (app.isolated) { 11782 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 11783 } 11784 app.setPid(0); 11785 } 11786 return false; 11787 } 11788 11789 // ========================================================= 11790 // SERVICES 11791 // ========================================================= 11792 11793 @Override getServices(int maxNum, int flags)11794 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) { 11795 enforceNotIsolatedCaller("getServices"); 11796 11797 final int callingUid = Binder.getCallingUid(); 11798 final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission( 11799 INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED); 11800 final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices", 11801 Binder.getCallingPid(), callingUid); 11802 synchronized (this) { 11803 return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid, 11804 allowed, canInteractAcrossUsers); 11805 } 11806 } 11807 11808 @Override getRunningServiceControlPanel(ComponentName name)11809 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 11810 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 11811 synchronized (this) { 11812 return mServices.getRunningServiceControlPanelLocked(name); 11813 } 11814 } 11815 11816 @Override startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId)11817 public ComponentName startService(IApplicationThread caller, Intent service, 11818 String resolvedType, boolean requireForeground, String callingPackage, 11819 String callingFeatureId, int userId) 11820 throws TransactionTooLargeException { 11821 enforceNotIsolatedCaller("startService"); 11822 // Refuse possible leaked file descriptors 11823 if (service != null && service.hasFileDescriptors() == true) { 11824 throw new IllegalArgumentException("File descriptors passed in Intent"); 11825 } 11826 11827 if (callingPackage == null) { 11828 throw new IllegalArgumentException("callingPackage cannot be null"); 11829 } 11830 11831 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 11832 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground); 11833 synchronized(this) { 11834 final int callingPid = Binder.getCallingPid(); 11835 final int callingUid = Binder.getCallingUid(); 11836 final long origId = Binder.clearCallingIdentity(); 11837 ComponentName res; 11838 try { 11839 res = mServices.startServiceLocked(caller, service, 11840 resolvedType, callingPid, callingUid, 11841 requireForeground, callingPackage, callingFeatureId, userId); 11842 } finally { 11843 Binder.restoreCallingIdentity(origId); 11844 } 11845 return res; 11846 } 11847 } 11848 11849 @Override stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)11850 public int stopService(IApplicationThread caller, Intent service, 11851 String resolvedType, int userId) { 11852 enforceNotIsolatedCaller("stopService"); 11853 // Refuse possible leaked file descriptors 11854 if (service != null && service.hasFileDescriptors() == true) { 11855 throw new IllegalArgumentException("File descriptors passed in Intent"); 11856 } 11857 11858 synchronized(this) { 11859 return mServices.stopServiceLocked(caller, service, resolvedType, userId); 11860 } 11861 } 11862 11863 @Override peekService(Intent service, String resolvedType, String callingPackage)11864 public IBinder peekService(Intent service, String resolvedType, String callingPackage) { 11865 enforceNotIsolatedCaller("peekService"); 11866 // Refuse possible leaked file descriptors 11867 if (service != null && service.hasFileDescriptors() == true) { 11868 throw new IllegalArgumentException("File descriptors passed in Intent"); 11869 } 11870 11871 if (callingPackage == null) { 11872 throw new IllegalArgumentException("callingPackage cannot be null"); 11873 } 11874 11875 synchronized(this) { 11876 return mServices.peekServiceLocked(service, resolvedType, callingPackage); 11877 } 11878 } 11879 11880 @Override stopServiceToken(ComponentName className, IBinder token, int startId)11881 public boolean stopServiceToken(ComponentName className, IBinder token, 11882 int startId) { 11883 synchronized(this) { 11884 return mServices.stopServiceTokenLocked(className, token, startId); 11885 } 11886 } 11887 11888 @Override setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)11889 public void setServiceForeground(ComponentName className, IBinder token, 11890 int id, Notification notification, int flags, int foregroundServiceType) { 11891 synchronized(this) { 11892 mServices.setServiceForegroundLocked(className, token, id, notification, flags, 11893 foregroundServiceType); 11894 } 11895 } 11896 11897 @Override getForegroundServiceType(ComponentName className, IBinder token)11898 public int getForegroundServiceType(ComponentName className, IBinder token) { 11899 synchronized (this) { 11900 return mServices.getForegroundServiceTypeLocked(className, token); 11901 } 11902 } 11903 11904 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)11905 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 11906 boolean requireFull, String name, String callerPackage) { 11907 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 11908 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 11909 } 11910 isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)11911 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 11912 String className, int flags) { 11913 boolean result = false; 11914 // For apps that don't have pre-defined UIDs, check for permission 11915 if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) { 11916 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 11917 if (ActivityManager.checkUidPermission( 11918 INTERACT_ACROSS_USERS, 11919 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 11920 ComponentName comp = new ComponentName(aInfo.packageName, className); 11921 String msg = "Permission Denial: Component " + comp.flattenToShortString() 11922 + " requests FLAG_SINGLE_USER, but app does not hold " 11923 + INTERACT_ACROSS_USERS; 11924 Slog.w(TAG, msg); 11925 throw new SecurityException(msg); 11926 } 11927 // Permission passed 11928 result = true; 11929 } 11930 } else if ("system".equals(componentProcessName)) { 11931 result = true; 11932 } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 11933 // Phone app and persistent apps are allowed to export singleuser providers. 11934 result = UserHandle.isSameApp(aInfo.uid, PHONE_UID) 11935 || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 11936 } 11937 if (DEBUG_MU) Slog.v(TAG_MU, 11938 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x" 11939 + Integer.toHexString(flags) + ") = " + result); 11940 return result; 11941 } 11942 11943 /** 11944 * Checks to see if the caller is in the same app as the singleton 11945 * component, or the component is in a special app. It allows special apps 11946 * to export singleton components but prevents exporting singleton 11947 * components for regular apps. 11948 */ isValidSingletonCall(int callingUid, int componentUid)11949 boolean isValidSingletonCall(int callingUid, int componentUid) { 11950 int componentAppId = UserHandle.getAppId(componentUid); 11951 return UserHandle.isSameApp(callingUid, componentUid) 11952 || componentAppId == SYSTEM_UID 11953 || componentAppId == PHONE_UID 11954 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 11955 == PackageManager.PERMISSION_GRANTED; 11956 } 11957 bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)11958 public int bindService(IApplicationThread caller, IBinder token, Intent service, 11959 String resolvedType, IServiceConnection connection, int flags, 11960 String callingPackage, int userId) throws TransactionTooLargeException { 11961 return bindIsolatedService(caller, token, service, resolvedType, connection, flags, 11962 null, callingPackage, userId); 11963 } 11964 bindIsolatedService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, String callingPackage, int userId)11965 public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service, 11966 String resolvedType, IServiceConnection connection, int flags, String instanceName, 11967 String callingPackage, int userId) throws TransactionTooLargeException { 11968 enforceNotIsolatedCaller("bindService"); 11969 11970 // Refuse possible leaked file descriptors 11971 if (service != null && service.hasFileDescriptors() == true) { 11972 throw new IllegalArgumentException("File descriptors passed in Intent"); 11973 } 11974 11975 if (callingPackage == null) { 11976 throw new IllegalArgumentException("callingPackage cannot be null"); 11977 } 11978 11979 // Ensure that instanceName, which is caller provided, does not contain 11980 // unusual characters. 11981 if (instanceName != null) { 11982 for (int i = 0; i < instanceName.length(); ++i) { 11983 char c = instanceName.charAt(i); 11984 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') 11985 || (c >= '0' && c <= '9') || c == '_' || c == '.')) { 11986 throw new IllegalArgumentException("Illegal instanceName"); 11987 } 11988 } 11989 } 11990 11991 synchronized(this) { 11992 return mServices.bindServiceLocked(caller, token, service, 11993 resolvedType, connection, flags, instanceName, callingPackage, userId); 11994 } 11995 } 11996 updateServiceGroup(IServiceConnection connection, int group, int importance)11997 public void updateServiceGroup(IServiceConnection connection, int group, int importance) { 11998 synchronized (this) { 11999 mServices.updateServiceGroupLocked(connection, group, importance); 12000 } 12001 } 12002 unbindService(IServiceConnection connection)12003 public boolean unbindService(IServiceConnection connection) { 12004 synchronized (this) { 12005 return mServices.unbindServiceLocked(connection); 12006 } 12007 } 12008 publishService(IBinder token, Intent intent, IBinder service)12009 public void publishService(IBinder token, Intent intent, IBinder service) { 12010 // Refuse possible leaked file descriptors 12011 if (intent != null && intent.hasFileDescriptors() == true) { 12012 throw new IllegalArgumentException("File descriptors passed in Intent"); 12013 } 12014 12015 synchronized(this) { 12016 if (!(token instanceof ServiceRecord)) { 12017 throw new IllegalArgumentException("Invalid service token"); 12018 } 12019 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 12020 } 12021 } 12022 unbindFinished(IBinder token, Intent intent, boolean doRebind)12023 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) { 12024 // Refuse possible leaked file descriptors 12025 if (intent != null && intent.hasFileDescriptors() == true) { 12026 throw new IllegalArgumentException("File descriptors passed in Intent"); 12027 } 12028 12029 synchronized(this) { 12030 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind); 12031 } 12032 } 12033 serviceDoneExecuting(IBinder token, int type, int startId, int res)12034 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) { 12035 synchronized(this) { 12036 if (!(token instanceof ServiceRecord)) { 12037 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token); 12038 throw new IllegalArgumentException("Invalid service token"); 12039 } 12040 mServices.serviceDoneExecutingLocked((ServiceRecord) token, type, startId, res, false); 12041 } 12042 } 12043 12044 // ========================================================= 12045 // BACKUP AND RESTORE 12046 // ========================================================= 12047 12048 // Cause the target app to be launched if necessary and its backup agent 12049 // instantiated. The backup agent will invoke backupAgentCreated() on the 12050 // activity manager to announce its creation. bindBackupAgent(String packageName, int backupMode, int targetUserId, @OperationType int operationType)12051 public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId, 12052 @OperationType int operationType) { 12053 if (DEBUG_BACKUP) { 12054 Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode 12055 + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid() 12056 + " uid = " + Process.myUid()); 12057 } 12058 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 12059 12060 // The instantiatedUserId is the user of the process the backup agent is started in. This is 12061 // different from the targetUserId which is the user whose data is to be backed up or 12062 // restored. This distinction is important for system-process packages that live in the 12063 // system user's process but backup/restore data for non-system users. 12064 // TODO (b/123688746): Handle all system-process packages with singleton check. 12065 final int instantiatedUserId = 12066 PLATFORM_PACKAGE_NAME.equals(packageName) ? UserHandle.USER_SYSTEM : targetUserId; 12067 12068 IPackageManager pm = AppGlobals.getPackageManager(); 12069 ApplicationInfo app = null; 12070 try { 12071 app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId); 12072 } catch (RemoteException e) { 12073 // can't happen; package manager is process-local 12074 } 12075 if (app == null) { 12076 Slog.w(TAG, "Unable to bind backup agent for " + packageName); 12077 return false; 12078 } 12079 12080 int oldBackupUid; 12081 int newBackupUid; 12082 12083 synchronized(this) { 12084 // !!! TODO: currently no check here that we're already bound 12085 // Backup agent is now in use, its package can't be stopped. 12086 try { 12087 AppGlobals.getPackageManager().setPackageStoppedState( 12088 app.packageName, false, UserHandle.getUserId(app.uid)); 12089 } catch (RemoteException e) { 12090 } catch (IllegalArgumentException e) { 12091 Slog.w(TAG, "Failed trying to unstop package " 12092 + app.packageName + ": " + e); 12093 } 12094 12095 BackupRecord r = new BackupRecord(app, backupMode, targetUserId, operationType); 12096 ComponentName hostingName = 12097 (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL) 12098 ? new ComponentName(app.packageName, app.backupAgentName) 12099 : new ComponentName("android", "FullBackupAgent"); 12100 12101 // startProcessLocked() returns existing proc's record if it's already running 12102 ProcessRecord proc = startProcessLocked(app.processName, app, 12103 false, 0, 12104 new HostingRecord("backup", hostingName), 12105 ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false); 12106 if (proc == null) { 12107 Slog.e(TAG, "Unable to start backup agent process " + r); 12108 return false; 12109 } 12110 12111 // If the app is a regular app (uid >= 10000) and not the system server or phone 12112 // process, etc, then mark it as being in full backup so that certain calls to the 12113 // process can be blocked. This is not reset to false anywhere because we kill the 12114 // process after the full backup is done and the ProcessRecord will vaporize anyway. 12115 if (UserHandle.isApp(app.uid) && 12116 backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) { 12117 proc.setInFullBackup(true); 12118 } 12119 r.app = proc; 12120 final BackupRecord backupTarget = mBackupTargets.get(targetUserId); 12121 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 12122 newBackupUid = proc.isInFullBackup() ? r.appInfo.uid : -1; 12123 mBackupTargets.put(targetUserId, r); 12124 12125 // Try not to kill the process during backup 12126 updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_NONE); 12127 12128 // If the process is already attached, schedule the creation of the backup agent now. 12129 // If it is not yet live, this will be done when it attaches to the framework. 12130 final IApplicationThread thread = proc.getThread(); 12131 if (thread != null) { 12132 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc); 12133 try { 12134 thread.scheduleCreateBackupAgent(app, 12135 compatibilityInfoForPackage(app), backupMode, targetUserId, 12136 operationType); 12137 } catch (RemoteException e) { 12138 // Will time out on the backup manager side 12139 } 12140 } else { 12141 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach"); 12142 } 12143 // Invariants: at this point, the target app process exists and the application 12144 // is either already running or in the process of coming up. mBackupTarget and 12145 // mBackupAppName describe the app, so that when it binds back to the AM we 12146 // know that it's scheduled for a backup-agent operation. 12147 } 12148 12149 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 12150 if (oldBackupUid != -1) { 12151 js.removeBackingUpUid(oldBackupUid); 12152 } 12153 if (newBackupUid != -1) { 12154 js.addBackingUpUid(newBackupUid); 12155 } 12156 12157 return true; 12158 } 12159 clearPendingBackup(int userId)12160 private void clearPendingBackup(int userId) { 12161 if (DEBUG_BACKUP) { 12162 Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = " 12163 + Binder.getCallingUid() + " uid = " + Process.myUid()); 12164 } 12165 12166 synchronized (this) { 12167 mBackupTargets.delete(userId); 12168 } 12169 12170 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 12171 js.clearAllBackingUpUids(); 12172 } 12173 12174 // A backup agent has just come up 12175 @Override backupAgentCreated(String agentPackageName, IBinder agent, int userId)12176 public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) { 12177 // Resolve the target user id and enforce permissions. 12178 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 12179 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null); 12180 if (DEBUG_BACKUP) { 12181 Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent 12182 + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId 12183 + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid()); 12184 } 12185 12186 synchronized(this) { 12187 final BackupRecord backupTarget = mBackupTargets.get(userId); 12188 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 12189 if (!agentPackageName.equals(backupAppName)) { 12190 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 12191 return; 12192 } 12193 } 12194 12195 final long oldIdent = Binder.clearCallingIdentity(); 12196 try { 12197 IBackupManager bm = IBackupManager.Stub.asInterface( 12198 ServiceManager.getService(Context.BACKUP_SERVICE)); 12199 bm.agentConnectedForUser(userId, agentPackageName, agent); 12200 } catch (RemoteException e) { 12201 // can't happen; the backup manager service is local 12202 } catch (Exception e) { 12203 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 12204 e.printStackTrace(); 12205 } finally { 12206 Binder.restoreCallingIdentity(oldIdent); 12207 } 12208 } 12209 12210 // done with this agent unbindBackupAgent(ApplicationInfo appInfo)12211 public void unbindBackupAgent(ApplicationInfo appInfo) { 12212 if (DEBUG_BACKUP) { 12213 Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = " 12214 + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = " 12215 + Process.myUid()); 12216 } 12217 12218 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent"); 12219 if (appInfo == null) { 12220 Slog.w(TAG, "unbind backup agent for null app"); 12221 return; 12222 } 12223 12224 int oldBackupUid; 12225 12226 final int userId = UserHandle.getUserId(appInfo.uid); 12227 synchronized(this) { 12228 final BackupRecord backupTarget = mBackupTargets.get(userId); 12229 String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName; 12230 try { 12231 if (backupAppName == null) { 12232 Slog.w(TAG, "Unbinding backup agent with no active backup"); 12233 return; 12234 } 12235 12236 if (!backupAppName.equals(appInfo.packageName)) { 12237 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 12238 return; 12239 } 12240 12241 // Not backing this app up any more; reset its OOM adjustment 12242 final ProcessRecord proc = backupTarget.app; 12243 updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_NONE); 12244 proc.setInFullBackup(false); 12245 12246 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1; 12247 12248 // If the app crashed during backup, 'thread' will be null here 12249 final IApplicationThread thread = proc.getThread(); 12250 if (thread != null) { 12251 try { 12252 thread.scheduleDestroyBackupAgent(appInfo, 12253 compatibilityInfoForPackage(appInfo), userId); 12254 } catch (Exception e) { 12255 Slog.e(TAG, "Exception when unbinding backup agent:"); 12256 e.printStackTrace(); 12257 } 12258 } 12259 } finally { 12260 mBackupTargets.delete(userId); 12261 } 12262 } 12263 12264 if (oldBackupUid != -1) { 12265 JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class); 12266 js.removeBackingUpUid(oldBackupUid); 12267 } 12268 } 12269 12270 // ========================================================= 12271 // BROADCASTS 12272 // ========================================================= 12273 isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)12274 private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) { 12275 if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) { 12276 return false; 12277 } 12278 // Easy case -- we have the app's ProcessRecord. 12279 if (record != null) { 12280 return record.info.isInstantApp(); 12281 } 12282 // Otherwise check with PackageManager. 12283 IPackageManager pm = AppGlobals.getPackageManager(); 12284 try { 12285 if (callerPackage == null) { 12286 final String[] packageNames = pm.getPackagesForUid(uid); 12287 if (packageNames == null || packageNames.length == 0) { 12288 throw new IllegalArgumentException("Unable to determine caller package name"); 12289 } 12290 // Instant Apps can't use shared uids, so its safe to only check the first package. 12291 callerPackage = packageNames[0]; 12292 } 12293 mAppOpsService.checkPackage(uid, callerPackage); 12294 return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid)); 12295 } catch (RemoteException e) { 12296 Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e); 12297 return true; 12298 } 12299 } 12300 isPendingBroadcastProcessLocked(int pid)12301 boolean isPendingBroadcastProcessLocked(int pid) { 12302 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 12303 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 12304 || mOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid); 12305 } 12306 skipPendingBroadcastLocked(int pid)12307 void skipPendingBroadcastLocked(int pid) { 12308 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 12309 for (BroadcastQueue queue : mBroadcastQueues) { 12310 queue.skipPendingBroadcastLocked(pid); 12311 } 12312 } 12313 12314 // The app just attached; send any pending broadcasts that it should receive sendPendingBroadcastsLocked(ProcessRecord app)12315 boolean sendPendingBroadcastsLocked(ProcessRecord app) { 12316 boolean didSomething = false; 12317 for (BroadcastQueue queue : mBroadcastQueues) { 12318 didSomething |= queue.sendPendingBroadcastsLocked(app); 12319 } 12320 return didSomething; 12321 } 12322 12323 /** 12324 * @deprecated Use {@link #registerReceiverWithFeature} 12325 */ 12326 @Deprecated registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)12327 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 12328 IIntentReceiver receiver, IntentFilter filter, String permission, int userId, 12329 int flags) { 12330 return registerReceiverWithFeature(caller, callerPackage, null, null, 12331 receiver, filter, permission, userId, flags); 12332 } 12333 registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)12334 public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage, 12335 String callerFeatureId, String receiverId, IIntentReceiver receiver, 12336 IntentFilter filter, String permission, int userId, int flags) { 12337 enforceNotIsolatedCaller("registerReceiver"); 12338 ArrayList<Intent> stickyIntents = null; 12339 ProcessRecord callerApp = null; 12340 final boolean visibleToInstantApps 12341 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0; 12342 int callingUid; 12343 int callingPid; 12344 boolean instantApp; 12345 synchronized(this) { 12346 if (caller != null) { 12347 callerApp = getRecordForAppLOSP(caller); 12348 if (callerApp == null) { 12349 throw new SecurityException( 12350 "Unable to find app for caller " + caller 12351 + " (pid=" + Binder.getCallingPid() 12352 + ") when registering receiver " + receiver); 12353 } 12354 if (callerApp.info.uid != SYSTEM_UID 12355 && !callerApp.getPkgList().containsKey(callerPackage) 12356 && !"android".equals(callerPackage)) { 12357 throw new SecurityException("Given caller package " + callerPackage 12358 + " is not running in process " + callerApp); 12359 } 12360 callingUid = callerApp.info.uid; 12361 callingPid = callerApp.getPid(); 12362 } else { 12363 callerPackage = null; 12364 callingUid = Binder.getCallingUid(); 12365 callingPid = Binder.getCallingPid(); 12366 } 12367 12368 instantApp = isInstantApp(callerApp, callerPackage, callingUid); 12369 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 12370 ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 12371 12372 Iterator<String> actions = filter.actionsIterator(); 12373 if (actions == null) { 12374 ArrayList<String> noAction = new ArrayList<String>(1); 12375 noAction.add(null); 12376 actions = noAction.iterator(); 12377 } 12378 12379 // Collect stickies of users 12380 int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) }; 12381 while (actions.hasNext()) { 12382 String action = actions.next(); 12383 for (int id : userIds) { 12384 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(id); 12385 if (stickies != null) { 12386 ArrayList<Intent> intents = stickies.get(action); 12387 if (intents != null) { 12388 if (stickyIntents == null) { 12389 stickyIntents = new ArrayList<Intent>(); 12390 } 12391 stickyIntents.addAll(intents); 12392 } 12393 } 12394 } 12395 } 12396 } 12397 12398 ArrayList<Intent> allSticky = null; 12399 if (stickyIntents != null) { 12400 final ContentResolver resolver = mContext.getContentResolver(); 12401 // Look for any matching sticky broadcasts... 12402 for (int i = 0, N = stickyIntents.size(); i < N; i++) { 12403 Intent intent = stickyIntents.get(i); 12404 // Don't provided intents that aren't available to instant apps. 12405 if (instantApp && 12406 (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) { 12407 continue; 12408 } 12409 // If intent has scheme "content", it will need to acccess 12410 // provider that needs to lock mProviderMap in ActivityThread 12411 // and also it may need to wait application response, so we 12412 // cannot lock ActivityManagerService here. 12413 if (filter.match(resolver, intent, true, TAG) >= 0) { 12414 if (allSticky == null) { 12415 allSticky = new ArrayList<Intent>(); 12416 } 12417 allSticky.add(intent); 12418 } 12419 } 12420 } 12421 12422 // The first sticky in the list is returned directly back to the client. 12423 Intent sticky = allSticky != null ? allSticky.get(0) : null; 12424 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky); 12425 if (receiver == null) { 12426 return sticky; 12427 } 12428 12429 // SafetyNet logging for b/177931370. If any process other than system_server tries to 12430 // listen to this broadcast action, then log it. 12431 if (callingPid != Process.myPid()) { 12432 if (filter.hasAction("com.android.server.net.action.SNOOZE_WARNING") 12433 || filter.hasAction("com.android.server.net.action.SNOOZE_RAPID")) { 12434 EventLog.writeEvent(0x534e4554, "177931370", callingUid, ""); 12435 } 12436 } 12437 12438 synchronized (this) { 12439 IApplicationThread thread; 12440 if (callerApp != null && ((thread = callerApp.getThread()) == null 12441 || thread.asBinder() != caller.asBinder())) { 12442 // Original caller already died 12443 return null; 12444 } 12445 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 12446 if (rl == null) { 12447 rl = new ReceiverList(this, callerApp, callingPid, callingUid, 12448 userId, receiver); 12449 if (rl.app != null) { 12450 final int totalReceiversForApp = rl.app.mReceivers.numberOfReceivers(); 12451 if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) { 12452 throw new IllegalStateException("Too many receivers, total of " 12453 + totalReceiversForApp + ", registered for pid: " 12454 + rl.pid + ", callerPackage: " + callerPackage); 12455 } 12456 rl.app.mReceivers.addReceiver(rl); 12457 } else { 12458 try { 12459 receiver.asBinder().linkToDeath(rl, 0); 12460 } catch (RemoteException e) { 12461 return sticky; 12462 } 12463 rl.linkedToDeath = true; 12464 } 12465 mRegisteredReceivers.put(receiver.asBinder(), rl); 12466 } else if (rl.uid != callingUid) { 12467 throw new IllegalArgumentException( 12468 "Receiver requested to register for uid " + callingUid 12469 + " was previously registered for uid " + rl.uid 12470 + " callerPackage is " + callerPackage); 12471 } else if (rl.pid != callingPid) { 12472 throw new IllegalArgumentException( 12473 "Receiver requested to register for pid " + callingPid 12474 + " was previously registered for pid " + rl.pid 12475 + " callerPackage is " + callerPackage); 12476 } else if (rl.userId != userId) { 12477 throw new IllegalArgumentException( 12478 "Receiver requested to register for user " + userId 12479 + " was previously registered for user " + rl.userId 12480 + " callerPackage is " + callerPackage); 12481 } 12482 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId, 12483 receiverId, permission, callingUid, userId, instantApp, visibleToInstantApps); 12484 if (rl.containsFilter(filter)) { 12485 Slog.w(TAG, "Receiver with filter " + filter 12486 + " already registered for pid " + rl.pid 12487 + ", callerPackage is " + callerPackage); 12488 } else { 12489 rl.add(bf); 12490 if (!bf.debugCheck()) { 12491 Slog.w(TAG, "==> For Dynamic broadcast"); 12492 } 12493 mReceiverResolver.addFilter(bf); 12494 } 12495 12496 // Enqueue broadcasts for all existing stickies that match 12497 // this filter. 12498 if (allSticky != null) { 12499 ArrayList receivers = new ArrayList(); 12500 receivers.add(bf); 12501 12502 final int stickyCount = allSticky.size(); 12503 for (int i = 0; i < stickyCount; i++) { 12504 Intent intent = allSticky.get(i); 12505 BroadcastQueue queue = broadcastQueueForIntent(intent); 12506 BroadcastRecord r = new BroadcastRecord(queue, intent, null, 12507 null, null, -1, -1, false, null, null, null, OP_NONE, null, receivers, 12508 null, 0, null, null, false, true, true, -1, false, null, 12509 false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */); 12510 queue.enqueueParallelBroadcastLocked(r); 12511 queue.scheduleBroadcastsLocked(); 12512 } 12513 } 12514 12515 return sticky; 12516 } 12517 } 12518 unregisterReceiver(IIntentReceiver receiver)12519 public void unregisterReceiver(IIntentReceiver receiver) { 12520 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver); 12521 12522 final long origId = Binder.clearCallingIdentity(); 12523 try { 12524 boolean doTrim = false; 12525 12526 synchronized(this) { 12527 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 12528 if (rl != null) { 12529 final BroadcastRecord r = rl.curBroadcast; 12530 if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) { 12531 final boolean doNext = r.queue.finishReceiverLocked( 12532 r, r.resultCode, r.resultData, r.resultExtras, 12533 r.resultAbort, false); 12534 if (doNext) { 12535 doTrim = true; 12536 r.queue.processNextBroadcastLocked(/* frommsg */ false, 12537 /* skipOomAdj */ true); 12538 } 12539 } 12540 12541 if (rl.app != null) { 12542 rl.app.mReceivers.removeReceiver(rl); 12543 } 12544 removeReceiverLocked(rl); 12545 if (rl.linkedToDeath) { 12546 rl.linkedToDeath = false; 12547 rl.receiver.asBinder().unlinkToDeath(rl, 0); 12548 } 12549 } 12550 12551 // If we actually concluded any broadcasts, we might now be able 12552 // to trim the recipients' apps from our working set 12553 if (doTrim) { 12554 trimApplicationsLocked(false, OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER); 12555 return; 12556 } 12557 } 12558 12559 } finally { 12560 Binder.restoreCallingIdentity(origId); 12561 } 12562 } 12563 removeReceiverLocked(ReceiverList rl)12564 void removeReceiverLocked(ReceiverList rl) { 12565 mRegisteredReceivers.remove(rl.receiver.asBinder()); 12566 for (int i = rl.size() - 1; i >= 0; i--) { 12567 mReceiverResolver.removeFilter(rl.get(i)); 12568 } 12569 } 12570 sendPackageBroadcastLocked(int cmd, String[] packages, int userId)12571 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 12572 mProcessList.sendPackageBroadcastLocked(cmd, packages, userId); 12573 } 12574 collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users, int[] broadcastAllowList)12575 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType, 12576 int callingUid, int[] users, int[] broadcastAllowList) { 12577 // TODO: come back and remove this assumption to triage all broadcasts 12578 int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING; 12579 12580 List<ResolveInfo> receivers = null; 12581 try { 12582 HashSet<ComponentName> singleUserReceivers = null; 12583 boolean scannedFirstReceivers = false; 12584 for (int user : users) { 12585 // Skip users that have Shell restrictions 12586 if (callingUid == SHELL_UID 12587 && mUserController.hasUserRestriction( 12588 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) { 12589 continue; 12590 } 12591 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager() 12592 .queryIntentReceivers(intent, resolvedType, pmFlags, user).getList(); 12593 if (user != UserHandle.USER_SYSTEM && newReceivers != null) { 12594 // If this is not the system user, we need to check for 12595 // any receivers that should be filtered out. 12596 for (int i=0; i<newReceivers.size(); i++) { 12597 ResolveInfo ri = newReceivers.get(i); 12598 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 12599 newReceivers.remove(i); 12600 i--; 12601 } 12602 } 12603 } 12604 if (newReceivers != null && newReceivers.size() == 0) { 12605 newReceivers = null; 12606 } 12607 if (receivers == null) { 12608 receivers = newReceivers; 12609 } else if (newReceivers != null) { 12610 // We need to concatenate the additional receivers 12611 // found with what we have do far. This would be easy, 12612 // but we also need to de-dup any receivers that are 12613 // singleUser. 12614 if (!scannedFirstReceivers) { 12615 // Collect any single user receivers we had already retrieved. 12616 scannedFirstReceivers = true; 12617 for (int i=0; i<receivers.size(); i++) { 12618 ResolveInfo ri = receivers.get(i); 12619 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 12620 ComponentName cn = new ComponentName( 12621 ri.activityInfo.packageName, ri.activityInfo.name); 12622 if (singleUserReceivers == null) { 12623 singleUserReceivers = new HashSet<ComponentName>(); 12624 } 12625 singleUserReceivers.add(cn); 12626 } 12627 } 12628 } 12629 // Add the new results to the existing results, tracking 12630 // and de-dupping single user receivers. 12631 for (int i=0; i<newReceivers.size(); i++) { 12632 ResolveInfo ri = newReceivers.get(i); 12633 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 12634 ComponentName cn = new ComponentName( 12635 ri.activityInfo.packageName, ri.activityInfo.name); 12636 if (singleUserReceivers == null) { 12637 singleUserReceivers = new HashSet<ComponentName>(); 12638 } 12639 if (!singleUserReceivers.contains(cn)) { 12640 singleUserReceivers.add(cn); 12641 receivers.add(ri); 12642 } 12643 } else { 12644 receivers.add(ri); 12645 } 12646 } 12647 } 12648 } 12649 } catch (RemoteException ex) { 12650 // pm is in same process, this will never happen. 12651 } 12652 if (receivers != null && broadcastAllowList != null) { 12653 for (int i = receivers.size() - 1; i >= 0; i--) { 12654 final int receiverAppId = UserHandle.getAppId( 12655 receivers.get(i).activityInfo.applicationInfo.uid); 12656 if (receiverAppId >= Process.FIRST_APPLICATION_UID 12657 && Arrays.binarySearch(broadcastAllowList, receiverAppId) < 0) { 12658 receivers.remove(i); 12659 } 12660 } 12661 } 12662 return receivers; 12663 } 12664 checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)12665 private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, 12666 String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) { 12667 if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 12668 // Don't yell about broadcasts sent via shell 12669 return; 12670 } 12671 12672 final String action = intent.getAction(); 12673 if (isProtectedBroadcast 12674 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action) 12675 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action) 12676 || Intent.ACTION_MEDIA_BUTTON.equals(action) 12677 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action) 12678 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action) 12679 || Intent.ACTION_MASTER_CLEAR.equals(action) 12680 || Intent.ACTION_FACTORY_RESET.equals(action) 12681 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 12682 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) 12683 || TelephonyManager.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action) 12684 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action) 12685 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action) 12686 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) { 12687 // Broadcast is either protected, or it's a public action that 12688 // we've relaxed, so it's fine for system internals to send. 12689 return; 12690 } 12691 12692 // This broadcast may be a problem... but there are often system components that 12693 // want to send an internal broadcast to themselves, which is annoying to have to 12694 // explicitly list each action as a protected broadcast, so we will check for that 12695 // one safe case and allow it: an explicit broadcast, only being received by something 12696 // that has protected itself. 12697 if (intent.getPackage() != null || intent.getComponent() != null) { 12698 if (receivers == null || receivers.size() == 0) { 12699 // Intent is explicit and there's no receivers. 12700 // This happens, e.g. , when a system component sends a broadcast to 12701 // its own runtime receiver, and there's no manifest receivers for it, 12702 // because this method is called twice for each broadcast, 12703 // for runtime receivers and manifest receivers and the later check would find 12704 // no receivers. 12705 return; 12706 } 12707 boolean allProtected = true; 12708 for (int i = receivers.size()-1; i >= 0; i--) { 12709 Object target = receivers.get(i); 12710 if (target instanceof ResolveInfo) { 12711 ResolveInfo ri = (ResolveInfo)target; 12712 if (ri.activityInfo.exported && ri.activityInfo.permission == null) { 12713 allProtected = false; 12714 break; 12715 } 12716 } else { 12717 BroadcastFilter bf = (BroadcastFilter)target; 12718 if (bf.requiredPermission == null) { 12719 allProtected = false; 12720 break; 12721 } 12722 } 12723 } 12724 if (allProtected) { 12725 // All safe! 12726 return; 12727 } 12728 } 12729 12730 // The vast majority of broadcasts sent from system internals 12731 // should be protected to avoid security holes, so yell loudly 12732 // to ensure we examine these cases. 12733 if (callerApp != null) { 12734 Log.wtf(TAG, "Sending non-protected broadcast " + action 12735 + " from system " + callerApp.toShortString() + " pkg " + callerPackage, 12736 new Throwable()); 12737 } else { 12738 Log.wtf(TAG, "Sending non-protected broadcast " + action 12739 + " from system uid " + UserHandle.formatUid(callingUid) 12740 + " pkg " + callerPackage, 12741 new Throwable()); 12742 } 12743 } 12744 12745 @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, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId)12746 final int broadcastIntentLocked(ProcessRecord callerApp, 12747 String callerPackage, String callerFeatureId, Intent intent, String resolvedType, 12748 IIntentReceiver resultTo, int resultCode, String resultData, 12749 Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, 12750 int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, 12751 int callingUid, int realCallingUid, int realCallingPid, int userId) { 12752 return broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, intent, 12753 resolvedType, resultTo, resultCode, resultData, resultExtras, requiredPermissions, 12754 excludedPermissions, appOp, bOptions, ordered, sticky, callingPid, callingUid, 12755 realCallingUid, realCallingPid, userId, false /* allowBackgroundActivityStarts */, 12756 null /* tokenNeededForBackgroundActivityStarts */, null /* broadcastAllowList */); 12757 } 12758 12759 @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, 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)12760 final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, 12761 @Nullable String callerFeatureId, Intent intent, String resolvedType, 12762 IIntentReceiver resultTo, int resultCode, String resultData, 12763 Bundle resultExtras, String[] requiredPermissions, 12764 String[] excludedPermissions, int appOp, Bundle bOptions, 12765 boolean ordered, boolean sticky, int callingPid, int callingUid, 12766 int realCallingUid, int realCallingPid, int userId, 12767 boolean allowBackgroundActivityStarts, 12768 @Nullable IBinder backgroundActivityStartsToken, 12769 @Nullable int[] broadcastAllowList) { 12770 intent = new Intent(intent); 12771 12772 final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid); 12773 // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS 12774 if (callerInstantApp) { 12775 intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 12776 } 12777 12778 if (userId == UserHandle.USER_ALL && broadcastAllowList != null) { 12779 Slog.e(TAG, "broadcastAllowList only applies when sending to individual users. " 12780 + "Assuming restrictive whitelist."); 12781 broadcastAllowList = new int[]{}; 12782 } 12783 12784 // By default broadcasts do not go to stopped apps. 12785 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 12786 12787 // If we have not finished booting, don't allow this to launch new processes. 12788 if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 12789 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 12790 } 12791 12792 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 12793 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent 12794 + " ordered=" + ordered + " userid=" + userId); 12795 if ((resultTo != null) && !ordered) { 12796 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!"); 12797 } 12798 12799 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 12800 ALLOW_NON_FULL, "broadcast", callerPackage); 12801 12802 // Make sure that the user who is receiving this broadcast or its parent is running. 12803 // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps. 12804 if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) { 12805 if ((callingUid != SYSTEM_UID 12806 || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) 12807 && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { 12808 Slog.w(TAG, "Skipping broadcast of " + intent 12809 + ": user " + userId + " and its parent (if any) are stopped"); 12810 return ActivityManager.BROADCAST_FAILED_USER_STOPPED; 12811 } 12812 } 12813 12814 final String action = intent.getAction(); 12815 BroadcastOptions brOptions = null; 12816 if (bOptions != null) { 12817 brOptions = new BroadcastOptions(bOptions); 12818 if (brOptions.getTemporaryAppAllowlistDuration() > 0) { 12819 // See if the caller is allowed to do this. Note we are checking against 12820 // the actual real caller (not whoever provided the operation as say a 12821 // PendingIntent), because that who is actually supplied the arguments. 12822 if (checkComponentPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, 12823 realCallingPid, realCallingUid, -1, true) 12824 != PackageManager.PERMISSION_GRANTED 12825 && checkComponentPermission(START_ACTIVITIES_FROM_BACKGROUND, 12826 realCallingPid, realCallingUid, -1, true) 12827 != PackageManager.PERMISSION_GRANTED 12828 && checkComponentPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, 12829 realCallingPid, realCallingUid, -1, true) 12830 != PackageManager.PERMISSION_GRANTED) { 12831 String msg = "Permission Denial: " + intent.getAction() 12832 + " broadcast from " + callerPackage + " (pid=" + callingPid 12833 + ", uid=" + callingUid + ")" 12834 + " requires " 12835 + CHANGE_DEVICE_IDLE_TEMP_WHITELIST + " or " 12836 + START_ACTIVITIES_FROM_BACKGROUND + " or " 12837 + START_FOREGROUND_SERVICES_FROM_BACKGROUND; 12838 Slog.w(TAG, msg); 12839 throw new SecurityException(msg); 12840 } 12841 } 12842 if (brOptions.isDontSendToRestrictedApps() 12843 && !isUidActiveLOSP(callingUid) 12844 && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) { 12845 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage 12846 + " has background restrictions"); 12847 return ActivityManager.START_CANCELED; 12848 } 12849 if (brOptions.allowsBackgroundActivityStarts()) { 12850 // See if the caller is allowed to do this. Note we are checking against 12851 // the actual real caller (not whoever provided the operation as say a 12852 // PendingIntent), because that who is actually supplied the arguments. 12853 if (checkComponentPermission( 12854 android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND, 12855 realCallingPid, realCallingUid, -1, true) 12856 != PackageManager.PERMISSION_GRANTED) { 12857 String msg = "Permission Denial: " + intent.getAction() 12858 + " broadcast from " + callerPackage + " (pid=" + callingPid 12859 + ", uid=" + callingUid + ")" 12860 + " requires " 12861 + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; 12862 Slog.w(TAG, msg); 12863 throw new SecurityException(msg); 12864 } else { 12865 allowBackgroundActivityStarts = true; 12866 // We set the token to null since if it wasn't for it we'd allow anyway here 12867 backgroundActivityStartsToken = null; 12868 } 12869 } 12870 } 12871 12872 // Verify that protected broadcasts are only being sent by system code, 12873 // and that system code is only sending protected broadcasts. 12874 final boolean isProtectedBroadcast; 12875 try { 12876 isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action); 12877 } catch (RemoteException e) { 12878 Slog.w(TAG, "Remote exception", e); 12879 return ActivityManager.BROADCAST_SUCCESS; 12880 } 12881 12882 final boolean isCallerSystem; 12883 switch (UserHandle.getAppId(callingUid)) { 12884 case ROOT_UID: 12885 case SYSTEM_UID: 12886 case PHONE_UID: 12887 case BLUETOOTH_UID: 12888 case NFC_UID: 12889 case SE_UID: 12890 case NETWORK_STACK_UID: 12891 isCallerSystem = true; 12892 break; 12893 default: 12894 isCallerSystem = (callerApp != null) && callerApp.isPersistent(); 12895 break; 12896 } 12897 12898 // First line security check before anything else: stop non-system apps from 12899 // sending protected broadcasts. 12900 if (!isCallerSystem) { 12901 if (isProtectedBroadcast) { 12902 String msg = "Permission Denial: not allowed to send broadcast " 12903 + action + " from pid=" 12904 + callingPid + ", uid=" + callingUid; 12905 Slog.w(TAG, msg); 12906 throw new SecurityException(msg); 12907 12908 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 12909 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { 12910 // Special case for compatibility: we don't want apps to send this, 12911 // but historically it has not been protected and apps may be using it 12912 // to poke their own app widget. So, instead of making it protected, 12913 // just limit it to the caller. 12914 if (callerPackage == null) { 12915 String msg = "Permission Denial: not allowed to send broadcast " 12916 + action + " from unknown caller."; 12917 Slog.w(TAG, msg); 12918 throw new SecurityException(msg); 12919 } else if (intent.getComponent() != null) { 12920 // They are good enough to send to an explicit component... verify 12921 // it is being sent to the calling app. 12922 if (!intent.getComponent().getPackageName().equals( 12923 callerPackage)) { 12924 String msg = "Permission Denial: not allowed to send broadcast " 12925 + action + " to " 12926 + intent.getComponent().getPackageName() + " from " 12927 + callerPackage; 12928 Slog.w(TAG, msg); 12929 throw new SecurityException(msg); 12930 } 12931 } else { 12932 // Limit broadcast to their own package. 12933 intent.setPackage(callerPackage); 12934 } 12935 } 12936 } 12937 12938 boolean timeoutExempt = false; 12939 12940 if (action != null) { 12941 if (getBackgroundLaunchBroadcasts().contains(action)) { 12942 if (DEBUG_BACKGROUND_CHECK) { 12943 Slog.i(TAG, "Broadcast action " + action + " forcing include-background"); 12944 } 12945 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 12946 } 12947 12948 switch (action) { 12949 case Intent.ACTION_UID_REMOVED: 12950 case Intent.ACTION_PACKAGE_REMOVED: 12951 case Intent.ACTION_PACKAGE_CHANGED: 12952 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 12953 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 12954 case Intent.ACTION_PACKAGES_SUSPENDED: 12955 case Intent.ACTION_PACKAGES_UNSUSPENDED: 12956 // Handle special intents: if this broadcast is from the package 12957 // manager about a package being removed, we need to remove all of 12958 // its activities from the history stack. 12959 if (checkComponentPermission( 12960 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 12961 callingPid, callingUid, -1, true) 12962 != PackageManager.PERMISSION_GRANTED) { 12963 String msg = "Permission Denial: " + intent.getAction() 12964 + " broadcast from " + callerPackage + " (pid=" + callingPid 12965 + ", uid=" + callingUid + ")" 12966 + " requires " 12967 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 12968 Slog.w(TAG, msg); 12969 throw new SecurityException(msg); 12970 } 12971 switch (action) { 12972 case Intent.ACTION_UID_REMOVED: 12973 final int uid = getUidFromIntent(intent); 12974 if (uid >= 0) { 12975 mBatteryStatsService.removeUid(uid); 12976 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 12977 mAppOpsService.resetAllModes(UserHandle.getUserId(uid), 12978 intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME)); 12979 } else { 12980 mAppOpsService.uidRemoved(uid); 12981 } 12982 } 12983 break; 12984 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 12985 // If resources are unavailable just force stop all those packages 12986 // and flush the attribute cache as well. 12987 String list[] = 12988 intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 12989 if (list != null && list.length > 0) { 12990 for (int i = 0; i < list.length; i++) { 12991 forceStopPackageLocked(list[i], -1, false, true, true, 12992 false, false, userId, "storage unmount"); 12993 } 12994 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 12995 sendPackageBroadcastLocked( 12996 ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE, 12997 list, userId); 12998 } 12999 break; 13000 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 13001 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 13002 break; 13003 case Intent.ACTION_PACKAGE_REMOVED: 13004 case Intent.ACTION_PACKAGE_CHANGED: 13005 Uri data = intent.getData(); 13006 String ssp; 13007 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 13008 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action); 13009 final boolean replacing = 13010 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 13011 final boolean killProcess = 13012 !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false); 13013 final boolean fullUninstall = removed && !replacing; 13014 if (removed) { 13015 if (killProcess) { 13016 forceStopPackageLocked(ssp, UserHandle.getAppId( 13017 intent.getIntExtra(Intent.EXTRA_UID, -1)), 13018 false, true, true, false, fullUninstall, userId, 13019 removed ? "pkg removed" : "pkg changed"); 13020 } else { 13021 // Kill any app zygotes always, since they can't fork new 13022 // processes with references to the old code 13023 forceStopAppZygoteLocked(ssp, UserHandle.getAppId( 13024 intent.getIntExtra(Intent.EXTRA_UID, -1)), 13025 userId); 13026 } 13027 final int cmd = killProcess 13028 ? ApplicationThreadConstants.PACKAGE_REMOVED 13029 : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL; 13030 sendPackageBroadcastLocked(cmd, 13031 new String[] {ssp}, userId); 13032 if (fullUninstall) { 13033 mAppOpsService.packageRemoved( 13034 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp); 13035 13036 // Remove all permissions granted from/to this package 13037 mUgmInternal.removeUriPermissionsForPackage(ssp, userId, 13038 true, false); 13039 13040 mAtmInternal.removeRecentTasksByPackageName(ssp, userId); 13041 13042 mServices.forceStopPackageLocked(ssp, userId); 13043 mAtmInternal.onPackageUninstalled(ssp); 13044 mBatteryStatsService.notePackageUninstalled(ssp); 13045 } 13046 } else { 13047 if (killProcess) { 13048 final int extraUid = intent.getIntExtra(Intent.EXTRA_UID, 13049 -1); 13050 synchronized (mProcLock) { 13051 mProcessList.killPackageProcessesLSP(ssp, 13052 UserHandle.getAppId(extraUid), 13053 userId, ProcessList.INVALID_ADJ, 13054 ApplicationExitInfo.REASON_USER_REQUESTED, 13055 ApplicationExitInfo.SUBREASON_UNKNOWN, 13056 "change " + ssp); 13057 } 13058 } 13059 cleanupDisabledPackageComponentsLocked(ssp, userId, 13060 intent.getStringArrayExtra( 13061 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST)); 13062 mServices.schedulePendingServiceStartLocked(ssp, userId); 13063 } 13064 } 13065 break; 13066 case Intent.ACTION_PACKAGES_SUSPENDED: 13067 case Intent.ACTION_PACKAGES_UNSUSPENDED: 13068 final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals( 13069 intent.getAction()); 13070 final String[] packageNames = intent.getStringArrayExtra( 13071 Intent.EXTRA_CHANGED_PACKAGE_LIST); 13072 final int userIdExtra = intent.getIntExtra( 13073 Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 13074 13075 mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended, 13076 userIdExtra); 13077 break; 13078 } 13079 break; 13080 case Intent.ACTION_PACKAGE_REPLACED: 13081 { 13082 final Uri data = intent.getData(); 13083 final String ssp; 13084 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 13085 ApplicationInfo aInfo = null; 13086 try { 13087 aInfo = AppGlobals.getPackageManager() 13088 .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId); 13089 } catch (RemoteException ignore) {} 13090 if (aInfo == null) { 13091 Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:" 13092 + " ssp=" + ssp + " data=" + data); 13093 return ActivityManager.BROADCAST_SUCCESS; 13094 } 13095 updateAssociationForApp(aInfo); 13096 mAtmInternal.onPackageReplaced(aInfo); 13097 mServices.updateServiceApplicationInfoLocked(aInfo); 13098 sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED, 13099 new String[] {ssp}, userId); 13100 } 13101 break; 13102 } 13103 case Intent.ACTION_PACKAGE_ADDED: 13104 { 13105 // Special case for adding a package: by default turn on compatibility mode. 13106 Uri data = intent.getData(); 13107 String ssp; 13108 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 13109 final boolean replacing = 13110 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 13111 mAtmInternal.onPackageAdded(ssp, replacing); 13112 13113 try { 13114 ApplicationInfo ai = AppGlobals.getPackageManager(). 13115 getApplicationInfo(ssp, STOCK_PM_FLAGS, 0); 13116 mBatteryStatsService.notePackageInstalled(ssp, 13117 ai != null ? ai.longVersionCode : 0); 13118 } catch (RemoteException e) { 13119 } 13120 } 13121 break; 13122 } 13123 case Intent.ACTION_PACKAGE_DATA_CLEARED: 13124 { 13125 Uri data = intent.getData(); 13126 String ssp; 13127 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 13128 mAtmInternal.onPackageDataCleared(ssp); 13129 } 13130 break; 13131 } 13132 case Intent.ACTION_TIMEZONE_CHANGED: 13133 // If this is the time zone changed action, queue up a message that will reset 13134 // the timezone of all currently running processes. This message will get 13135 // queued up before the broadcast happens. 13136 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 13137 break; 13138 case Intent.ACTION_TIME_CHANGED: 13139 // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between 13140 // the tri-state value it may contain and "unknown". 13141 // For convenience we re-use the Intent extra values. 13142 final int NO_EXTRA_VALUE_FOUND = -1; 13143 final int timeFormatPreferenceMsgValue = intent.getIntExtra( 13144 Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, 13145 NO_EXTRA_VALUE_FOUND /* defaultValue */); 13146 // Only send a message if the time preference is available. 13147 if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) { 13148 Message updateTimePreferenceMsg = 13149 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG, 13150 timeFormatPreferenceMsgValue, 0); 13151 mHandler.sendMessage(updateTimePreferenceMsg); 13152 } 13153 mBatteryStatsService.noteCurrentTimeChanged(); 13154 break; 13155 case ConnectivityManager.ACTION_CLEAR_DNS_CACHE: 13156 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 13157 break; 13158 case Proxy.PROXY_CHANGE_ACTION: 13159 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG)); 13160 break; 13161 case android.hardware.Camera.ACTION_NEW_PICTURE: 13162 case android.hardware.Camera.ACTION_NEW_VIDEO: 13163 // In N we just turned these off; in O we are turing them back on partly, 13164 // only for registered receivers. This will still address the main problem 13165 // (a spam of apps waking up when a picture is taken putting significant 13166 // memory pressure on the system at a bad point), while still allowing apps 13167 // that are already actively running to know about this happening. 13168 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 13169 break; 13170 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED: 13171 mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG); 13172 break; 13173 case "com.android.launcher.action.INSTALL_SHORTCUT": 13174 // As of O, we no longer support this broadcasts, even for pre-O apps. 13175 // Apps should now be using ShortcutManager.pinRequestShortcut(). 13176 Log.w(TAG, "Broadcast " + action 13177 + " no longer supported. It will not be delivered."); 13178 return ActivityManager.BROADCAST_SUCCESS; 13179 case Intent.ACTION_PRE_BOOT_COMPLETED: 13180 timeoutExempt = true; 13181 break; 13182 case Intent.ACTION_CLOSE_SYSTEM_DIALOGS: 13183 if (!mAtmInternal.checkCanCloseSystemDialogs(callingPid, callingUid, 13184 callerPackage)) { 13185 // Returning success seems to be the pattern here 13186 return ActivityManager.BROADCAST_SUCCESS; 13187 } 13188 break; 13189 } 13190 13191 if (Intent.ACTION_PACKAGE_ADDED.equals(action) || 13192 Intent.ACTION_PACKAGE_REMOVED.equals(action) || 13193 Intent.ACTION_PACKAGE_REPLACED.equals(action)) { 13194 final int uid = getUidFromIntent(intent); 13195 if (uid != -1) { 13196 final UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 13197 if (uidRec != null) { 13198 uidRec.updateHasInternetPermission(); 13199 } 13200 } 13201 } 13202 } 13203 13204 // Add to the sticky list if requested. 13205 if (sticky) { 13206 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY, 13207 callingPid, callingUid) 13208 != PackageManager.PERMISSION_GRANTED) { 13209 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid=" 13210 + callingPid + ", uid=" + callingUid 13211 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 13212 Slog.w(TAG, msg); 13213 throw new SecurityException(msg); 13214 } 13215 if (requiredPermissions != null && requiredPermissions.length > 0) { 13216 Slog.w(TAG, "Can't broadcast sticky intent " + intent 13217 + " and enforce permissions " + Arrays.toString(requiredPermissions)); 13218 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 13219 } 13220 if (intent.getComponent() != null) { 13221 throw new SecurityException( 13222 "Sticky broadcasts can't target a specific component"); 13223 } 13224 // We use userId directly here, since the "all" target is maintained 13225 // as a separate set of sticky broadcasts. 13226 if (userId != UserHandle.USER_ALL) { 13227 // But first, if this is not a broadcast to all users, then 13228 // make sure it doesn't conflict with an existing broadcast to 13229 // all users. 13230 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get( 13231 UserHandle.USER_ALL); 13232 if (stickies != null) { 13233 ArrayList<Intent> list = stickies.get(intent.getAction()); 13234 if (list != null) { 13235 int N = list.size(); 13236 int i; 13237 for (i=0; i<N; i++) { 13238 if (intent.filterEquals(list.get(i))) { 13239 throw new IllegalArgumentException( 13240 "Sticky broadcast " + intent + " for user " 13241 + userId + " conflicts with existing global broadcast"); 13242 } 13243 } 13244 } 13245 } 13246 } 13247 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 13248 if (stickies == null) { 13249 stickies = new ArrayMap<>(); 13250 mStickyBroadcasts.put(userId, stickies); 13251 } 13252 ArrayList<Intent> list = stickies.get(intent.getAction()); 13253 if (list == null) { 13254 list = new ArrayList<>(); 13255 stickies.put(intent.getAction(), list); 13256 } 13257 final int stickiesCount = list.size(); 13258 int i; 13259 for (i = 0; i < stickiesCount; i++) { 13260 if (intent.filterEquals(list.get(i))) { 13261 // This sticky already exists, replace it. 13262 list.set(i, new Intent(intent)); 13263 break; 13264 } 13265 } 13266 if (i >= stickiesCount) { 13267 list.add(new Intent(intent)); 13268 } 13269 } 13270 13271 int[] users; 13272 if (userId == UserHandle.USER_ALL) { 13273 // Caller wants broadcast to go to all started users. 13274 users = mUserController.getStartedUserArray(); 13275 } else { 13276 // Caller wants broadcast to go to one specific user. 13277 users = new int[] {userId}; 13278 } 13279 13280 // Figure out who all will receive this broadcast. 13281 List receivers = null; 13282 List<BroadcastFilter> registeredReceivers = null; 13283 // Need to resolve the intent to interested receivers... 13284 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) 13285 == 0) { 13286 receivers = collectReceiverComponents( 13287 intent, resolvedType, callingUid, users, broadcastAllowList); 13288 } 13289 if (intent.getComponent() == null) { 13290 if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) { 13291 // Query one target user at a time, excluding shell-restricted users 13292 for (int i = 0; i < users.length; i++) { 13293 if (mUserController.hasUserRestriction( 13294 UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) { 13295 continue; 13296 } 13297 List<BroadcastFilter> registeredReceiversForUser = 13298 mReceiverResolver.queryIntent(intent, 13299 resolvedType, false /*defaultOnly*/, users[i]); 13300 if (registeredReceivers == null) { 13301 registeredReceivers = registeredReceiversForUser; 13302 } else if (registeredReceiversForUser != null) { 13303 registeredReceivers.addAll(registeredReceiversForUser); 13304 } 13305 } 13306 } else { 13307 registeredReceivers = mReceiverResolver.queryIntent(intent, 13308 resolvedType, false /*defaultOnly*/, userId); 13309 } 13310 } 13311 13312 final boolean replacePending = 13313 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 13314 13315 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction() 13316 + " replacePending=" + replacePending); 13317 if (registeredReceivers != null && broadcastAllowList != null) { 13318 // if a uid whitelist was provided, remove anything in the application space that wasn't 13319 // in it. 13320 for (int i = registeredReceivers.size() - 1; i >= 0; i--) { 13321 final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid); 13322 if (owningAppId >= Process.FIRST_APPLICATION_UID 13323 && Arrays.binarySearch(broadcastAllowList, owningAppId) < 0) { 13324 registeredReceivers.remove(i); 13325 } 13326 } 13327 } 13328 13329 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 13330 if (!ordered && NR > 0) { 13331 // If we are not serializing this broadcast, then send the 13332 // registered receivers separately so they don't wait for the 13333 // components to be launched. 13334 if (isCallerSystem) { 13335 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid, 13336 isProtectedBroadcast, registeredReceivers); 13337 } 13338 final BroadcastQueue queue = broadcastQueueForIntent(intent); 13339 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, 13340 callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType, 13341 requiredPermissions, excludedPermissions, appOp, brOptions, registeredReceivers, 13342 resultTo, resultCode, resultData, resultExtras, ordered, sticky, false, userId, 13343 allowBackgroundActivityStarts, backgroundActivityStartsToken, 13344 timeoutExempt); 13345 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r); 13346 final boolean replaced = replacePending 13347 && (queue.replaceParallelBroadcastLocked(r) != null); 13348 // Note: We assume resultTo is null for non-ordered broadcasts. 13349 if (!replaced) { 13350 queue.enqueueParallelBroadcastLocked(r); 13351 queue.scheduleBroadcastsLocked(); 13352 } 13353 registeredReceivers = null; 13354 NR = 0; 13355 } 13356 13357 // Merge into one list. 13358 int ir = 0; 13359 if (receivers != null) { 13360 // A special case for PACKAGE_ADDED: do not allow the package 13361 // being added to see this broadcast. This prevents them from 13362 // using this as a back door to get run as soon as they are 13363 // installed. Maybe in the future we want to have a special install 13364 // broadcast or such for apps, but we'd like to deliberately make 13365 // this decision. 13366 String skipPackages[] = null; 13367 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 13368 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 13369 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 13370 Uri data = intent.getData(); 13371 if (data != null) { 13372 String pkgName = data.getSchemeSpecificPart(); 13373 if (pkgName != null) { 13374 skipPackages = new String[] { pkgName }; 13375 } 13376 } 13377 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 13378 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 13379 } 13380 if (skipPackages != null && (skipPackages.length > 0)) { 13381 for (String skipPackage : skipPackages) { 13382 if (skipPackage != null) { 13383 int NT = receivers.size(); 13384 for (int it=0; it<NT; it++) { 13385 ResolveInfo curt = (ResolveInfo)receivers.get(it); 13386 if (curt.activityInfo.packageName.equals(skipPackage)) { 13387 receivers.remove(it); 13388 it--; 13389 NT--; 13390 } 13391 } 13392 } 13393 } 13394 } 13395 13396 int NT = receivers != null ? receivers.size() : 0; 13397 int it = 0; 13398 ResolveInfo curt = null; 13399 BroadcastFilter curr = null; 13400 while (it < NT && ir < NR) { 13401 if (curt == null) { 13402 curt = (ResolveInfo)receivers.get(it); 13403 } 13404 if (curr == null) { 13405 curr = registeredReceivers.get(ir); 13406 } 13407 if (curr.getPriority() >= curt.priority) { 13408 // Insert this broadcast record into the final list. 13409 receivers.add(it, curr); 13410 ir++; 13411 curr = null; 13412 it++; 13413 NT++; 13414 } else { 13415 // Skip to the next ResolveInfo in the final list. 13416 it++; 13417 curt = null; 13418 } 13419 } 13420 } 13421 while (ir < NR) { 13422 if (receivers == null) { 13423 receivers = new ArrayList(); 13424 } 13425 receivers.add(registeredReceivers.get(ir)); 13426 ir++; 13427 } 13428 13429 if (isCallerSystem) { 13430 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid, 13431 isProtectedBroadcast, receivers); 13432 } 13433 13434 if ((receivers != null && receivers.size() > 0) 13435 || resultTo != null) { 13436 BroadcastQueue queue = broadcastQueueForIntent(intent); 13437 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, 13438 callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType, 13439 requiredPermissions, excludedPermissions, appOp, brOptions, 13440 receivers, resultTo, resultCode, resultData, resultExtras, 13441 ordered, sticky, false, userId, allowBackgroundActivityStarts, 13442 backgroundActivityStartsToken, timeoutExempt); 13443 13444 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r); 13445 13446 final BroadcastRecord oldRecord = 13447 replacePending ? queue.replaceOrderedBroadcastLocked(r) : null; 13448 if (oldRecord != null) { 13449 // Replaced, fire the result-to receiver. 13450 if (oldRecord.resultTo != null) { 13451 final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent); 13452 try { 13453 oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo, 13454 oldRecord.intent, 13455 Activity.RESULT_CANCELED, null, null, 13456 false, false, oldRecord.userId); 13457 } catch (RemoteException e) { 13458 Slog.w(TAG, "Failure [" 13459 + queue.mQueueName + "] sending broadcast result of " 13460 + intent, e); 13461 13462 } 13463 } 13464 } else { 13465 queue.enqueueOrderedBroadcastLocked(r); 13466 queue.scheduleBroadcastsLocked(); 13467 } 13468 } else { 13469 // There was nobody interested in the broadcast, but we still want to record 13470 // that it happened. 13471 if (intent.getComponent() == null && intent.getPackage() == null 13472 && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 13473 // This was an implicit broadcast... let's record it for posterity. 13474 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0); 13475 } 13476 } 13477 13478 return ActivityManager.BROADCAST_SUCCESS; 13479 } 13480 13481 /** 13482 * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1 13483 */ getUidFromIntent(Intent intent)13484 private int getUidFromIntent(Intent intent) { 13485 if (intent == null) { 13486 return -1; 13487 } 13488 final Bundle intentExtras = intent.getExtras(); 13489 return intent.hasExtra(Intent.EXTRA_UID) 13490 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 13491 } 13492 rotateBroadcastStatsIfNeededLocked()13493 final void rotateBroadcastStatsIfNeededLocked() { 13494 final long now = SystemClock.elapsedRealtime(); 13495 if (mCurBroadcastStats == null || 13496 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) { 13497 mLastBroadcastStats = mCurBroadcastStats; 13498 if (mLastBroadcastStats != null) { 13499 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime(); 13500 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis(); 13501 } 13502 mCurBroadcastStats = new BroadcastStats(); 13503 } 13504 } 13505 addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)13506 final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount, 13507 int skipCount, long dispatchTime) { 13508 rotateBroadcastStatsIfNeededLocked(); 13509 mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime); 13510 } 13511 addBackgroundCheckViolationLocked(String action, String targetPackage)13512 final void addBackgroundCheckViolationLocked(String action, String targetPackage) { 13513 rotateBroadcastStatsIfNeededLocked(); 13514 mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage); 13515 } 13516 verifyBroadcastLocked(Intent intent)13517 final Intent verifyBroadcastLocked(Intent intent) { 13518 // Refuse possible leaked file descriptors 13519 if (intent != null && intent.hasFileDescriptors() == true) { 13520 throw new IllegalArgumentException("File descriptors passed in Intent"); 13521 } 13522 13523 int flags = intent.getFlags(); 13524 13525 if (!mProcessesReady) { 13526 // if the caller really truly claims to know what they're doing, go 13527 // ahead and allow the broadcast without launching any receivers 13528 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 13529 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed. 13530 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 13531 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 13532 + " before boot completion"); 13533 throw new IllegalStateException("Cannot broadcast before boot completed"); 13534 } 13535 } 13536 13537 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 13538 throw new IllegalArgumentException( 13539 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 13540 } 13541 13542 if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 13543 switch (Binder.getCallingUid()) { 13544 case ROOT_UID: 13545 case SHELL_UID: 13546 break; 13547 default: 13548 Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID " 13549 + Binder.getCallingUid()); 13550 intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL); 13551 break; 13552 } 13553 } 13554 13555 return intent; 13556 } 13557 13558 /** 13559 * @deprecated Use {@link #broadcastIntentWithFeature} 13560 */ 13561 @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)13562 public final int broadcastIntent(IApplicationThread caller, 13563 Intent intent, String resolvedType, IIntentReceiver resultTo, 13564 int resultCode, String resultData, Bundle resultExtras, 13565 String[] requiredPermissions, int appOp, Bundle bOptions, 13566 boolean serialized, boolean sticky, int userId) { 13567 return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode, 13568 resultData, resultExtras, requiredPermissions, null, appOp, bOptions, serialized, 13569 sticky, userId); 13570 } 13571 broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, int appOp, Bundle bOptions, boolean serialized, boolean sticky, int userId)13572 public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, 13573 Intent intent, String resolvedType, IIntentReceiver resultTo, 13574 int resultCode, String resultData, Bundle resultExtras, 13575 String[] requiredPermissions, String[] excludedPermissions, int appOp, Bundle bOptions, 13576 boolean serialized, boolean sticky, int userId) { 13577 enforceNotIsolatedCaller("broadcastIntent"); 13578 synchronized(this) { 13579 intent = verifyBroadcastLocked(intent); 13580 13581 final ProcessRecord callerApp = getRecordForAppLOSP(caller); 13582 final int callingPid = Binder.getCallingPid(); 13583 final int callingUid = Binder.getCallingUid(); 13584 13585 final long origId = Binder.clearCallingIdentity(); 13586 try { 13587 return broadcastIntentLocked(callerApp, 13588 callerApp != null ? callerApp.info.packageName : null, callingFeatureId, 13589 intent, resolvedType, resultTo, resultCode, resultData, resultExtras, 13590 requiredPermissions, excludedPermissions, appOp, bOptions, serialized, 13591 sticky, callingPid, callingUid, callingUid, callingPid, userId); 13592 } finally { 13593 Binder.restoreCallingIdentity(origId); 13594 } 13595 } 13596 } 13597 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)13598 int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, 13599 int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 13600 IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, 13601 String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, 13602 int userId, boolean allowBackgroundActivityStarts, 13603 @Nullable IBinder backgroundActivityStartsToken) { 13604 synchronized(this) { 13605 intent = verifyBroadcastLocked(intent); 13606 13607 final long origId = Binder.clearCallingIdentity(); 13608 String[] requiredPermissions = requiredPermission == null ? null 13609 : new String[] {requiredPermission}; 13610 try { 13611 return broadcastIntentLocked(null, packageName, featureId, intent, resolvedType, 13612 resultTo, resultCode, resultData, resultExtras, requiredPermissions, null, 13613 OP_NONE, bOptions, serialized, sticky, -1, uid, realCallingUid, 13614 realCallingPid, userId, allowBackgroundActivityStarts, 13615 backgroundActivityStartsToken, 13616 null /* broadcastAllowList */); 13617 } finally { 13618 Binder.restoreCallingIdentity(origId); 13619 } 13620 } 13621 } 13622 unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)13623 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 13624 // Refuse possible leaked file descriptors 13625 if (intent != null && intent.hasFileDescriptors() == true) { 13626 throw new IllegalArgumentException("File descriptors passed in Intent"); 13627 } 13628 13629 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 13630 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null); 13631 13632 synchronized(this) { 13633 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 13634 != PackageManager.PERMISSION_GRANTED) { 13635 String msg = "Permission Denial: unbroadcastIntent() from pid=" 13636 + Binder.getCallingPid() 13637 + ", uid=" + Binder.getCallingUid() 13638 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 13639 Slog.w(TAG, msg); 13640 throw new SecurityException(msg); 13641 } 13642 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 13643 if (stickies != null) { 13644 ArrayList<Intent> list = stickies.get(intent.getAction()); 13645 if (list != null) { 13646 int N = list.size(); 13647 int i; 13648 for (i=0; i<N; i++) { 13649 if (intent.filterEquals(list.get(i))) { 13650 list.remove(i); 13651 break; 13652 } 13653 } 13654 if (list.size() <= 0) { 13655 stickies.remove(intent.getAction()); 13656 } 13657 } 13658 if (stickies.size() <= 0) { 13659 mStickyBroadcasts.remove(userId); 13660 } 13661 } 13662 } 13663 } 13664 backgroundServicesFinishedLocked(int userId)13665 void backgroundServicesFinishedLocked(int userId) { 13666 for (BroadcastQueue queue : mBroadcastQueues) { 13667 queue.backgroundServicesFinishedLocked(userId); 13668 } 13669 } 13670 finishReceiver(IBinder who, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)13671 public void finishReceiver(IBinder who, int resultCode, String resultData, 13672 Bundle resultExtras, boolean resultAbort, int flags) { 13673 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who); 13674 13675 // Refuse possible leaked file descriptors 13676 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 13677 throw new IllegalArgumentException("File descriptors passed in Bundle"); 13678 } 13679 13680 final long origId = Binder.clearCallingIdentity(); 13681 try { 13682 boolean doNext = false; 13683 BroadcastRecord r; 13684 BroadcastQueue queue; 13685 13686 synchronized(this) { 13687 if (isOnOffloadQueue(flags)) { 13688 queue = mOffloadBroadcastQueue; 13689 } else { 13690 queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0 13691 ? mFgBroadcastQueue : mBgBroadcastQueue; 13692 } 13693 13694 r = queue.getMatchingOrderedReceiver(who); 13695 if (r != null) { 13696 doNext = r.queue.finishReceiverLocked(r, resultCode, 13697 resultData, resultExtras, resultAbort, true); 13698 } 13699 if (doNext) { 13700 r.queue.processNextBroadcastLocked(/*fromMsg=*/ false, /*skipOomAdj=*/ true); 13701 } 13702 // updateOomAdjLocked() will be done here 13703 trimApplicationsLocked(false, OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER); 13704 } 13705 13706 } finally { 13707 Binder.restoreCallingIdentity(origId); 13708 } 13709 } 13710 13711 // ========================================================= 13712 // INSTRUMENTATION 13713 // ========================================================= 13714 startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)13715 public boolean startInstrumentation(ComponentName className, 13716 String profileFile, int flags, Bundle arguments, 13717 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 13718 int userId, String abiOverride) { 13719 enforceNotIsolatedCaller("startInstrumentation"); 13720 final int callingUid = Binder.getCallingUid(); 13721 final int callingPid = Binder.getCallingPid(); 13722 userId = mUserController.handleIncomingUser(callingPid, callingUid, 13723 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 13724 // Refuse possible leaked file descriptors 13725 if (arguments != null && arguments.hasFileDescriptors()) { 13726 throw new IllegalArgumentException("File descriptors passed in Bundle"); 13727 } 13728 13729 synchronized(this) { 13730 InstrumentationInfo ii = null; 13731 ApplicationInfo ai = null; 13732 13733 boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0; 13734 13735 try { 13736 ii = mContext.getPackageManager().getInstrumentationInfo( 13737 className, STOCK_PM_FLAGS); 13738 ai = AppGlobals.getPackageManager().getApplicationInfo( 13739 ii.targetPackage, STOCK_PM_FLAGS, userId); 13740 } catch (PackageManager.NameNotFoundException e) { 13741 } catch (RemoteException e) { 13742 } 13743 if (ii == null) { 13744 reportStartInstrumentationFailureLocked(watcher, className, 13745 "Unable to find instrumentation info for: " + className); 13746 return false; 13747 } 13748 if (ai == null) { 13749 reportStartInstrumentationFailureLocked(watcher, className, 13750 "Unable to find instrumentation target package: " + ii.targetPackage); 13751 return false; 13752 } 13753 13754 if (ii.targetPackage.equals("android")) { 13755 if (!noRestart) { 13756 reportStartInstrumentationFailureLocked(watcher, className, 13757 "Cannot instrument system server without 'no-restart'"); 13758 return false; 13759 } 13760 } else if (!ai.hasCode()) { 13761 reportStartInstrumentationFailureLocked(watcher, className, 13762 "Instrumentation target has no code: " + ii.targetPackage); 13763 return false; 13764 } 13765 13766 if (!Build.IS_DEBUGGABLE) { 13767 int match = mContext.getPackageManager().checkSignatures( 13768 ii.targetPackage, ii.packageName); 13769 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 13770 String msg = "Permission Denial: starting instrumentation " 13771 + className + " from pid=" 13772 + Binder.getCallingPid() 13773 + ", uid=" + Binder.getCallingPid() 13774 + " not allowed because package " + ii.packageName 13775 + " does not have a signature matching the target " 13776 + ii.targetPackage; 13777 reportStartInstrumentationFailureLocked(watcher, className, msg); 13778 throw new SecurityException(msg); 13779 } 13780 } 13781 13782 ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); 13783 activeInstr.mClass = className; 13784 String defProcess = ai.processName;; 13785 if (ii.targetProcesses == null) { 13786 activeInstr.mTargetProcesses = new String[]{ai.processName}; 13787 } else if (ii.targetProcesses.equals("*")) { 13788 activeInstr.mTargetProcesses = new String[0]; 13789 } else { 13790 activeInstr.mTargetProcesses = ii.targetProcesses.split(","); 13791 defProcess = activeInstr.mTargetProcesses[0]; 13792 } 13793 activeInstr.mTargetInfo = ai; 13794 activeInstr.mProfileFile = profileFile; 13795 activeInstr.mArguments = arguments; 13796 activeInstr.mWatcher = watcher; 13797 activeInstr.mUiAutomationConnection = uiAutomationConnection; 13798 activeInstr.mResultClass = className; 13799 activeInstr.mHasBackgroundActivityStartsPermission = checkPermission( 13800 START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid) 13801 == PackageManager.PERMISSION_GRANTED; 13802 activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission( 13803 START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid) 13804 == PackageManager.PERMISSION_GRANTED; 13805 activeInstr.mNoRestart = noRestart; 13806 boolean disableHiddenApiChecks = ai.usesNonSdkApi() 13807 || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0; 13808 boolean disableTestApiChecks = disableHiddenApiChecks 13809 || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0; 13810 13811 if (disableHiddenApiChecks || disableTestApiChecks) { 13812 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS, 13813 "disable hidden API checks"); 13814 } 13815 13816 final long origId = Binder.clearCallingIdentity(); 13817 13818 ProcessRecord app; 13819 synchronized (mProcLock) { 13820 if (noRestart) { 13821 app = getProcessRecordLocked(ai.processName, ai.uid); 13822 } else { 13823 // Instrumentation can kill and relaunch even persistent processes 13824 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, 13825 userId, "start instr"); 13826 // Inform usage stats to make the target package active 13827 if (mUsageStatsService != null) { 13828 mUsageStatsService.reportEvent(ii.targetPackage, userId, 13829 UsageEvents.Event.SYSTEM_INTERACTION); 13830 } 13831 app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks, 13832 disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY); 13833 } 13834 13835 app.setActiveInstrumentation(activeInstr); 13836 activeInstr.mFinished = false; 13837 activeInstr.mSourceUid = callingUid; 13838 activeInstr.mRunningProcesses.add(app); 13839 if (!mActiveInstrumentation.contains(activeInstr)) { 13840 mActiveInstrumentation.add(activeInstr); 13841 } 13842 } 13843 13844 if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) { 13845 // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with 13846 // --no-isolated-storage flag. 13847 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid, 13848 ii.packageName, AppOpsManager.MODE_ALLOWED); 13849 } 13850 Binder.restoreCallingIdentity(origId); 13851 13852 if (noRestart) { 13853 instrumentWithoutRestart(activeInstr, ai); 13854 } 13855 } 13856 13857 return true; 13858 } 13859 instrumentWithoutRestart(ActiveInstrumentation activeInstr, ApplicationInfo targetInfo)13860 private void instrumentWithoutRestart(ActiveInstrumentation activeInstr, 13861 ApplicationInfo targetInfo) { 13862 ProcessRecord pr; 13863 synchronized (this) { 13864 pr = getProcessRecordLocked(targetInfo.processName, targetInfo.uid); 13865 } 13866 13867 try { 13868 pr.getThread().instrumentWithoutRestart( 13869 activeInstr.mClass, 13870 activeInstr.mArguments, 13871 activeInstr.mWatcher, 13872 activeInstr.mUiAutomationConnection, 13873 targetInfo); 13874 } catch (RemoteException e) { 13875 Slog.i(TAG, "RemoteException from instrumentWithoutRestart", e); 13876 } 13877 } 13878 isCallerShell()13879 private boolean isCallerShell() { 13880 final int callingUid = Binder.getCallingUid(); 13881 return callingUid == SHELL_UID || callingUid == ROOT_UID; 13882 } 13883 13884 /** 13885 * Report errors that occur while attempting to start Instrumentation. Always writes the 13886 * error to the logs, but if somebody is watching, send the report there too. This enables 13887 * the "am" command to report errors with more information. 13888 * 13889 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 13890 * @param cn The component name of the instrumentation. 13891 * @param report The error report. 13892 */ reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)13893 private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, 13894 ComponentName cn, String report) { 13895 Slog.w(TAG, report); 13896 if (watcher != null) { 13897 Bundle results = new Bundle(); 13898 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 13899 results.putString("Error", report); 13900 mInstrumentationReporter.reportStatus(watcher, cn, -1, results); 13901 } 13902 } 13903 addInstrumentationResultsLocked(ProcessRecord app, Bundle results)13904 void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) { 13905 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 13906 if (instr == null) { 13907 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 13908 return; 13909 } 13910 13911 if (!instr.mFinished && results != null) { 13912 if (instr.mCurResults == null) { 13913 instr.mCurResults = new Bundle(results); 13914 } else { 13915 instr.mCurResults.putAll(results); 13916 } 13917 } 13918 } 13919 addInstrumentationResults(IApplicationThread target, Bundle results)13920 public void addInstrumentationResults(IApplicationThread target, Bundle results) { 13921 int userId = UserHandle.getCallingUserId(); 13922 // Refuse possible leaked file descriptors 13923 if (results != null && results.hasFileDescriptors()) { 13924 throw new IllegalArgumentException("File descriptors passed in Intent"); 13925 } 13926 13927 synchronized(this) { 13928 ProcessRecord app = getRecordForAppLOSP(target); 13929 if (app == null) { 13930 Slog.w(TAG, "addInstrumentationResults: no app for " + target); 13931 return; 13932 } 13933 final long origId = Binder.clearCallingIdentity(); 13934 try { 13935 addInstrumentationResultsLocked(app, results); 13936 } finally { 13937 Binder.restoreCallingIdentity(origId); 13938 } 13939 } 13940 } 13941 13942 @GuardedBy("this") finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)13943 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 13944 final ActiveInstrumentation instr = app.getActiveInstrumentation(); 13945 if (instr == null) { 13946 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app); 13947 return; 13948 } 13949 13950 synchronized (mProcLock) { 13951 if (!instr.mFinished) { 13952 if (instr.mWatcher != null) { 13953 Bundle finalResults = instr.mCurResults; 13954 if (finalResults != null) { 13955 if (instr.mCurResults != null && results != null) { 13956 finalResults.putAll(results); 13957 } 13958 } else { 13959 finalResults = results; 13960 } 13961 mInstrumentationReporter.reportFinished(instr.mWatcher, 13962 instr.mClass, resultCode, finalResults); 13963 } 13964 13965 // Can't call out of the system process with a lock held, so post a message. 13966 if (instr.mUiAutomationConnection != null) { 13967 // Go back to the default mode of denying OP_NO_ISOLATED_STORAGE app op. 13968 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, app.uid, 13969 app.info.packageName, AppOpsManager.MODE_ERRORED); 13970 mAppOpsService.setAppOpsServiceDelegate(null); 13971 getPermissionManagerInternal().stopShellPermissionIdentityDelegation(); 13972 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG, 13973 instr.mUiAutomationConnection).sendToTarget(); 13974 } 13975 instr.mFinished = true; 13976 } 13977 13978 instr.removeProcess(app); 13979 app.setActiveInstrumentation(null); 13980 } 13981 13982 if (!instr.mNoRestart) { 13983 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, 13984 app.userId, 13985 "finished inst"); 13986 } 13987 } 13988 finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)13989 public void finishInstrumentation(IApplicationThread target, 13990 int resultCode, Bundle results) { 13991 int userId = UserHandle.getCallingUserId(); 13992 // Refuse possible leaked file descriptors 13993 if (results != null && results.hasFileDescriptors()) { 13994 throw new IllegalArgumentException("File descriptors passed in Intent"); 13995 } 13996 13997 synchronized(this) { 13998 ProcessRecord app = getRecordForAppLOSP(target); 13999 if (app == null) { 14000 Slog.w(TAG, "finishInstrumentation: no app for " + target); 14001 return; 14002 } 14003 final long origId = Binder.clearCallingIdentity(); 14004 finishInstrumentationLocked(app, resultCode, results); 14005 Binder.restoreCallingIdentity(origId); 14006 } 14007 } 14008 14009 @Override getFocusedRootTaskInfo()14010 public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException { 14011 return mActivityTaskManager.getFocusedRootTaskInfo(); 14012 } 14013 14014 @Override getConfiguration()14015 public Configuration getConfiguration() { 14016 return mActivityTaskManager.getConfiguration(); 14017 } 14018 14019 @Override suppressResizeConfigChanges(boolean suppress)14020 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException { 14021 mActivityTaskManager.suppressResizeConfigChanges(suppress); 14022 } 14023 14024 @Override updatePersistentConfiguration(Configuration values)14025 public void updatePersistentConfiguration(Configuration values) { 14026 updatePersistentConfigurationWithAttribution(values, 14027 Settings.getPackageNameForUid(mContext, Binder.getCallingUid()), null); 14028 } 14029 14030 @Override updatePersistentConfigurationWithAttribution(Configuration values, String callingPackage, String callingAttributionTag)14031 public void updatePersistentConfigurationWithAttribution(Configuration values, 14032 String callingPackage, String callingAttributionTag) { 14033 enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()"); 14034 enforceWriteSettingsPermission("updatePersistentConfiguration()", callingPackage, 14035 callingAttributionTag); 14036 if (values == null) { 14037 throw new NullPointerException("Configuration must not be null"); 14038 } 14039 14040 int userId = UserHandle.getCallingUserId(); 14041 14042 mActivityTaskManager.updatePersistentConfiguration(values, userId); 14043 } 14044 enforceWriteSettingsPermission(String func, String callingPackage, String callingAttributionTag)14045 private void enforceWriteSettingsPermission(String func, String callingPackage, 14046 String callingAttributionTag) { 14047 int uid = Binder.getCallingUid(); 14048 if (uid == ROOT_UID) { 14049 return; 14050 } 14051 14052 if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid, 14053 callingPackage, callingAttributionTag, false)) { 14054 return; 14055 } 14056 14057 String msg = "Permission Denial: " + func + " from pid=" 14058 + Binder.getCallingPid() 14059 + ", uid=" + uid 14060 + " requires " + android.Manifest.permission.WRITE_SETTINGS; 14061 Slog.w(TAG, msg); 14062 throw new SecurityException(msg); 14063 } 14064 14065 @Override updateConfiguration(Configuration values)14066 public boolean updateConfiguration(Configuration values) { 14067 return mActivityTaskManager.updateConfiguration(values); 14068 } 14069 14070 @Override updateMccMncConfiguration(String mcc, String mnc)14071 public boolean updateMccMncConfiguration(String mcc, String mnc) { 14072 int mccInt, mncInt; 14073 try { 14074 mccInt = Integer.parseInt(mcc); 14075 mncInt = Integer.parseInt(mnc); 14076 } catch (NumberFormatException | StringIndexOutOfBoundsException ex) { 14077 Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex); 14078 return false; 14079 } 14080 Configuration config = new Configuration(); 14081 config.mcc = mccInt; 14082 config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt; 14083 return mActivityTaskManager.updateConfiguration(config); 14084 } 14085 14086 @Override getLaunchedFromUid(IBinder activityToken)14087 public int getLaunchedFromUid(IBinder activityToken) { 14088 return ActivityClient.getInstance().getLaunchedFromUid(activityToken); 14089 } 14090 getLaunchedFromPackage(IBinder activityToken)14091 public String getLaunchedFromPackage(IBinder activityToken) { 14092 return ActivityClient.getInstance().getLaunchedFromPackage(activityToken); 14093 } 14094 14095 // ========================================================= 14096 // LIFETIME MANAGEMENT 14097 // ========================================================= 14098 14099 // Returns whether the app is receiving broadcast. 14100 // If receiving, fetch all broadcast queues which the app is 14101 // the current [or imminent] receiver on. isReceivingBroadcastLocked(ProcessRecord app, ArraySet<BroadcastQueue> receivingQueues)14102 boolean isReceivingBroadcastLocked(ProcessRecord app, 14103 ArraySet<BroadcastQueue> receivingQueues) { 14104 final ProcessReceiverRecord prr = app.mReceivers; 14105 final int numOfReceivers = prr.numberOfCurReceivers(); 14106 if (numOfReceivers > 0) { 14107 for (int i = 0; i < numOfReceivers; i++) { 14108 receivingQueues.add(prr.getCurReceiverAt(i).queue); 14109 } 14110 return true; 14111 } 14112 14113 // It's not the current receiver, but it might be starting up to become one 14114 for (BroadcastQueue queue : mBroadcastQueues) { 14115 final BroadcastRecord r = queue.mPendingBroadcast; 14116 if (r != null && r.curApp == app) { 14117 // found it; report which queue it's in 14118 receivingQueues.add(queue); 14119 } 14120 } 14121 14122 return !receivingQueues.isEmpty(); 14123 } 14124 startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)14125 Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, 14126 int targetUid, long targetVersionCode, ComponentName targetComponent, 14127 String targetProcess) { 14128 if (!mTrackingAssociations) { 14129 return null; 14130 } 14131 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 14132 = mAssociations.get(targetUid); 14133 if (components == null) { 14134 components = new ArrayMap<>(); 14135 mAssociations.put(targetUid, components); 14136 } 14137 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 14138 if (sourceUids == null) { 14139 sourceUids = new SparseArray<>(); 14140 components.put(targetComponent, sourceUids); 14141 } 14142 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 14143 if (sourceProcesses == null) { 14144 sourceProcesses = new ArrayMap<>(); 14145 sourceUids.put(sourceUid, sourceProcesses); 14146 } 14147 Association ass = sourceProcesses.get(sourceProcess); 14148 if (ass == null) { 14149 ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent, 14150 targetProcess); 14151 sourceProcesses.put(sourceProcess, ass); 14152 } 14153 ass.mCount++; 14154 ass.mNesting++; 14155 if (ass.mNesting == 1) { 14156 ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis(); 14157 ass.mLastState = sourceState; 14158 } 14159 return ass; 14160 } 14161 stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)14162 void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, 14163 long targetVersionCode, ComponentName targetComponent, String targetProcess) { 14164 if (!mTrackingAssociations) { 14165 return; 14166 } 14167 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 14168 = mAssociations.get(targetUid); 14169 if (components == null) { 14170 return; 14171 } 14172 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 14173 if (sourceUids == null) { 14174 return; 14175 } 14176 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 14177 if (sourceProcesses == null) { 14178 return; 14179 } 14180 Association ass = sourceProcesses.get(sourceProcess); 14181 if (ass == null || ass.mNesting <= 0) { 14182 return; 14183 } 14184 ass.mNesting--; 14185 if (ass.mNesting == 0) { 14186 long uptime = SystemClock.uptimeMillis(); 14187 ass.mTime += uptime - ass.mStartTime; 14188 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 14189 += uptime - ass.mLastStateUptime; 14190 ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2; 14191 } 14192 } 14193 noteUidProcessState(final int uid, final int state, final @ProcessCapability int capability)14194 void noteUidProcessState(final int uid, final int state, 14195 final @ProcessCapability int capability) { 14196 mBatteryStatsService.noteUidProcessState(uid, state); 14197 mAppOpsService.updateUidProcState(uid, state, capability); 14198 if (mTrackingAssociations) { 14199 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 14200 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 14201 = mAssociations.valueAt(i1); 14202 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 14203 SparseArray<ArrayMap<String, Association>> sourceUids 14204 = targetComponents.valueAt(i2); 14205 ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid); 14206 if (sourceProcesses != null) { 14207 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 14208 Association ass = sourceProcesses.valueAt(i4); 14209 if (ass.mNesting >= 1) { 14210 // currently associated 14211 long uptime = SystemClock.uptimeMillis(); 14212 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE] 14213 += uptime - ass.mLastStateUptime; 14214 ass.mLastState = state; 14215 ass.mLastStateUptime = uptime; 14216 } 14217 } 14218 } 14219 } 14220 } 14221 } 14222 } 14223 14224 /** 14225 * Returns true if things are idle enough to perform GCs. 14226 */ 14227 @GuardedBy("this") canGcNowLocked()14228 final boolean canGcNowLocked() { 14229 for (BroadcastQueue q : mBroadcastQueues) { 14230 if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isEmpty()) { 14231 return false; 14232 } 14233 } 14234 return mAtmInternal.canGcNow(); 14235 } 14236 checkExcessivePowerUsage()14237 private void checkExcessivePowerUsage() { 14238 updateCpuStatsNow(); 14239 14240 synchronized (mProcLock) { 14241 final boolean doCpuKills = mLastPowerCheckUptime != 0; 14242 final long curUptime = SystemClock.uptimeMillis(); 14243 final long uptimeSince = curUptime - mLastPowerCheckUptime; 14244 mLastPowerCheckUptime = curUptime; 14245 mProcessList.forEachLruProcessesLOSP(false, app -> { 14246 if (app.getThread() == null) { 14247 return; 14248 } 14249 if (app.mState.getSetProcState() >= ActivityManager.PROCESS_STATE_HOME) { 14250 int cpuLimit; 14251 long checkDur = curUptime - app.mState.getWhenUnimportant(); 14252 if (checkDur <= mConstants.POWER_CHECK_INTERVAL) { 14253 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1; 14254 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 2) 14255 || app.mState.getSetProcState() <= ActivityManager.PROCESS_STATE_HOME) { 14256 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2; 14257 } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 3)) { 14258 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3; 14259 } else { 14260 cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4; 14261 } 14262 14263 updateAppProcessCpuTimeLPr(uptimeSince, doCpuKills, checkDur, cpuLimit, app); 14264 14265 // Also check the phantom processes if there is any 14266 updatePhantomProcessCpuTimeLPr( 14267 uptimeSince, doCpuKills, checkDur, cpuLimit, app); 14268 } 14269 }); 14270 } 14271 } 14272 14273 @GuardedBy("mProcLock") updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)14274 private void updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, 14275 final long checkDur, final int cpuLimit, final ProcessRecord app) { 14276 synchronized (mAppProfiler.mProfilerLock) { 14277 final ProcessProfileRecord profile = app.mProfile; 14278 final long curCpuTime = profile.mCurCpuTime.get(); 14279 final long lastCpuTime = profile.mLastCpuTime.get(); 14280 if (lastCpuTime > 0) { 14281 final long cpuTimeUsed = curCpuTime - lastCpuTime; 14282 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed, 14283 app.processName, app.toShortString(), cpuLimit, app)) { 14284 mHandler.post(() -> { 14285 synchronized (ActivityManagerService.this) { 14286 app.killLocked("excessive cpu " + cpuTimeUsed + " during " 14287 + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit, 14288 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 14289 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU, 14290 true); 14291 } 14292 }); 14293 profile.reportExcessiveCpu(); 14294 } 14295 } 14296 14297 profile.mLastCpuTime.set(curCpuTime); 14298 } 14299 } 14300 14301 @GuardedBy("mProcLock") updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)14302 private void updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, 14303 final long checkDur, final int cpuLimit, final ProcessRecord app) { 14304 mPhantomProcessList.forEachPhantomProcessOfApp(app, r -> { 14305 if (r.mLastCputime > 0) { 14306 final long cpuTimeUsed = r.mCurrentCputime - r.mLastCputime; 14307 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed, 14308 app.processName, r.toString(), cpuLimit, app)) { 14309 mHandler.post(() -> { 14310 synchronized (ActivityManagerService.this) { 14311 mPhantomProcessList.killPhantomProcessGroupLocked(app, r, 14312 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE, 14313 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU, 14314 "excessive cpu " + cpuTimeUsed + " during " 14315 + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit); 14316 } 14317 }); 14318 return false; 14319 } 14320 } 14321 r.mLastCputime = r.mCurrentCputime; 14322 return true; 14323 }); 14324 } 14325 14326 @GuardedBy("mProcLock") checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, final long cputimeUsed, final String processName, final String description, final int cpuLimit, final ProcessRecord app)14327 private boolean checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, 14328 final long cputimeUsed, final String processName, final String description, 14329 final int cpuLimit, final ProcessRecord app) { 14330 if (DEBUG_POWER && (uptimeSince > 0)) { 14331 StringBuilder sb = new StringBuilder(128); 14332 sb.append("CPU for "); 14333 sb.append(description); 14334 sb.append(": over "); 14335 TimeUtils.formatDuration(uptimeSince, sb); 14336 sb.append(" used "); 14337 TimeUtils.formatDuration(cputimeUsed, sb); 14338 sb.append(" ("); 14339 sb.append((cputimeUsed * 100.0) / uptimeSince); 14340 sb.append("%)"); 14341 Slog.i(TAG_POWER, sb.toString()); 14342 } 14343 // If the process has used too much CPU over the last duration, the 14344 // user probably doesn't want this, so kill! 14345 if (doCpuKills && uptimeSince > 0) { 14346 if (((cputimeUsed * 100) / uptimeSince) >= cpuLimit) { 14347 mBatteryStatsService.reportExcessiveCpu(app.info.uid, app.processName, 14348 uptimeSince, cputimeUsed); 14349 app.getPkgList().forEachPackageProcessStats(holder -> { 14350 final ProcessState state = holder.state; 14351 FrameworkStatsLog.write( 14352 FrameworkStatsLog.EXCESSIVE_CPU_USAGE_REPORTED, 14353 app.info.uid, 14354 processName, 14355 state != null ? state.getPackage() : app.info.packageName, 14356 holder.appVersion); 14357 }); 14358 return true; 14359 } 14360 } 14361 return false; 14362 } 14363 isEphemeralLocked(int uid)14364 private boolean isEphemeralLocked(int uid) { 14365 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid); 14366 if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid 14367 return false; 14368 } 14369 return getPackageManagerInternal().isPackageEphemeral( 14370 UserHandle.getUserId(uid), packages[0]); 14371 } 14372 14373 @GuardedBy("this") enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)14374 void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) { 14375 uid = uidRec != null ? uidRec.getUid() : uid; 14376 if (uid < 0) { 14377 throw new IllegalArgumentException("No UidRecord or uid"); 14378 } 14379 14380 final int procState = uidRec != null 14381 ? uidRec.getSetProcState() : PROCESS_STATE_NONEXISTENT; 14382 final long procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0; 14383 final int capability = uidRec != null ? uidRec.getSetCapability() : 0; 14384 final boolean ephemeral = uidRec != null ? uidRec.isEphemeral() : isEphemeralLocked(uid); 14385 14386 if (uidRec != null && !uidRec.isIdle() && (change & UidRecord.CHANGE_GONE) != 0) { 14387 // If this uid is going away, and we haven't yet reported it is gone, 14388 // then do so now. 14389 change |= UidRecord.CHANGE_IDLE; 14390 } 14391 final int enqueuedChange = mUidObserverController.enqueueUidChange( 14392 uidRec == null ? null : uidRec.pendingChange, 14393 uid, change, procState, procStateSeq, capability, ephemeral); 14394 if (uidRec != null) { 14395 uidRec.setLastReportedChange(enqueuedChange); 14396 uidRec.updateLastDispatchedProcStateSeq(enqueuedChange); 14397 } 14398 14399 // Directly update the power manager, since we sit on top of it and it is critical 14400 // it be kept in sync (so wake locks will be held as soon as appropriate). 14401 if (mLocalPowerManager != null) { 14402 // TODO: dispatch cached/uncached changes here, so we don't need to report 14403 // all proc state changes. 14404 if ((enqueuedChange & UidRecord.CHANGE_ACTIVE) != 0) { 14405 mLocalPowerManager.uidActive(uid); 14406 } 14407 if ((enqueuedChange & UidRecord.CHANGE_IDLE) != 0) { 14408 mLocalPowerManager.uidIdle(uid); 14409 } 14410 if ((enqueuedChange & UidRecord.CHANGE_GONE) != 0) { 14411 mLocalPowerManager.uidGone(uid); 14412 } else { 14413 mLocalPowerManager.updateUidProcState(uid, procState); 14414 } 14415 } 14416 } 14417 14418 @GuardedBy(anyOf = {"this", "mProcLock"}) setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor, long now)14419 final void setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor, long now) { 14420 if (proc.getThread() != null) { 14421 proc.mProfile.setProcessTrackerState( 14422 proc.mState.getReportedProcState(), memFactor, now); 14423 } 14424 } 14425 14426 @GuardedBy("this") updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean oomAdj)14427 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 14428 int fgServiceTypes, boolean oomAdj) { 14429 final ProcessServiceRecord psr = proc.mServices; 14430 if (isForeground != psr.hasForegroundServices() 14431 || psr.getForegroundServiceTypes() != fgServiceTypes) { 14432 psr.setHasForegroundServices(isForeground, fgServiceTypes); 14433 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 14434 proc.info.uid); 14435 if (isForeground) { 14436 if (curProcs == null) { 14437 curProcs = new ArrayList<ProcessRecord>(); 14438 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 14439 } 14440 if (!curProcs.contains(proc)) { 14441 curProcs.add(proc); 14442 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 14443 proc.info.packageName, proc.info.uid); 14444 } 14445 } else { 14446 if (curProcs != null) { 14447 if (curProcs.remove(proc)) { 14448 mBatteryStatsService.noteEvent( 14449 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 14450 proc.info.packageName, proc.info.uid); 14451 if (curProcs.size() <= 0) { 14452 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 14453 } 14454 } 14455 } 14456 } 14457 14458 psr.setReportedForegroundServiceTypes(fgServiceTypes); 14459 ProcessChangeItem item = mProcessList.enqueueProcessChangeItemLocked( 14460 proc.getPid(), proc.info.uid); 14461 item.changes |= ProcessChangeItem.CHANGE_FOREGROUND_SERVICES; 14462 item.foregroundServiceTypes = fgServiceTypes; 14463 } 14464 if (oomAdj) { 14465 updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 14466 } 14467 } 14468 14469 // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update 14470 // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities getTopApp()14471 ProcessRecord getTopApp() { 14472 final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null; 14473 final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null; 14474 String pkg; 14475 int uid; 14476 if (r != null) { 14477 pkg = r.processName; 14478 uid = r.info.uid; 14479 } else { 14480 pkg = null; 14481 uid = -1; 14482 } 14483 // Has the UID or resumed package name changed? 14484 synchronized (mCurResumedAppLock) { 14485 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 14486 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 14487 14488 final long identity = Binder.clearCallingIdentity(); 14489 try { 14490 if (mCurResumedPackage != null) { 14491 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 14492 mCurResumedPackage, mCurResumedUid); 14493 } 14494 mCurResumedPackage = pkg; 14495 mCurResumedUid = uid; 14496 if (mCurResumedPackage != null) { 14497 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 14498 mCurResumedPackage, mCurResumedUid); 14499 } 14500 } finally { 14501 Binder.restoreCallingIdentity(identity); 14502 } 14503 } 14504 } 14505 return r; 14506 } 14507 14508 /** 14509 * Enqueue the given process into a todo list, and the caller should 14510 * call {@link #updateOomAdjPendingTargetsLocked} to kick off a pass of the oom adj update. 14511 */ 14512 @GuardedBy("this") enqueueOomAdjTargetLocked(ProcessRecord app)14513 void enqueueOomAdjTargetLocked(ProcessRecord app) { 14514 mOomAdjuster.enqueueOomAdjTargetLocked(app); 14515 } 14516 14517 /** 14518 * Remove the given process into a todo list. 14519 */ 14520 @GuardedBy("this") removeOomAdjTargetLocked(ProcessRecord app, boolean procDied)14521 void removeOomAdjTargetLocked(ProcessRecord app, boolean procDied) { 14522 mOomAdjuster.removeOomAdjTargetLocked(app, procDied); 14523 } 14524 14525 /** 14526 * Kick off an oom adj update pass for the pending targets which are enqueued via 14527 * {@link #enqueueOomAdjTargetLocked}. 14528 */ 14529 @GuardedBy("this") updateOomAdjPendingTargetsLocked(String oomAdjReason)14530 void updateOomAdjPendingTargetsLocked(String oomAdjReason) { 14531 mOomAdjuster.updateOomAdjPendingTargetsLocked(oomAdjReason); 14532 } 14533 14534 static final class ProcStatsRunnable implements Runnable { 14535 private final ActivityManagerService mService; 14536 private final ProcessStatsService mProcessStats; 14537 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)14538 ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) { 14539 this.mService = service; 14540 this.mProcessStats = mProcessStats; 14541 } 14542 run()14543 @Override public void run() { 14544 mProcessStats.writeStateAsync(); 14545 } 14546 } 14547 14548 @GuardedBy("this") updateOomAdjLocked(String oomAdjReason)14549 final void updateOomAdjLocked(String oomAdjReason) { 14550 mOomAdjuster.updateOomAdjLocked(oomAdjReason); 14551 } 14552 14553 /** 14554 * Update OomAdj for a specific process and its reachable processes. 14555 * 14556 * @param app The process to update 14557 * @param oomAdjReason 14558 * @return whether updateOomAdjLocked(app) was successful. 14559 */ 14560 @GuardedBy("this") updateOomAdjLocked(ProcessRecord app, String oomAdjReason)14561 final boolean updateOomAdjLocked(ProcessRecord app, String oomAdjReason) { 14562 return mOomAdjuster.updateOomAdjLocked(app, oomAdjReason); 14563 } 14564 14565 @Override makePackageIdle(String packageName, int userId)14566 public void makePackageIdle(String packageName, int userId) { 14567 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 14568 != PackageManager.PERMISSION_GRANTED) { 14569 String msg = "Permission Denial: makePackageIdle() from pid=" 14570 + Binder.getCallingPid() 14571 + ", uid=" + Binder.getCallingUid() 14572 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 14573 Slog.w(TAG, msg); 14574 throw new SecurityException(msg); 14575 } 14576 final int callingPid = Binder.getCallingPid(); 14577 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 14578 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null); 14579 final long callingId = Binder.clearCallingIdentity(); 14580 try { 14581 IPackageManager pm = AppGlobals.getPackageManager(); 14582 int pkgUid = -1; 14583 try { 14584 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES 14585 | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM); 14586 } catch (RemoteException e) { 14587 } 14588 if (pkgUid == -1) { 14589 throw new IllegalArgumentException("Unknown package name " + packageName); 14590 } 14591 14592 synchronized (this) { 14593 try { 14594 if (mLocalPowerManager != null) { 14595 mLocalPowerManager.startUidChanges(); 14596 } 14597 final int appId = UserHandle.getAppId(pkgUid); 14598 for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; i--) { 14599 final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i); 14600 final long bgTime = uidRec.getLastBackgroundTime(); 14601 if (bgTime > 0 && !uidRec.isIdle()) { 14602 final int uid = uidRec.getUid(); 14603 if (UserHandle.getAppId(uid) == appId) { 14604 if (userId == UserHandle.USER_ALL 14605 || userId == UserHandle.getUserId(uid)) { 14606 EventLogTags.writeAmUidIdle(uid); 14607 synchronized (mProcLock) { 14608 uidRec.setIdle(true); 14609 uidRec.setSetIdle(true); 14610 } 14611 Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uid) 14612 + " from package " + packageName + " user " + userId); 14613 doStopUidLocked(uid, uidRec); 14614 } 14615 } 14616 } 14617 } 14618 } finally { 14619 if (mLocalPowerManager != null) { 14620 mLocalPowerManager.finishUidChanges(); 14621 } 14622 } 14623 } 14624 } finally { 14625 Binder.restoreCallingIdentity(callingId); 14626 } 14627 } 14628 14629 /** Make the currently active UIDs idle after a certain grace period. */ idleUids()14630 final void idleUids() { 14631 synchronized (this) { 14632 mOomAdjuster.idleUidsLocked(); 14633 } 14634 } 14635 runInBackgroundDisabled(int uid)14636 final void runInBackgroundDisabled(int uid) { 14637 synchronized (this) { 14638 UidRecord uidRec = mProcessList.getUidRecordLOSP(uid); 14639 if (uidRec != null) { 14640 // This uid is actually running... should it be considered background now? 14641 if (uidRec.isIdle()) { 14642 doStopUidLocked(uidRec.getUid(), uidRec); 14643 } 14644 } else { 14645 // This uid isn't actually running... still send a report about it being "stopped". 14646 doStopUidLocked(uid, null); 14647 } 14648 } 14649 } 14650 cameraActiveChanged(@serIdInt int uid, boolean active)14651 final void cameraActiveChanged(@UserIdInt int uid, boolean active) { 14652 synchronized (mActiveCameraUids) { 14653 final int curIndex = mActiveCameraUids.indexOf(uid); 14654 if (active) { 14655 if (curIndex < 0) { 14656 mActiveCameraUids.add(uid); 14657 } 14658 } else { 14659 if (curIndex >= 0) { 14660 mActiveCameraUids.remove(curIndex); 14661 } 14662 } 14663 } 14664 } 14665 isCameraActiveForUid(@serIdInt int uid)14666 final boolean isCameraActiveForUid(@UserIdInt int uid) { 14667 synchronized (mActiveCameraUids) { 14668 return mActiveCameraUids.indexOf(uid) >= 0; 14669 } 14670 } 14671 14672 @GuardedBy("this") doStopUidLocked(int uid, final UidRecord uidRec)14673 final void doStopUidLocked(int uid, final UidRecord uidRec) { 14674 mServices.stopInBackgroundLocked(uid); 14675 enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE); 14676 } 14677 14678 /** 14679 * Allowlists {@code targetUid} to temporarily bypass Power Save mode. 14680 */ 14681 @GuardedBy("this") tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)14682 void tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, 14683 long duration, int type, @ReasonCode int reasonCode, String reason) { 14684 if (DEBUG_ALLOWLISTS) { 14685 Slog.d(TAG, "tempAllowlistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", " 14686 + targetUid + ", " + duration + ", " + type + ")"); 14687 } 14688 14689 synchronized (mPidsSelfLocked) { 14690 final ProcessRecord pr = mPidsSelfLocked.get(callerPid); 14691 if (pr == null) { 14692 Slog.w(TAG, "tempAllowlistForPendingIntentLocked() no ProcessRecord for pid " 14693 + callerPid); 14694 return; 14695 } 14696 if (!pr.mServices.mAllowlistManager) { 14697 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid) 14698 != PackageManager.PERMISSION_GRANTED 14699 && checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callerPid, callerUid) 14700 != PackageManager.PERMISSION_GRANTED 14701 && checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callerPid, 14702 callerUid) != PackageManager.PERMISSION_GRANTED) { 14703 if (DEBUG_ALLOWLISTS) { 14704 Slog.d(TAG, "tempAllowlistForPendingIntentLocked() for target " + targetUid 14705 + ": pid " + callerPid + " is not allowed"); 14706 } 14707 return; 14708 } 14709 } 14710 } 14711 14712 tempAllowlistUidLocked(targetUid, duration, reasonCode, reason, type, callerUid); 14713 } 14714 14715 /** 14716 * Allowlists {@code targetUid} to temporarily bypass Power Save mode. 14717 */ 14718 @GuardedBy("this") tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, String reason, @TempAllowListType int type, int callingUid)14719 void tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, 14720 String reason, @TempAllowListType int type, int callingUid) { 14721 synchronized (mProcLock) { 14722 // The temp allowlist type could change according to the reasonCode. 14723 if (mLocalDeviceIdleController != null) { 14724 type = mLocalDeviceIdleController.getTempAllowListType(reasonCode, type); 14725 } 14726 if (type == TEMPORARY_ALLOW_LIST_TYPE_NONE) { 14727 return; 14728 } 14729 mPendingTempAllowlist.put(targetUid, 14730 new PendingTempAllowlist(targetUid, duration, reasonCode, reason, type, 14731 callingUid)); 14732 setUidTempAllowlistStateLSP(targetUid, true); 14733 mUiHandler.obtainMessage(PUSH_TEMP_ALLOWLIST_UI_MSG).sendToTarget(); 14734 14735 if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) { 14736 mFgsStartTempAllowList.add(targetUid, duration, 14737 new FgsTempAllowListItem(duration, reasonCode, reason, callingUid)); 14738 } 14739 } 14740 } 14741 pushTempAllowlist()14742 void pushTempAllowlist() { 14743 final int N; 14744 final PendingTempAllowlist[] list; 14745 14746 // First copy out the pending changes... we need to leave them in the map for now, 14747 // in case someone needs to check what is coming up while we don't have the lock held. 14748 synchronized (mProcLock) { 14749 N = mPendingTempAllowlist.size(); 14750 list = new PendingTempAllowlist[N]; 14751 for (int i = 0; i < N; i++) { 14752 list[i] = mPendingTempAllowlist.valueAt(i); 14753 } 14754 } 14755 14756 // Now safely dispatch changes to device idle controller. Skip this if we're early 14757 // in boot and the controller hasn't yet been brought online: we do not apply 14758 // device idle policy anyway at this phase. 14759 if (mLocalDeviceIdleController != null) { 14760 for (int i = 0; i < N; i++) { 14761 PendingTempAllowlist ptw = list[i]; 14762 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid, 14763 ptw.duration, ptw.type, true, ptw.reasonCode, ptw.tag, 14764 ptw.callingUid); 14765 } 14766 } 14767 14768 // And now we can safely remove them from the map. 14769 synchronized (this) { 14770 synchronized (mProcLock) { 14771 for (int i = 0; i < N; i++) { 14772 PendingTempAllowlist ptw = list[i]; 14773 int index = mPendingTempAllowlist.indexOfKey(ptw.targetUid); 14774 if (index >= 0 && mPendingTempAllowlist.valueAt(index) == ptw) { 14775 mPendingTempAllowlist.removeAt(index); 14776 } 14777 } 14778 } 14779 } 14780 } 14781 14782 @GuardedBy({"this", "mProcLock"}) setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist)14783 final void setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist) { 14784 mOomAdjuster.setAppIdTempAllowlistStateLSP(uid, onAllowlist); 14785 } 14786 14787 @GuardedBy({"this", "mProcLock"}) setUidTempAllowlistStateLSP(int uid, boolean onAllowlist)14788 final void setUidTempAllowlistStateLSP(int uid, boolean onAllowlist) { 14789 mOomAdjuster.setUidTempAllowlistStateLSP(uid, onAllowlist); 14790 } 14791 trimApplications(boolean forceFullOomAdj, String oomAdjReason)14792 private void trimApplications(boolean forceFullOomAdj, String oomAdjReason) { 14793 synchronized (this) { 14794 trimApplicationsLocked(forceFullOomAdj, oomAdjReason); 14795 } 14796 } 14797 14798 @GuardedBy("this") trimApplicationsLocked(boolean forceFullOomAdj, String oomAdjReason)14799 private void trimApplicationsLocked(boolean forceFullOomAdj, String oomAdjReason) { 14800 // First remove any unused application processes whose package 14801 // has been removed. 14802 boolean didSomething = false; 14803 for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) { 14804 final ProcessRecord app = mProcessList.mRemovedProcesses.get(i); 14805 if (!app.hasActivitiesOrRecentTasks() 14806 && app.mReceivers.numberOfCurReceivers() == 0 14807 && app.mServices.numberOfRunningServices() == 0) { 14808 final IApplicationThread thread = app.getThread(); 14809 Slog.i(TAG, "Exiting empty application process " 14810 + app.toShortString() + " (" 14811 + (thread != null ? thread.asBinder() : null) 14812 + ")\n"); 14813 final int pid = app.getPid(); 14814 if (pid > 0 && pid != MY_PID) { 14815 app.killLocked("empty", 14816 ApplicationExitInfo.REASON_OTHER, 14817 ApplicationExitInfo.SUBREASON_TRIM_EMPTY, 14818 false); 14819 } else if (thread != null) { 14820 try { 14821 thread.scheduleExit(); 14822 } catch (Exception e) { 14823 // Ignore exceptions. 14824 } 14825 } 14826 didSomething = true; 14827 cleanUpApplicationRecordLocked(app, pid, false, true, -1, false /*replacingPid*/, 14828 false /* fromBinderDied */); 14829 mProcessList.mRemovedProcesses.remove(i); 14830 14831 if (app.isPersistent()) { 14832 addAppLocked(app.info, null, false, null /* ABI override */, 14833 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH); 14834 } 14835 } 14836 } 14837 14838 // Now update the oom adj for all processes. Don't skip this, since other callers 14839 // might be depending on it. 14840 if (didSomething || forceFullOomAdj) { 14841 updateOomAdjLocked(oomAdjReason); 14842 } else { 14843 // Process any pending oomAdj targets, it'll be a no-op if nothing is pending. 14844 updateOomAdjPendingTargetsLocked(oomAdjReason); 14845 } 14846 } 14847 14848 /** This method sends the specified signal to each of the persistent apps */ signalPersistentProcesses(final int sig)14849 public void signalPersistentProcesses(final int sig) throws RemoteException { 14850 if (sig != SIGNAL_USR1) { 14851 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 14852 } 14853 14854 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 14855 != PackageManager.PERMISSION_GRANTED) { 14856 throw new SecurityException("Requires permission " 14857 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 14858 } 14859 14860 synchronized (mProcLock) { 14861 mProcessList.forEachLruProcessesLOSP(false, app -> { 14862 if (app.getThread() != null && app.isPersistent()) { 14863 sendSignal(app.getPid(), sig); 14864 } 14865 }); 14866 } 14867 } 14868 profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)14869 public boolean profileControl(String process, int userId, boolean start, 14870 ProfilerInfo profilerInfo, int profileType) throws RemoteException { 14871 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 14872 // its own permission. 14873 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 14874 != PackageManager.PERMISSION_GRANTED) { 14875 throw new SecurityException("Requires permission " 14876 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 14877 } 14878 14879 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) { 14880 throw new IllegalArgumentException("null profile info or fd"); 14881 } 14882 14883 ProcessRecord proc = null; 14884 synchronized (mProcLock) { 14885 if (process != null) { 14886 proc = findProcessLOSP(process, userId, "profileControl"); 14887 } 14888 14889 if (start && (proc == null || proc.getThread() == null)) { 14890 throw new IllegalArgumentException("Unknown process: " + process); 14891 } 14892 } 14893 14894 synchronized (mAppProfiler.mProfilerLock) { 14895 return mAppProfiler.profileControlLPf(proc, start, profilerInfo, profileType); 14896 } 14897 } 14898 14899 @GuardedBy(anyOf = {"this", "mProcLock"}) findProcessLOSP(String process, int userId, String callName)14900 private ProcessRecord findProcessLOSP(String process, int userId, String callName) { 14901 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 14902 userId, true, ALLOW_FULL_ONLY, callName, null); 14903 ProcessRecord proc = null; 14904 try { 14905 int pid = Integer.parseInt(process); 14906 synchronized (mPidsSelfLocked) { 14907 proc = mPidsSelfLocked.get(pid); 14908 } 14909 } catch (NumberFormatException e) { 14910 } 14911 14912 if (proc == null) { 14913 ArrayMap<String, SparseArray<ProcessRecord>> all = 14914 mProcessList.getProcessNamesLOSP().getMap(); 14915 SparseArray<ProcessRecord> procs = all.get(process); 14916 if (procs != null && procs.size() > 0) { 14917 proc = procs.valueAt(0); 14918 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 14919 for (int i=1; i<procs.size(); i++) { 14920 ProcessRecord thisProc = procs.valueAt(i); 14921 if (thisProc.userId == userId) { 14922 proc = thisProc; 14923 break; 14924 } 14925 } 14926 } 14927 } 14928 } 14929 14930 return proc; 14931 } 14932 14933 @Override dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)14934 public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, 14935 boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) { 14936 try { 14937 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 14938 // its own permission (same as profileControl). 14939 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 14940 != PackageManager.PERMISSION_GRANTED) { 14941 throw new SecurityException("Requires permission " 14942 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 14943 } 14944 14945 if (fd == null) { 14946 throw new IllegalArgumentException("null fd"); 14947 } 14948 14949 synchronized (this) { 14950 ProcessRecord proc = findProcessLOSP(process, userId, "dumpHeap"); 14951 IApplicationThread thread; 14952 if (proc == null || (thread = proc.getThread()) == null) { 14953 throw new IllegalArgumentException("Unknown process: " + process); 14954 } 14955 14956 boolean isDebuggable = Build.IS_DEBUGGABLE; 14957 if (!isDebuggable) { 14958 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 14959 throw new SecurityException("Process not debuggable: " + proc); 14960 } 14961 } 14962 14963 mOomAdjuster.mCachedAppOptimizer.enableFreezer(false); 14964 14965 final RemoteCallback intermediateCallback = new RemoteCallback( 14966 new RemoteCallback.OnResultListener() { 14967 @Override 14968 public void onResult(Bundle result) { 14969 finishCallback.sendResult(result); 14970 mOomAdjuster.mCachedAppOptimizer.enableFreezer(true); 14971 } 14972 }, null); 14973 14974 thread.dumpHeap(managed, mallocInfo, runGc, path, fd, intermediateCallback); 14975 fd = null; 14976 return true; 14977 } 14978 } catch (RemoteException e) { 14979 throw new IllegalStateException("Process disappeared"); 14980 } finally { 14981 if (fd != null) { 14982 try { 14983 fd.close(); 14984 } catch (IOException e) { 14985 } 14986 } 14987 } 14988 } 14989 14990 @Override setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)14991 public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, 14992 String reportPackage) { 14993 if (processName != null) { 14994 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 14995 "setDumpHeapDebugLimit()"); 14996 } else { 14997 synchronized (mPidsSelfLocked) { 14998 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid()); 14999 if (proc == null) { 15000 throw new SecurityException("No process found for calling pid " 15001 + Binder.getCallingPid()); 15002 } 15003 if (!Build.IS_DEBUGGABLE 15004 && (proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 15005 throw new SecurityException("Not running a debuggable build"); 15006 } 15007 processName = proc.processName; 15008 uid = proc.uid; 15009 if (reportPackage != null && !proc.getPkgList().containsKey(reportPackage)) { 15010 throw new SecurityException("Package " + reportPackage + " is not running in " 15011 + proc); 15012 } 15013 } 15014 } 15015 mAppProfiler.setDumpHeapDebugLimit(processName, uid, maxMemSize, reportPackage); 15016 } 15017 15018 @Override dumpHeapFinished(String path)15019 public void dumpHeapFinished(String path) { 15020 mAppProfiler.dumpHeapFinished(path, Binder.getCallingPid()); 15021 } 15022 15023 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ monitor()15024 public void monitor() { 15025 synchronized (this) { } 15026 } 15027 onCoreSettingsChange(Bundle settings)15028 void onCoreSettingsChange(Bundle settings) { 15029 synchronized (mProcLock) { 15030 mProcessList.updateCoreSettingsLOSP(settings); 15031 } 15032 } 15033 15034 // Multi-user methods 15035 15036 /** 15037 * Start user, if its not already running, but don't bring it to foreground. 15038 */ 15039 @Override startUserInBackground(final int userId)15040 public boolean startUserInBackground(final int userId) { 15041 return startUserInBackgroundWithListener(userId, null); 15042 } 15043 15044 @Override startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)15045 public boolean startUserInBackgroundWithListener(final int userId, 15046 @Nullable IProgressListener unlockListener) { 15047 return mUserController.startUser(userId, /* foreground */ false, unlockListener); 15048 } 15049 15050 @Override startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)15051 public boolean startUserInForegroundWithListener(final int userId, 15052 @Nullable IProgressListener unlockListener) { 15053 // Permission check done inside UserController. 15054 return mUserController.startUser(userId, /* foreground */ true, unlockListener); 15055 } 15056 15057 @Override unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener)15058 public boolean unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener) { 15059 return mUserController.unlockUser(userId, token, secret, listener); 15060 } 15061 15062 @Override switchUser(final int targetUserId)15063 public boolean switchUser(final int targetUserId) { 15064 return mUserController.switchUser(targetUserId); 15065 } 15066 15067 @Override stopUser(final int userId, boolean force, final IStopUserCallback callback)15068 public int stopUser(final int userId, boolean force, final IStopUserCallback callback) { 15069 return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ false, 15070 /* callback= */ callback, /* keyEvictedCallback= */ null); 15071 } 15072 15073 /** 15074 * Stops user but allow delayed locking. Delayed locking keeps user unlocked even after 15075 * stopping only if {@code config_multiuserDelayUserDataLocking} overlay is set true. 15076 * 15077 * <p>When delayed locking is not enabled through the overlay, this call becomes the same 15078 * with {@link #stopUser(int, boolean, IStopUserCallback)} call. 15079 * 15080 * @param userId User id to stop. 15081 * @param force Force stop the user even if the user is related with system user or current 15082 * user. 15083 * @param callback Callback called when user has stopped. 15084 * 15085 * @return {@link ActivityManager#USER_OP_SUCCESS} when user is stopped successfully. Returns 15086 * other {@code ActivityManager#USER_OP_*} codes for failure. 15087 * 15088 */ 15089 @Override stopUserWithDelayedLocking(final int userId, boolean force, final IStopUserCallback callback)15090 public int stopUserWithDelayedLocking(final int userId, boolean force, 15091 final IStopUserCallback callback) { 15092 return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ true, 15093 /* callback= */ callback, /* keyEvictedCallback= */ null); 15094 } 15095 15096 @Override startProfile(@serIdInt int userId)15097 public boolean startProfile(@UserIdInt int userId) { 15098 return mUserController.startProfile(userId); 15099 } 15100 15101 @Override stopProfile(@serIdInt int userId)15102 public boolean stopProfile(@UserIdInt int userId) { 15103 return mUserController.stopProfile(userId); 15104 } 15105 15106 @Override getCurrentUser()15107 public UserInfo getCurrentUser() { 15108 return mUserController.getCurrentUser(); 15109 } 15110 15111 @Override getCurrentUserId()15112 public @UserIdInt int getCurrentUserId() { 15113 return mUserController.getCurrentUserIdChecked(); 15114 } 15115 getStartedUserState(int userId)15116 String getStartedUserState(int userId) { 15117 final UserState userState = mUserController.getStartedUserState(userId); 15118 return UserState.stateToString(userState.state); 15119 } 15120 15121 @Override isUserRunning(int userId, int flags)15122 public boolean isUserRunning(int userId, int flags) { 15123 if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId()) 15124 && checkCallingPermission(INTERACT_ACROSS_USERS) 15125 != PackageManager.PERMISSION_GRANTED) { 15126 String msg = "Permission Denial: isUserRunning() from pid=" 15127 + Binder.getCallingPid() 15128 + ", uid=" + Binder.getCallingUid() 15129 + " requires " + INTERACT_ACROSS_USERS; 15130 Slog.w(TAG, msg); 15131 throw new SecurityException(msg); 15132 } 15133 return mUserController.isUserRunning(userId, flags); 15134 } 15135 15136 @Override getRunningUserIds()15137 public int[] getRunningUserIds() { 15138 if (checkCallingPermission(INTERACT_ACROSS_USERS) 15139 != PackageManager.PERMISSION_GRANTED) { 15140 String msg = "Permission Denial: isUserRunning() from pid=" 15141 + Binder.getCallingPid() 15142 + ", uid=" + Binder.getCallingUid() 15143 + " requires " + INTERACT_ACROSS_USERS; 15144 Slog.w(TAG, msg); 15145 throw new SecurityException(msg); 15146 } 15147 return mUserController.getStartedUserArray(); 15148 } 15149 15150 @Override registerUserSwitchObserver(IUserSwitchObserver observer, String name)15151 public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) { 15152 mUserController.registerUserSwitchObserver(observer, name); 15153 } 15154 15155 @Override unregisterUserSwitchObserver(IUserSwitchObserver observer)15156 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 15157 mUserController.unregisterUserSwitchObserver(observer); 15158 } 15159 getAppInfoForUser(ApplicationInfo info, int userId)15160 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 15161 if (info == null) return null; 15162 ApplicationInfo newInfo = new ApplicationInfo(info); 15163 newInfo.initForUser(userId); 15164 return newInfo; 15165 } 15166 isUserStopped(int userId)15167 public boolean isUserStopped(int userId) { 15168 return mUserController.getStartedUserState(userId) == null; 15169 } 15170 getActivityInfoForUser(ActivityInfo aInfo, int userId)15171 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 15172 if (aInfo == null 15173 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 15174 return aInfo; 15175 } 15176 15177 ActivityInfo info = new ActivityInfo(aInfo); 15178 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 15179 return info; 15180 } 15181 15182 @GuardedBy("mProcLock") processSanityChecksLPr(ProcessRecord process, IApplicationThread thread)15183 private boolean processSanityChecksLPr(ProcessRecord process, IApplicationThread thread) { 15184 if (process == null || thread == null) { 15185 return false; 15186 } 15187 15188 if (!Build.IS_DEBUGGABLE) { 15189 if ((process.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 15190 return false; 15191 } 15192 } 15193 15194 return true; 15195 } 15196 startBinderTracking()15197 public boolean startBinderTracking() throws RemoteException { 15198 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 15199 // permission (same as profileControl). 15200 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 15201 != PackageManager.PERMISSION_GRANTED) { 15202 throw new SecurityException("Requires permission " 15203 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 15204 } 15205 15206 synchronized (mProcLock) { 15207 mBinderTransactionTrackingEnabled = true; 15208 mProcessList.forEachLruProcessesLOSP(true, process -> { 15209 final IApplicationThread thread = process.getThread(); 15210 if (!processSanityChecksLPr(process, thread)) { 15211 return; 15212 } 15213 try { 15214 thread.startBinderTracking(); 15215 } catch (RemoteException e) { 15216 Log.v(TAG, "Process disappared"); 15217 } 15218 }); 15219 } 15220 return true; 15221 } 15222 15223 @Override stopBinderTrackingAndDump(final ParcelFileDescriptor fd)15224 public boolean stopBinderTrackingAndDump(final ParcelFileDescriptor fd) throws RemoteException { 15225 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own 15226 // permission (same as profileControl). 15227 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 15228 != PackageManager.PERMISSION_GRANTED) { 15229 throw new SecurityException("Requires permission " 15230 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 15231 } 15232 15233 boolean closeFd = true; 15234 try { 15235 synchronized (mProcLock) { 15236 if (fd == null) { 15237 throw new IllegalArgumentException("null fd"); 15238 } 15239 mBinderTransactionTrackingEnabled = false; 15240 15241 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor())); 15242 pw.println("Binder transaction traces for all processes.\n"); 15243 mProcessList.forEachLruProcessesLOSP(true, process -> { 15244 final IApplicationThread thread = process.getThread(); 15245 if (!processSanityChecksLPr(process, thread)) { 15246 return; 15247 } 15248 15249 pw.println("Traces for process: " + process.processName); 15250 pw.flush(); 15251 try { 15252 TransferPipe tp = new TransferPipe(); 15253 try { 15254 thread.stopBinderTrackingAndDump(tp.getWriteFd()); 15255 tp.go(fd.getFileDescriptor()); 15256 } finally { 15257 tp.kill(); 15258 } 15259 } catch (IOException e) { 15260 pw.println("Failure while dumping IPC traces from " + process + 15261 ". Exception: " + e); 15262 pw.flush(); 15263 } catch (RemoteException e) { 15264 pw.println("Got a RemoteException while dumping IPC traces from " + 15265 process + ". Exception: " + e); 15266 pw.flush(); 15267 } 15268 }); 15269 closeFd = false; 15270 return true; 15271 } 15272 } finally { 15273 if (fd != null && closeFd) { 15274 try { 15275 fd.close(); 15276 } catch (IOException e) { 15277 } 15278 } 15279 } 15280 } 15281 15282 @VisibleForTesting 15283 public final class LocalService extends ActivityManagerInternal 15284 implements ActivityManagerLocal { 15285 @Override checkContentProviderAccess(String authority, int userId)15286 public String checkContentProviderAccess(String authority, int userId) { 15287 return mCpHelper.checkContentProviderAccess(authority, userId); 15288 } 15289 15290 @Override checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)15291 public int checkContentProviderUriPermission(Uri uri, int userId, 15292 int callingUid, int modeFlags) { 15293 return mCpHelper.checkContentProviderUriPermission(uri, userId, callingUid, modeFlags); 15294 } 15295 15296 @Override onWakefulnessChanged(int wakefulness)15297 public void onWakefulnessChanged(int wakefulness) { 15298 ActivityManagerService.this.onWakefulnessChanged(wakefulness); 15299 } 15300 15301 @Override startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)15302 public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs, 15303 String processName, String abiOverride, int uid, Runnable crashHandler) { 15304 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 15305 processName, abiOverride, uid, crashHandler); 15306 } 15307 15308 @Override onUserRemoved(@serIdInt int userId)15309 public void onUserRemoved(@UserIdInt int userId) { 15310 // Clean up any ActivityTaskManager state (by telling it the user is stopped) 15311 mAtmInternal.onUserStopped(userId); 15312 // Clean up various services by removing the user 15313 mBatteryStatsService.onUserRemoved(userId); 15314 mUserController.onUserRemoved(userId); 15315 } 15316 15317 @Override killForegroundAppsForUser(@serIdInt int userId)15318 public void killForegroundAppsForUser(@UserIdInt int userId) { 15319 final ArrayList<ProcessRecord> procs = new ArrayList<>(); 15320 synchronized (mProcLock) { 15321 final int numOfProcs = mProcessList.getProcessNamesLOSP().getMap().size(); 15322 for (int ip = 0; ip < numOfProcs; ip++) { 15323 final SparseArray<ProcessRecord> apps = 15324 mProcessList.getProcessNamesLOSP().getMap().valueAt(ip); 15325 final int NA = apps.size(); 15326 for (int ia = 0; ia < NA; ia++) { 15327 final ProcessRecord app = apps.valueAt(ia); 15328 if (app.isPersistent()) { 15329 // We don't kill persistent processes. 15330 continue; 15331 } 15332 if (app.isRemoved() 15333 || (app.userId == userId && app.mState.hasForegroundActivities())) { 15334 procs.add(app); 15335 } 15336 } 15337 } 15338 } 15339 15340 final int numOfProcs = procs.size(); 15341 if (numOfProcs > 0) { 15342 synchronized (ActivityManagerService.this) { 15343 for (int i = 0; i < numOfProcs; i++) { 15344 mProcessList.removeProcessLocked(procs.get(i), false, true, 15345 ApplicationExitInfo.REASON_OTHER, 15346 ApplicationExitInfo.SUBREASON_KILL_ALL_FG, 15347 "kill all fg"); 15348 } 15349 } 15350 } 15351 } 15352 15353 @Override setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, int type, @ReasonCode int reasonCode, @Nullable String reason)15354 public void setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, 15355 long duration, int type, @ReasonCode int reasonCode, @Nullable String reason) { 15356 mPendingIntentController.setPendingIntentAllowlistDuration(target, allowlistToken, 15357 duration, type, reasonCode, reason); 15358 } 15359 15360 @Override getPendingIntentFlags(IIntentSender target)15361 public int getPendingIntentFlags(IIntentSender target) { 15362 return mPendingIntentController.getPendingIntentFlags(target); 15363 } 15364 15365 @Override getStartedUserIds()15366 public int[] getStartedUserIds() { 15367 return mUserController.getStartedUserArray(); 15368 } 15369 15370 @Override setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken, int flags)15371 public void setPendingIntentAllowBgActivityStarts(IIntentSender target, 15372 IBinder allowlistToken, int flags) { 15373 if (!(target instanceof PendingIntentRecord)) { 15374 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():" 15375 + " not a PendingIntentRecord: " + target); 15376 return; 15377 } 15378 synchronized (ActivityManagerService.this) { 15379 ((PendingIntentRecord) target).setAllowBgActivityStarts(allowlistToken, flags); 15380 } 15381 } 15382 15383 @Override clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)15384 public void clearPendingIntentAllowBgActivityStarts(IIntentSender target, 15385 IBinder allowlistToken) { 15386 if (!(target instanceof PendingIntentRecord)) { 15387 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():" 15388 + " not a PendingIntentRecord: " + target); 15389 return; 15390 } 15391 synchronized (ActivityManagerService.this) { 15392 ((PendingIntentRecord) target).clearAllowBgActivityStarts(allowlistToken); 15393 } 15394 } 15395 15396 @Override setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)15397 public void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids) { 15398 synchronized (ActivityManagerService.this) { 15399 synchronized (mProcLock) { 15400 mDeviceIdleAllowlist = allAppids; 15401 mDeviceIdleExceptIdleAllowlist = exceptIdleAppids; 15402 } 15403 } 15404 } 15405 15406 @Override updateDeviceIdleTempAllowlist(int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)15407 public void updateDeviceIdleTempAllowlist(int[] appids, int changingUid, boolean adding, 15408 long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, 15409 @Nullable String reason, int callingUid) { 15410 synchronized (ActivityManagerService.this) { 15411 synchronized (mProcLock) { 15412 mDeviceIdleTempAllowlist = appids; 15413 if (adding) { 15414 if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) { 15415 // Note, the device idle temp-allowlist are by app-ids, but here 15416 // mFgsStartTempAllowList contains UIDs. 15417 mFgsStartTempAllowList.add(changingUid, durationMs, 15418 new FgsTempAllowListItem(durationMs, reasonCode, reason, 15419 callingUid)); 15420 } 15421 } else { 15422 // Note in the removing case, we need to remove all the UIDs matching 15423 // the appId, because DeviceIdle's temp-allowlist are based on AppIds, 15424 // not UIDs. 15425 // For eacmple, "cmd deviceidle tempallowlist -r PACKAGE" will 15426 // not only remove this app for user 0, but for all users. 15427 mFgsStartTempAllowList.removeAppId(UserHandle.getAppId(changingUid)); 15428 } 15429 setAppIdTempAllowlistStateLSP(changingUid, adding); 15430 } 15431 } 15432 } 15433 15434 @Override getUidProcessState(int uid)15435 public int getUidProcessState(int uid) { 15436 return getUidState(uid); 15437 } 15438 15439 @Override getProcessesWithPendingBindMounts(int userId)15440 public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) { 15441 return mProcessList.getProcessesWithPendingBindMounts(userId); 15442 } 15443 15444 @Override isSystemReady()15445 public boolean isSystemReady() { 15446 // no need to synchronize(this) just to read & return the value 15447 return mSystemReady; 15448 } 15449 15450 /** 15451 * Sets if the given pid has an overlay UI or not. 15452 * 15453 * @param pid The pid we are setting overlay UI for. 15454 * @param hasOverlayUi True if the process has overlay UI. 15455 * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY 15456 */ 15457 @Override setHasOverlayUi(int pid, boolean hasOverlayUi)15458 public void setHasOverlayUi(int pid, boolean hasOverlayUi) { 15459 synchronized (ActivityManagerService.this) { 15460 final ProcessRecord pr; 15461 synchronized (mPidsSelfLocked) { 15462 pr = mPidsSelfLocked.get(pid); 15463 if (pr == null) { 15464 Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid); 15465 return; 15466 } 15467 } 15468 if (pr.mState.hasOverlayUi() == hasOverlayUi) { 15469 return; 15470 } 15471 pr.mState.setHasOverlayUi(hasOverlayUi); 15472 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid); 15473 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY); 15474 } 15475 } 15476 15477 /** 15478 * Called after the network policy rules are updated by 15479 * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid} 15480 * and {@param procStateSeq}. 15481 */ 15482 @Override notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)15483 public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) { 15484 if (DEBUG_NETWORK) { 15485 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: " 15486 + uid + " seq: " + procStateSeq); 15487 } 15488 UidRecord record; 15489 synchronized (mProcLock) { 15490 record = mProcessList.getUidRecordLOSP(uid); 15491 if (record == null) { 15492 if (DEBUG_NETWORK) { 15493 Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid 15494 + " procStateSeq: " + procStateSeq); 15495 } 15496 return; 15497 } 15498 } 15499 synchronized (record.networkStateLock) { 15500 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 15501 if (DEBUG_NETWORK) { 15502 Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already" 15503 + " been handled for uid: " + uid); 15504 } 15505 return; 15506 } 15507 record.lastNetworkUpdatedProcStateSeq = procStateSeq; 15508 if (record.curProcStateSeq > procStateSeq) { 15509 if (DEBUG_NETWORK) { 15510 Slog.d(TAG_NETWORK, "No need to handle older seq no., Uid: " + uid 15511 + ", curProcstateSeq: " + record.curProcStateSeq 15512 + ", procStateSeq: " + procStateSeq); 15513 } 15514 return; 15515 } 15516 if (record.waitingForNetwork) { 15517 if (DEBUG_NETWORK) { 15518 Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid 15519 + ", procStateSeq: " + procStateSeq); 15520 } 15521 record.networkStateLock.notifyAll(); 15522 } 15523 } 15524 } 15525 15526 @Override isRuntimeRestarted()15527 public boolean isRuntimeRestarted() { 15528 return mSystemServiceManager.isRuntimeRestarted(); 15529 } 15530 15531 @Override canStartMoreUsers()15532 public boolean canStartMoreUsers() { 15533 return mUserController.canStartMoreUsers(); 15534 } 15535 15536 @Override setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)15537 public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) { 15538 mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage); 15539 } 15540 15541 @Override setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)15542 public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) { 15543 mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage); 15544 } 15545 15546 @Override getMaxRunningUsers()15547 public int getMaxRunningUsers() { 15548 return mUserController.getMaxRunningUsers(); 15549 } 15550 15551 @Override isUidActive(int uid)15552 public boolean isUidActive(int uid) { 15553 synchronized (mProcLock) { 15554 return isUidActiveLOSP(uid); 15555 } 15556 } 15557 15558 @Override getMemoryStateForProcesses()15559 public List<ProcessMemoryState> getMemoryStateForProcesses() { 15560 List<ProcessMemoryState> processMemoryStates = new ArrayList<>(); 15561 synchronized (mPidsSelfLocked) { 15562 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) { 15563 final ProcessRecord r = mPidsSelfLocked.valueAt(i); 15564 processMemoryStates.add(new ProcessMemoryState( 15565 r.uid, r.getPid(), r.processName, r.mState.getCurAdj())); 15566 } 15567 } 15568 return processMemoryStates; 15569 } 15570 15571 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)15572 public int handleIncomingUser(int callingPid, int callingUid, int userId, 15573 boolean allowAll, int allowMode, String name, String callerPackage) { 15574 return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll, 15575 allowMode, name, callerPackage); 15576 } 15577 15578 @Override enforceCallingPermission(String permission, String func)15579 public void enforceCallingPermission(String permission, String func) { 15580 ActivityManagerService.this.enforceCallingPermission(permission, func); 15581 } 15582 15583 @Override getCurrentUserId()15584 public int getCurrentUserId() { 15585 return mUserController.getCurrentUserId(); 15586 } 15587 15588 @Override isUserRunning(int userId, int flags)15589 public boolean isUserRunning(int userId, int flags) { 15590 // Holding am lock isn't required to call into user controller. 15591 return mUserController.isUserRunning(userId, flags); 15592 } 15593 15594 @Override trimApplications()15595 public void trimApplications() { 15596 ActivityManagerService.this.trimApplications(true, OomAdjuster.OOM_ADJ_REASON_ACTIVITY); 15597 } 15598 killProcessesForRemovedTask(ArrayList<Object> procsToKill)15599 public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) { 15600 synchronized (ActivityManagerService.this) { 15601 for (int i = 0; i < procsToKill.size(); i++) { 15602 final WindowProcessController wpc = 15603 (WindowProcessController) procsToKill.get(i); 15604 final ProcessRecord pr = (ProcessRecord) wpc.mOwner; 15605 if (pr.mState.getSetSchedGroup() == ProcessList.SCHED_GROUP_BACKGROUND 15606 && pr.mReceivers.numberOfCurReceivers() == 0) { 15607 pr.killLocked("remove task", ApplicationExitInfo.REASON_USER_REQUESTED, 15608 ApplicationExitInfo.SUBREASON_UNKNOWN, true); 15609 } else { 15610 // We delay killing processes that are not in the background or running a 15611 // receiver. 15612 pr.setWaitingToKill("remove task"); 15613 } 15614 } 15615 } 15616 } 15617 15618 @Override killProcess(String processName, int uid, String reason)15619 public void killProcess(String processName, int uid, String reason) { 15620 synchronized (ActivityManagerService.this) { 15621 final ProcessRecord proc = getProcessRecordLocked(processName, uid); 15622 if (proc != null) { 15623 mProcessList.removeProcessLocked(proc, false /* callerWillRestart */, 15624 true /* allowRestart */, ApplicationExitInfo.REASON_OTHER, reason); 15625 } 15626 } 15627 } 15628 15629 @Override hasRunningActivity(int uid, @Nullable String packageName)15630 public boolean hasRunningActivity(int uid, @Nullable String packageName) { 15631 if (packageName == null) return false; 15632 15633 synchronized (mProcLock) { 15634 return mProcessList.searchEachLruProcessesLOSP(true, app -> { 15635 if (app.uid == uid 15636 && app.getWindowProcessController().hasRunningActivity(packageName)) { 15637 return Boolean.TRUE; 15638 } 15639 return null; 15640 }) != null; 15641 } 15642 } 15643 15644 @Override updateOomAdj()15645 public void updateOomAdj() { 15646 synchronized (ActivityManagerService.this) { 15647 ActivityManagerService.this.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); 15648 } 15649 } 15650 15651 @Override updateCpuStats()15652 public void updateCpuStats() { 15653 ActivityManagerService.this.updateCpuStats(); 15654 } 15655 15656 @Override updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)15657 public void updateBatteryStats(ComponentName activity, int uid, int userId, 15658 boolean resumed) { 15659 ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed); 15660 } 15661 15662 @Override updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)15663 public void updateActivityUsageStats(ComponentName activity, int userId, int event, 15664 IBinder appToken, ComponentName taskRoot) { 15665 ActivityManagerService.this.updateActivityUsageStats(activity, userId, event, 15666 appToken, taskRoot); 15667 } 15668 15669 @Override updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)15670 public void updateForegroundTimeIfOnBattery( 15671 String packageName, int uid, long cpuTimeDiff) { 15672 mBatteryStatsService.updateForegroundTimeIfOnBattery(packageName, uid, cpuTimeDiff); 15673 } 15674 15675 @Override sendForegroundProfileChanged(int userId)15676 public void sendForegroundProfileChanged(int userId) { 15677 mUserController.sendForegroundProfileChanged(userId); 15678 } 15679 15680 @Override shouldConfirmCredentials(int userId)15681 public boolean shouldConfirmCredentials(int userId) { 15682 return mUserController.shouldConfirmCredentials(userId); 15683 } 15684 15685 @Override noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)15686 public void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, 15687 String tag) { 15688 ActivityManagerService.this.noteAlarmFinish((ps != null) ? ps.getTarget() : null, 15689 workSource, sourceUid, tag); 15690 } 15691 15692 @Override noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)15693 public void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, 15694 String tag) { 15695 ActivityManagerService.this.noteAlarmStart((ps != null) ? ps.getTarget() : null, 15696 workSource, sourceUid, tag); 15697 } 15698 15699 @Override noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)15700 public void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, 15701 String sourcePkg, String tag) { 15702 ActivityManagerService.this.noteWakeupAlarm((ps != null) ? ps.getTarget() : null, 15703 workSource, sourceUid, sourcePkg, tag); 15704 } 15705 15706 @Override isAppStartModeDisabled(int uid, String packageName)15707 public boolean isAppStartModeDisabled(int uid, String packageName) { 15708 return ActivityManagerService.this.isAppStartModeDisabled(uid, packageName); 15709 } 15710 15711 @Override getCurrentProfileIds()15712 public int[] getCurrentProfileIds() { 15713 return mUserController.getCurrentProfileIds(); 15714 } 15715 15716 @Override getCurrentUser()15717 public UserInfo getCurrentUser() { 15718 return mUserController.getCurrentUser(); 15719 } 15720 15721 @Override ensureNotSpecialUser(int userId)15722 public void ensureNotSpecialUser(int userId) { 15723 mUserController.ensureNotSpecialUser(userId); 15724 } 15725 15726 @Override isCurrentProfile(int userId)15727 public boolean isCurrentProfile(int userId) { 15728 return mUserController.isCurrentProfile(userId); 15729 } 15730 15731 @Override hasStartedUserState(int userId)15732 public boolean hasStartedUserState(int userId) { 15733 return mUserController.hasStartedUserState(userId); 15734 } 15735 15736 @Override finishUserSwitch(Object uss)15737 public void finishUserSwitch(Object uss) { 15738 mUserController.finishUserSwitch((UserState) uss); 15739 } 15740 15741 @Override scheduleAppGcs()15742 public void scheduleAppGcs() { 15743 synchronized (mAppProfiler.mProfilerLock) { 15744 mAppProfiler.scheduleAppGcsLPf(); 15745 } 15746 } 15747 15748 @Override getTaskIdForActivity(IBinder token, boolean onlyRoot)15749 public int getTaskIdForActivity(IBinder token, boolean onlyRoot) { 15750 return ActivityManagerService.this.getTaskForActivity(token, onlyRoot); 15751 } 15752 15753 @Override getActivityPresentationInfo(IBinder token)15754 public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) { 15755 final ActivityClient ac = ActivityClient.getInstance(); 15756 return new ActivityPresentationInfo(ac.getTaskForActivity(token, 15757 /*onlyRoot=*/ false), ac.getDisplayId(token), 15758 mAtmInternal.getActivityName(token)); 15759 } 15760 15761 @Override setBooting(boolean booting)15762 public void setBooting(boolean booting) { 15763 mBooting = booting; 15764 } 15765 15766 @Override isBooting()15767 public boolean isBooting() { 15768 return mBooting; 15769 } 15770 15771 @Override setBooted(boolean booted)15772 public void setBooted(boolean booted) { 15773 mBooted = booted; 15774 } 15775 15776 @Override isBooted()15777 public boolean isBooted() { 15778 return mBooted; 15779 } 15780 15781 @Override finishBooting()15782 public void finishBooting() { 15783 ActivityManagerService.this.finishBooting(); 15784 } 15785 15786 @Override tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)15787 public void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, 15788 long duration, int type, @ReasonCode int reasonCode, String reason) { 15789 synchronized (ActivityManagerService.this) { 15790 ActivityManagerService.this.tempAllowlistForPendingIntentLocked( 15791 callerPid, callerUid, targetUid, duration, type, reasonCode, reason); 15792 } 15793 } 15794 15795 @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)15796 public int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, 15797 int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 15798 IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, 15799 String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, 15800 int userId, boolean allowBackgroundActivityStarts, 15801 @Nullable IBinder backgroundActivityStartsToken) { 15802 synchronized (ActivityManagerService.this) { 15803 return ActivityManagerService.this.broadcastIntentInPackage(packageName, featureId, 15804 uid, realCallingUid, realCallingPid, intent, resolvedType, resultTo, 15805 resultCode, resultData, resultExtras, requiredPermission, bOptions, 15806 serialized, sticky, userId, allowBackgroundActivityStarts, 15807 backgroundActivityStartsToken); 15808 } 15809 } 15810 15811 @Override broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable Bundle bOptions)15812 public int broadcastIntent(Intent intent, 15813 IIntentReceiver resultTo, 15814 String[] requiredPermissions, 15815 boolean serialized, int userId, int[] appIdAllowList, @Nullable Bundle bOptions) { 15816 synchronized (ActivityManagerService.this) { 15817 intent = verifyBroadcastLocked(intent); 15818 15819 final int callingPid = Binder.getCallingPid(); 15820 final int callingUid = Binder.getCallingUid(); 15821 final long origId = Binder.clearCallingIdentity(); 15822 try { 15823 return ActivityManagerService.this.broadcastIntentLocked(null /*callerApp*/, 15824 null /*callerPackage*/, null /*callingFeatureId*/, intent, 15825 null /*resolvedType*/, resultTo, 0 /*resultCode*/, null /*resultData*/, 15826 null /*resultExtras*/, requiredPermissions, null, AppOpsManager.OP_NONE, 15827 bOptions /*options*/, serialized, false /*sticky*/, callingPid, 15828 callingUid, callingUid, callingPid, userId, 15829 false /*allowBackgroundStarts*/, 15830 null /*tokenNeededForBackgroundActivityStarts*/, appIdAllowList); 15831 } finally { 15832 Binder.restoreCallingIdentity(origId); 15833 } 15834 } 15835 15836 } 15837 15838 @Override startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)15839 public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType, 15840 boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, 15841 int userId, boolean allowBackgroundActivityStarts, 15842 @Nullable IBinder backgroundActivityStartsToken) 15843 throws TransactionTooLargeException { 15844 synchronized(ActivityManagerService.this) { 15845 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 15846 "startServiceInPackage: " + service + " type=" + resolvedType); 15847 final long origId = Binder.clearCallingIdentity(); 15848 ComponentName res; 15849 try { 15850 res = mServices.startServiceLocked(null, service, 15851 resolvedType, -1, uid, fgRequired, callingPackage, 15852 callingFeatureId, userId, allowBackgroundActivityStarts, 15853 backgroundActivityStartsToken); 15854 } finally { 15855 Binder.restoreCallingIdentity(origId); 15856 } 15857 return res; 15858 } 15859 } 15860 15861 // The arguments here are untyped because the base ActivityManagerInternal class 15862 // doesn't have compile-time visibility into ActivityServiceConnectionHolder or 15863 // ConnectionRecord. 15864 @Override disconnectActivityFromServices(Object connectionHolder)15865 public void disconnectActivityFromServices(Object connectionHolder) { 15866 // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder 15867 final ActivityServiceConnectionsHolder holder = 15868 (ActivityServiceConnectionsHolder) connectionHolder; 15869 synchronized (ActivityManagerService.this) { 15870 synchronized (mProcLock) { 15871 holder.forEachConnection(cr -> mServices.removeConnectionLocked( 15872 (ConnectionRecord) cr, null /* skipApp */, holder /* skipAct */, 15873 false /* enqueueOomAdj */)); 15874 } 15875 } 15876 } 15877 cleanUpServices(int userId, ComponentName component, Intent baseIntent)15878 public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) { 15879 synchronized(ActivityManagerService.this) { 15880 mServices.cleanUpServices(userId, component, baseIntent); 15881 } 15882 } 15883 getActivityInfoForUser(ActivityInfo aInfo, int userId)15884 public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 15885 // Locked intentionally not held as it isn't needed for this case. 15886 return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId); 15887 } 15888 ensureBootCompleted()15889 public void ensureBootCompleted() { 15890 // Locked intentionally not held as it isn't needed for this case. 15891 ActivityManagerService.this.ensureBootCompleted(); 15892 } 15893 updateOomLevelsForDisplay(int displayId)15894 public void updateOomLevelsForDisplay(int displayId) { 15895 synchronized(ActivityManagerService.this) { 15896 if (mWindowManager != null) { 15897 mProcessList.applyDisplaySize(mWindowManager); 15898 } 15899 } 15900 } 15901 isActivityStartsLoggingEnabled()15902 public boolean isActivityStartsLoggingEnabled() { 15903 return mConstants.mFlagActivityStartsLoggingEnabled; 15904 } 15905 isBackgroundActivityStartsEnabled()15906 public boolean isBackgroundActivityStartsEnabled() { 15907 return mConstants.mFlagBackgroundActivityStartsEnabled; 15908 } 15909 reportCurKeyguardUsageEvent(boolean keyguardShowing)15910 public void reportCurKeyguardUsageEvent(boolean keyguardShowing) { 15911 ActivityManagerService.this.reportGlobalUsageEvent(keyguardShowing 15912 ? UsageEvents.Event.KEYGUARD_SHOWN 15913 : UsageEvents.Event.KEYGUARD_HIDDEN); 15914 } 15915 15916 @Override monitor()15917 public void monitor() { 15918 ActivityManagerService.this.monitor(); 15919 } 15920 15921 @Override inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason)15922 public long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason) { 15923 return ActivityManagerService.this.inputDispatchingTimedOut(pid, aboveSystem, reason); 15924 } 15925 15926 @Override inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, String reason)15927 public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName, 15928 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, 15929 boolean aboveSystem, String reason) { 15930 return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc, 15931 activityShortComponentName, aInfo, parentShortComponentName, 15932 (WindowProcessController) parentProc, aboveSystem, reason); 15933 15934 } 15935 15936 @Override inputDispatchingResumed(int pid)15937 public void inputDispatchingResumed(int pid) { 15938 // TODO (b/171218828) 15939 return; 15940 } 15941 15942 @Override broadcastGlobalConfigurationChanged(int changes, boolean initLocale)15943 public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) { 15944 synchronized (ActivityManagerService.this) { 15945 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 15946 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 15947 | Intent.FLAG_RECEIVER_REPLACE_PENDING 15948 | Intent.FLAG_RECEIVER_FOREGROUND 15949 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 15950 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 15951 null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID, 15952 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 15953 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) { 15954 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 15955 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND 15956 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND 15957 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 15958 if (initLocale || !mProcessesReady) { 15959 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 15960 } 15961 final BroadcastOptions bOptions = BroadcastOptions.makeBasic(); 15962 bOptions.setTemporaryAppAllowlist(mInternal.getBootTimeTempAllowListDuration(), 15963 TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED, 15964 PowerExemptionManager.REASON_LOCALE_CHANGED, ""); 15965 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 15966 null, OP_NONE, bOptions.toBundle(), false, false, MY_PID, SYSTEM_UID, 15967 Binder.getCallingUid(), Binder.getCallingPid(), 15968 UserHandle.USER_ALL); 15969 } 15970 15971 // Send a broadcast to PackageInstallers if the configuration change is interesting 15972 // for the purposes of installing additional splits. 15973 if (!initLocale && isSplitConfigurationChange(changes)) { 15974 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED); 15975 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING 15976 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 15977 15978 // Typically only app stores will have this permission. 15979 String[] permissions = 15980 new String[] { android.Manifest.permission.INSTALL_PACKAGES }; 15981 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, 15982 permissions, null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID, 15983 Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL); 15984 } 15985 } 15986 } 15987 15988 /** 15989 * Returns true if this configuration change is interesting enough to send an 15990 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast. 15991 */ isSplitConfigurationChange(int configDiff)15992 private boolean isSplitConfigurationChange(int configDiff) { 15993 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0; 15994 } 15995 15996 @Override broadcastCloseSystemDialogs(String reason)15997 public void broadcastCloseSystemDialogs(String reason) { 15998 synchronized (ActivityManagerService.this) { 15999 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 16000 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 16001 | Intent.FLAG_RECEIVER_FOREGROUND); 16002 if (reason != null) { 16003 intent.putExtra("reason", reason); 16004 } 16005 16006 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, 16007 null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(), 16008 Binder.getCallingPid(), UserHandle.USER_ALL); 16009 } 16010 } 16011 16012 @Override killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)16013 public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 16014 synchronized (ActivityManagerService.this) { 16015 ActivityManagerService.this.killAllBackgroundProcessesExcept( 16016 minTargetSdk, maxProcState); 16017 } 16018 } 16019 16020 @Override startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)16021 public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, 16022 boolean isTop, String hostingType, ComponentName hostingName) { 16023 try { 16024 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 16025 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:" 16026 + processName); 16027 } 16028 synchronized (ActivityManagerService.this) { 16029 // If the process is known as top app, set a hint so when the process is 16030 // started, the top priority can be applied immediately to avoid cpu being 16031 // preempted by other processes before attaching the process of top app. 16032 startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */, 16033 new HostingRecord(hostingType, hostingName, isTop), 16034 ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */, 16035 false /* isolated */); 16036 } 16037 } finally { 16038 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 16039 } 16040 } 16041 16042 @Override setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)16043 public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, 16044 ProfilerInfo profilerInfo, Object wmLock) { 16045 synchronized (ActivityManagerService.this) { 16046 /** 16047 * This function is called from the window manager context and needs to be executed 16048 * synchronously. To avoid deadlock, we pass a message to AMS to execute the 16049 * function and notify the passed in lock when it has been completed. 16050 */ 16051 synchronized (wmLock) { 16052 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) { 16053 setDebugApp(aInfo.processName, true, false); 16054 } 16055 16056 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) { 16057 setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName); 16058 } 16059 16060 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) { 16061 setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName); 16062 } 16063 16064 if (profilerInfo != null) { 16065 setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo); 16066 } 16067 wmLock.notify(); 16068 } 16069 } 16070 } 16071 16072 @Override getStorageMountMode(int pid, int uid)16073 public int getStorageMountMode(int pid, int uid) { 16074 if (uid == SHELL_UID || uid == ROOT_UID) { 16075 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16076 } 16077 synchronized (mPidsSelfLocked) { 16078 final ProcessRecord pr = mPidsSelfLocked.get(pid); 16079 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.getMountMode(); 16080 } 16081 } 16082 16083 @Override isAppForeground(int uid)16084 public boolean isAppForeground(int uid) { 16085 return ActivityManagerService.this.isAppForeground(uid); 16086 } 16087 16088 @Override isAppBad(final String processName, final int uid)16089 public boolean isAppBad(final String processName, final int uid) { 16090 return ActivityManagerService.this.isAppBad(processName, uid); 16091 } 16092 16093 @Override clearPendingBackup(int userId)16094 public void clearPendingBackup(int userId) { 16095 ActivityManagerService.this.clearPendingBackup(userId); 16096 } 16097 16098 /** 16099 * When power button is very long pressed, call this interface to do some pre-shutdown work 16100 * like persisting database etc. 16101 */ 16102 @Override prepareForPossibleShutdown()16103 public void prepareForPossibleShutdown() { 16104 ActivityManagerService.this.prepareForPossibleShutdown(); 16105 } 16106 16107 @Override hasRunningForegroundService(int uid, int foregroundServicetype)16108 public boolean hasRunningForegroundService(int uid, int foregroundServicetype) { 16109 synchronized (ActivityManagerService.this) { 16110 return mProcessList.searchEachLruProcessesLOSP(true, app -> { 16111 if (app.uid != uid) { 16112 return null; 16113 } 16114 16115 if ((app.mServices.getForegroundServiceTypes() & foregroundServicetype) != 0) { 16116 return Boolean.TRUE; 16117 } 16118 return null; 16119 }) != null; 16120 } 16121 } 16122 16123 @Override 16124 public boolean hasForegroundServiceNotification(String pkg, int userId, 16125 String channelId) { 16126 synchronized (ActivityManagerService.this) { 16127 return mServices.hasForegroundServiceNotificationLocked(pkg, userId, channelId); 16128 } 16129 } 16130 16131 @Override 16132 public ServiceNotificationPolicy applyForegroundServiceNotification( 16133 Notification notification, String tag, int id, String pkg, int userId) { 16134 synchronized (ActivityManagerService.this) { 16135 return mServices.applyForegroundServiceNotificationLocked(notification, 16136 tag, id, pkg, userId); 16137 } 16138 } 16139 16140 @Override 16141 public void onForegroundServiceNotificationUpdate(boolean shown, 16142 Notification notification, int id, String pkg, @UserIdInt int userId) { 16143 synchronized (ActivityManagerService.this) { 16144 mServices.onForegroundServiceNotificationUpdateLocked(shown, 16145 notification, id, pkg, userId); 16146 } 16147 } 16148 16149 @Override 16150 public void stopForegroundServicesForChannel(String pkg, int userId, 16151 String channelId) { 16152 synchronized (ActivityManagerService.this) { 16153 mServices.stopForegroundServicesForChannelLocked(pkg, userId, channelId); 16154 } 16155 } 16156 16157 @Override 16158 public void registerProcessObserver(IProcessObserver processObserver) { 16159 ActivityManagerService.this.registerProcessObserver(processObserver); 16160 } 16161 16162 @Override 16163 public void unregisterProcessObserver(IProcessObserver processObserver) { 16164 ActivityManagerService.this.unregisterProcessObserver(processObserver); 16165 } 16166 16167 @Override 16168 public boolean isUidCurrentlyInstrumented(int uid) { 16169 synchronized (mProcLock) { 16170 for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) { 16171 ActiveInstrumentation activeInst = mActiveInstrumentation.get(i); 16172 if (!activeInst.mFinished && activeInst.mTargetInfo != null 16173 && activeInst.mTargetInfo.uid == uid) { 16174 return true; 16175 } 16176 } 16177 } 16178 return false; 16179 } 16180 16181 @Override 16182 public void setDeviceOwnerUid(int uid) { 16183 mDeviceOwnerUid = uid; 16184 } 16185 16186 @Override 16187 public boolean isDeviceOwner(int uid) { 16188 int cachedUid = mDeviceOwnerUid; 16189 return uid >= 0 && cachedUid == uid; 16190 } 16191 16192 16193 @Override 16194 public void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids) { 16195 synchronized (ActivityManagerService.this) { 16196 mProfileOwnerUids = profileOwnerUids; 16197 } 16198 } 16199 16200 @Override 16201 public boolean isProfileOwner(int uid) { 16202 synchronized (ActivityManagerService.this) { 16203 return mProfileOwnerUids != null && mProfileOwnerUids.indexOf(uid) >= 0; 16204 } 16205 } 16206 16207 @Override 16208 public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) { 16209 synchronized (ActivityManagerService.this) { 16210 mCompanionAppUidsMap.put(userId, companionAppUids); 16211 } 16212 } 16213 16214 @Override 16215 public boolean isAssociatedCompanionApp(int userId, int uid) { 16216 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId); 16217 if (allUids == null) { 16218 return false; 16219 } 16220 return allUids.contains(uid); 16221 } 16222 16223 @Override 16224 public void addPendingTopUid(int uid, int pid) { 16225 mPendingStartActivityUids.add(uid, pid); 16226 } 16227 16228 @Override 16229 public void deletePendingTopUid(int uid) { 16230 mPendingStartActivityUids.delete(uid); 16231 } 16232 16233 @Override 16234 public boolean isPendingTopUid(int uid) { 16235 return mPendingStartActivityUids.isPendingTopUid(uid); 16236 } 16237 16238 @Override 16239 public Intent getIntentForIntentSender(IIntentSender sender) { 16240 return ActivityManagerService.this.getIntentForIntentSender(sender); 16241 } 16242 16243 @Override 16244 public PendingIntent getPendingIntentActivityAsApp( 16245 int requestCode, @NonNull Intent intent, int flags, Bundle options, 16246 String ownerPkg, int ownerUid) { 16247 return getPendingIntentActivityAsApp(requestCode, new Intent[] { intent }, flags, 16248 options, ownerPkg, ownerUid); 16249 } 16250 16251 @Override 16252 public PendingIntent getPendingIntentActivityAsApp( 16253 int requestCode, @NonNull Intent[] intents, int flags, Bundle options, 16254 String ownerPkg, int ownerUid) { 16255 // system callers must explicitly set mutability state 16256 final boolean flagImmutableSet = (flags & PendingIntent.FLAG_IMMUTABLE) != 0; 16257 final boolean flagMutableSet = (flags & PendingIntent.FLAG_MUTABLE) != 0; 16258 if (flagImmutableSet == flagMutableSet) { 16259 throw new IllegalArgumentException( 16260 "Must set exactly one of FLAG_IMMUTABLE or FLAG_MUTABLE"); 16261 } 16262 16263 final Context context = ActivityManagerService.this.mContext; 16264 final ContentResolver resolver = context.getContentResolver(); 16265 final int len = intents.length; 16266 final String[] resolvedTypes = new String[len]; 16267 for (int i = 0; i < len; i++) { 16268 final Intent intent = intents[i]; 16269 resolvedTypes[i] = intent.resolveTypeIfNeeded(resolver); 16270 intent.migrateExtraStreamToClipData(context); 16271 intent.prepareToLeaveProcess(context); 16272 } 16273 IIntentSender target = 16274 ActivityManagerService.this.getIntentSenderWithFeatureAsApp( 16275 INTENT_SENDER_ACTIVITY, ownerPkg, 16276 context.getAttributionTag(), null, null, requestCode, 16277 intents, 16278 resolvedTypes, 16279 flags, options, UserHandle.getUserId(ownerUid), ownerUid); 16280 return target != null ? new PendingIntent(target) : null; 16281 } 16282 16283 @Override 16284 public long getBootTimeTempAllowListDuration() { 16285 // Do not lock ActivityManagerService.this here, this API is called by 16286 // PackageManagerService. 16287 return mConstants.mBootTimeTempAllowlistDuration; 16288 } 16289 16290 @Override 16291 public void registerAnrController(AnrController controller) { 16292 mActivityTaskManager.registerAnrController(controller); 16293 } 16294 16295 @Override 16296 public void unregisterAnrController(AnrController controller) { 16297 mActivityTaskManager.unregisterAnrController(controller); 16298 } 16299 16300 @Override 16301 public boolean canStartForegroundService(int pid, int uid, @NonNull String packageName) { 16302 synchronized (ActivityManagerService.this) { 16303 return mServices.canStartForegroundServiceLocked(pid, uid, packageName); 16304 } 16305 } 16306 16307 @Override 16308 public void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs) { 16309 mFgsWhileInUseTempAllowList.add(uid, durationMs, ""); 16310 } 16311 16312 @Override 16313 public boolean isTempAllowlistedForFgsWhileInUse(int uid) { 16314 return mFgsWhileInUseTempAllowList.isAllowed(uid); 16315 } 16316 16317 @Override 16318 public boolean canAllowWhileInUsePermissionInFgs(int pid, int uid, 16319 @NonNull String packageName) { 16320 synchronized (ActivityManagerService.this) { 16321 return mServices.canAllowWhileInUsePermissionInFgsLocked(pid, uid, packageName); 16322 } 16323 } 16324 16325 @Override 16326 public @TempAllowListType int getPushMessagingOverQuotaBehavior() { 16327 synchronized (ActivityManagerService.this) { 16328 return mConstants.mPushMessagingOverQuotaBehavior; 16329 } 16330 } 16331 16332 @Override 16333 public int getUidCapability(int uid) { 16334 synchronized (ActivityManagerService.this) { 16335 UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid); 16336 if (uidRecord == null) { 16337 throw new IllegalArgumentException("uid record for " + uid + " not found"); 16338 } 16339 return uidRecord.getCurCapability(); 16340 } 16341 } 16342 16343 /** 16344 * @return The PID list of the isolated process with packages matching the given uid. 16345 */ 16346 @Nullable 16347 public List<Integer> getIsolatedProcesses(int uid) { 16348 synchronized (ActivityManagerService.this) { 16349 return mProcessList.getIsolatedProcessesLocked(uid); 16350 } 16351 } 16352 } 16353 16354 long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) { 16355 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 16356 throw new SecurityException("Requires permission " + FILTER_EVENTS); 16357 } 16358 ProcessRecord proc; 16359 synchronized (mPidsSelfLocked) { 16360 proc = mPidsSelfLocked.get(pid); 16361 } 16362 final long timeoutMillis = proc != null ? proc.getInputDispatchingTimeoutMillis() : 16363 DEFAULT_DISPATCHING_TIMEOUT_MILLIS; 16364 16365 if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, reason)) { 16366 return 0; 16367 } 16368 16369 return timeoutMillis; 16370 } 16371 16372 /** 16373 * Handle input dispatching timeouts. 16374 * @return whether input dispatching should be aborted or not. 16375 */ 16376 boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, 16377 ApplicationInfo aInfo, String parentShortComponentName, 16378 WindowProcessController parentProcess, boolean aboveSystem, String reason) { 16379 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) { 16380 throw new SecurityException("Requires permission " + FILTER_EVENTS); 16381 } 16382 16383 final String annotation; 16384 if (reason == null) { 16385 annotation = "Input dispatching timed out"; 16386 } else { 16387 annotation = "Input dispatching timed out (" + reason + ")"; 16388 } 16389 16390 if (proc != null) { 16391 synchronized (this) { 16392 if (proc.isDebugging()) { 16393 return false; 16394 } 16395 16396 if (proc.getActiveInstrumentation() != null) { 16397 Bundle info = new Bundle(); 16398 info.putString("shortMsg", "keyDispatchingTimedOut"); 16399 info.putString("longMsg", annotation); 16400 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 16401 return true; 16402 } 16403 } 16404 mAnrHelper.appNotResponding(proc, activityShortComponentName, aInfo, 16405 parentShortComponentName, parentProcess, aboveSystem, annotation); 16406 } 16407 16408 return true; 16409 } 16410 16411 /** 16412 * Called by app main thread to wait for the network policy rules to get updated. 16413 * 16414 * @param procStateSeq The sequence number indicating the process state change that the main 16415 * thread is interested in. 16416 */ 16417 @Override 16418 public void waitForNetworkStateUpdate(long procStateSeq) { 16419 final int callingUid = Binder.getCallingUid(); 16420 if (DEBUG_NETWORK) { 16421 Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq); 16422 } 16423 UidRecord record; 16424 synchronized (mProcLock) { 16425 record = mProcessList.getUidRecordLOSP(callingUid); 16426 if (record == null) { 16427 return; 16428 } 16429 } 16430 synchronized (record.networkStateLock) { 16431 if (record.lastDispatchedProcStateSeq < procStateSeq) { 16432 if (DEBUG_NETWORK) { 16433 Slog.d(TAG_NETWORK, "Uid state change for seq no. " + procStateSeq + " is not " 16434 + "dispatched to NPMS yet, so don't wait. Uid: " + callingUid 16435 + " lastProcStateSeqDispatchedToObservers: " 16436 + record.lastDispatchedProcStateSeq); 16437 } 16438 return; 16439 } 16440 if (record.curProcStateSeq > procStateSeq) { 16441 if (DEBUG_NETWORK) { 16442 Slog.d(TAG_NETWORK, "Ignore the wait requests for older seq numbers. Uid: " 16443 + callingUid + ", curProcStateSeq: " + record.curProcStateSeq 16444 + ", procStateSeq: " + procStateSeq); 16445 } 16446 return; 16447 } 16448 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) { 16449 if (DEBUG_NETWORK) { 16450 Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. " 16451 + procStateSeq + ", so no need to wait. Uid: " 16452 + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: " 16453 + record.lastNetworkUpdatedProcStateSeq); 16454 } 16455 return; 16456 } 16457 try { 16458 if (DEBUG_NETWORK) { 16459 Slog.d(TAG_NETWORK, "Starting to wait for the network rules update." 16460 + " Uid: " + callingUid + " procStateSeq: " + procStateSeq); 16461 } 16462 final long startTime = SystemClock.uptimeMillis(); 16463 record.waitingForNetwork = true; 16464 record.networkStateLock.wait(mWaitForNetworkTimeoutMs); 16465 record.waitingForNetwork = false; 16466 final long totalTime = SystemClock.uptimeMillis() - startTime; 16467 if (totalTime >= mWaitForNetworkTimeoutMs || DEBUG_NETWORK) { 16468 Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: " 16469 + totalTime + ". Uid: " + callingUid + " procStateSeq: " 16470 + procStateSeq + " UidRec: " + record 16471 + " validateUidRec: " 16472 + mUidObserverController.getValidateUidRecord(callingUid)); 16473 } 16474 } catch (InterruptedException e) { 16475 Thread.currentThread().interrupt(); 16476 } 16477 } 16478 } 16479 16480 @Override 16481 public void waitForBroadcastIdle() { 16482 waitForBroadcastIdle(/* printWriter= */ null); 16483 } 16484 16485 public void waitForBroadcastIdle(@Nullable PrintWriter pw) { 16486 enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()"); 16487 while (true) { 16488 boolean idle = true; 16489 synchronized (this) { 16490 for (BroadcastQueue queue : mBroadcastQueues) { 16491 if (!queue.isIdle()) { 16492 final String msg = "Waiting for queue " + queue + " to become idle..."; 16493 if (pw != null) { 16494 pw.println(msg); 16495 pw.println(queue.describeState()); 16496 pw.flush(); 16497 } 16498 Slog.v(TAG, msg); 16499 queue.cancelDeferrals(); 16500 idle = false; 16501 } 16502 } 16503 } 16504 16505 if (idle) { 16506 final String msg = "All broadcast queues are idle!"; 16507 if (pw != null) { 16508 pw.println(msg); 16509 pw.flush(); 16510 } 16511 Slog.v(TAG, msg); 16512 return; 16513 } else { 16514 SystemClock.sleep(1000); 16515 } 16516 } 16517 } 16518 16519 /** 16520 * Force the settings cache to be loaded 16521 */ 16522 void refreshSettingsCache() { 16523 mCoreSettingsObserver.onChange(true); 16524 } 16525 16526 /** 16527 * Kill processes for the user with id userId and that depend on the package named packageName 16528 */ 16529 @Override 16530 public void killPackageDependents(String packageName, int userId) { 16531 enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()"); 16532 if (packageName == null) { 16533 throw new NullPointerException( 16534 "Cannot kill the dependents of a package without its name."); 16535 } 16536 16537 final long callingId = Binder.clearCallingIdentity(); 16538 IPackageManager pm = AppGlobals.getPackageManager(); 16539 int pkgUid = -1; 16540 try { 16541 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 16542 } catch (RemoteException e) { 16543 } 16544 if (userId != UserHandle.USER_ALL && pkgUid == -1) { 16545 throw new IllegalArgumentException( 16546 "Cannot kill dependents of non-existing package " + packageName); 16547 } 16548 try { 16549 synchronized(this) { 16550 synchronized (mProcLock) { 16551 mProcessList.killPackageProcessesLSP(packageName, UserHandle.getAppId(pkgUid), 16552 userId, ProcessList.FOREGROUND_APP_ADJ, 16553 ApplicationExitInfo.REASON_DEPENDENCY_DIED, 16554 ApplicationExitInfo.SUBREASON_UNKNOWN, 16555 "dep: " + packageName); 16556 } 16557 } 16558 } finally { 16559 Binder.restoreCallingIdentity(callingId); 16560 } 16561 } 16562 16563 @Override 16564 public int restartUserInBackground(final int userId) { 16565 return mUserController.restartUser(userId, /* foreground */ false); 16566 } 16567 16568 @Override 16569 public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) { 16570 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 16571 "scheduleApplicationInfoChanged()"); 16572 16573 final long origId = Binder.clearCallingIdentity(); 16574 try { 16575 final boolean updateFrameworkRes = packageNames.contains("android"); 16576 synchronized (mProcLock) { 16577 updateApplicationInfoLOSP(packageNames, updateFrameworkRes, userId); 16578 } 16579 16580 AppWidgetManagerInternal widgets = LocalServices.getService( 16581 AppWidgetManagerInternal.class); 16582 if (widgets != null) { 16583 widgets.applyResourceOverlaysToWidgets(new HashSet<>(packageNames), userId, 16584 updateFrameworkRes); 16585 } 16586 } finally { 16587 Binder.restoreCallingIdentity(origId); 16588 } 16589 } 16590 16591 /** 16592 * Synchronously update the system ActivityThread, bypassing any deferred threading so any 16593 * resources and overlaid values are available immediately. 16594 */ 16595 public void updateSystemUiContext() { 16596 final PackageManagerInternal packageManagerInternal = getPackageManagerInternal(); 16597 16598 ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android", 16599 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM); 16600 ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai); 16601 } 16602 16603 @GuardedBy(anyOf = {"this", "mProcLock"}) 16604 private void updateApplicationInfoLOSP(@NonNull List<String> packagesToUpdate, 16605 boolean updateFrameworkRes, int userId) { 16606 if (updateFrameworkRes) { 16607 ParsingPackageUtils.readConfigUseRoundIcon(null); 16608 } 16609 16610 mProcessList.updateApplicationInfoLOSP(packagesToUpdate, userId, updateFrameworkRes); 16611 16612 if (updateFrameworkRes) { 16613 // Update system server components that need to know about changed overlays. Because the 16614 // overlay is applied in ActivityThread, we need to serialize through its thread too. 16615 final Executor executor = ActivityThread.currentActivityThread().getExecutor(); 16616 final DisplayManagerInternal display = 16617 LocalServices.getService(DisplayManagerInternal.class); 16618 if (display != null) { 16619 executor.execute(display::onOverlayChanged); 16620 } 16621 if (mWindowManager != null) { 16622 executor.execute(mWindowManager::onOverlayChanged); 16623 } 16624 } 16625 } 16626 16627 /** 16628 * Update the binder call heavy hitter watcher per the new configuration 16629 */ 16630 void scheduleUpdateBinderHeavyHitterWatcherConfig() { 16631 // There are two sets of configs: the default watcher and the auto sampler, 16632 // the default one takes precedence. System would kick off auto sampler when there is 16633 // an anomaly (i.e., consecutive ANRs), but it'll be stopped automatically after a while. 16634 mHandler.post(() -> { 16635 final boolean enabled; 16636 final int batchSize; 16637 final float threshold; 16638 final BinderCallHeavyHitterListener listener; 16639 synchronized (mProcLock) { 16640 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 16641 // Default watcher takes precedence, ignore the auto sampler. 16642 mHandler.removeMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG); 16643 // Set the watcher with the default watcher's config 16644 enabled = true; 16645 batchSize = mConstants.BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE; 16646 threshold = mConstants.BINDER_HEAVY_HITTER_WATCHER_THRESHOLD; 16647 listener = (a, b, c, d) -> mHandler.post( 16648 () -> handleBinderHeavyHitters(a, b, c, d)); 16649 } else if (mHandler.hasMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG)) { 16650 // There is an ongoing auto sampler session, update it 16651 enabled = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED; 16652 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE; 16653 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD; 16654 listener = (a, b, c, d) -> mHandler.post( 16655 () -> handleBinderHeavyHitters(a, b, c, d)); 16656 } else { 16657 // Stop it 16658 enabled = false; 16659 batchSize = 0; 16660 threshold = 0.0f; 16661 listener = null; 16662 } 16663 } 16664 Binder.setHeavyHitterWatcherConfig(enabled, batchSize, threshold, listener); 16665 }); 16666 } 16667 16668 /** 16669 * Kick off the watcher to run for given timeout, it could be throttled however. 16670 */ 16671 void scheduleBinderHeavyHitterAutoSampler() { 16672 mHandler.post(() -> { 16673 final int batchSize; 16674 final float threshold; 16675 final long now; 16676 synchronized (mProcLock) { 16677 if (!mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED) { 16678 // It's configured OFF 16679 return; 16680 } 16681 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 16682 // If the default watcher is active already, don't start the auto sampler 16683 return; 16684 } 16685 now = SystemClock.uptimeMillis(); 16686 if (mLastBinderHeavyHitterAutoSamplerStart 16687 + BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS > now) { 16688 // Too frequent, throttle it 16689 return; 16690 } 16691 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE; 16692 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD; 16693 } 16694 // No lock is needed because we are accessing these variables in handle thread only. 16695 mLastBinderHeavyHitterAutoSamplerStart = now; 16696 // Start the watcher with the auto sampler's config. 16697 Binder.setHeavyHitterWatcherConfig(true, batchSize, threshold, 16698 (a, b, c, d) -> mHandler.post(() -> handleBinderHeavyHitters(a, b, c, d))); 16699 // Schedule to stop it after given timeout. 16700 mHandler.sendMessageDelayed(mHandler.obtainMessage( 16701 BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG), 16702 BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS); 16703 }); 16704 } 16705 16706 /** 16707 * Stop the binder heavy hitter auto sampler after given timeout. 16708 */ 16709 private void handleBinderHeavyHitterAutoSamplerTimeOut() { 16710 synchronized (mProcLock) { 16711 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) { 16712 // The default watcher is ON, don't bother to stop it. 16713 return; 16714 } 16715 } 16716 Binder.setHeavyHitterWatcherConfig(false, 0, 0.0f, null); 16717 } 16718 16719 /** 16720 * Handle the heavy hitters 16721 */ 16722 private void handleBinderHeavyHitters(@NonNull final List<HeavyHitterContainer> hitters, 16723 final int totalBinderCalls, final float threshold, final long timeSpan) { 16724 final int size = hitters.size(); 16725 if (size == 0) { 16726 return; 16727 } 16728 // Simply log it for now 16729 final String pfmt = "%.1f%%"; 16730 final BinderTransactionNameResolver resolver = new BinderTransactionNameResolver(); 16731 final StringBuilder sb = new StringBuilder("Excessive incoming binder calls(>") 16732 .append(String.format(pfmt, threshold * 100)) 16733 .append(',').append(totalBinderCalls) 16734 .append(',').append(timeSpan) 16735 .append("ms): "); 16736 for (int i = 0; i < size; i++) { 16737 if (i > 0) { 16738 sb.append(", "); 16739 } 16740 final HeavyHitterContainer container = hitters.get(i); 16741 sb.append('[').append(container.mUid) 16742 .append(',').append(container.mClass.getName()) 16743 .append(',').append(resolver.getMethodName(container.mClass, container.mCode)) 16744 .append(',').append(container.mCode) 16745 .append(',').append(String.format(pfmt, container.mFrequency * 100)) 16746 .append(']'); 16747 } 16748 Slog.w(TAG, sb.toString()); 16749 } 16750 16751 /** 16752 * Attach an agent to the specified process (proces name or PID) 16753 */ 16754 public void attachAgent(String process, String path) { 16755 try { 16756 synchronized (mProcLock) { 16757 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_SYSTEM, 16758 "attachAgent"); 16759 IApplicationThread thread; 16760 if (proc == null || (thread = proc.getThread()) == null) { 16761 throw new IllegalArgumentException("Unknown process: " + process); 16762 } 16763 16764 if (!Build.IS_DEBUGGABLE) { 16765 if ((proc.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 16766 throw new SecurityException("Process not debuggable: " + proc); 16767 } 16768 } 16769 16770 thread.attachAgent(path); 16771 } 16772 } catch (RemoteException e) { 16773 throw new IllegalStateException("Process disappeared"); 16774 } 16775 } 16776 16777 /** 16778 * When power button is very long pressed, call this interface to do some pre-shutdown work 16779 * like persisting database etc. 16780 */ 16781 public void prepareForPossibleShutdown() { 16782 if (mUsageStatsService != null) { 16783 mUsageStatsService.prepareForPossibleShutdown(); 16784 } 16785 } 16786 16787 @VisibleForTesting 16788 public static class Injector { 16789 private NetworkManagementInternal mNmi; 16790 private Context mContext; 16791 16792 public Injector(Context context) { 16793 mContext = context; 16794 } 16795 16796 public Context getContext() { 16797 return mContext; 16798 } 16799 16800 public AppOpsService getAppOpsService(File file, Handler handler) { 16801 return new AppOpsService(file, handler, getContext()); 16802 } 16803 16804 public Handler getUiHandler(ActivityManagerService service) { 16805 return service.new UiHandler(); 16806 } 16807 16808 public boolean isNetworkRestrictedForUid(int uid) { 16809 if (ensureHasNetworkManagementInternal()) { 16810 return mNmi.isNetworkRestrictedForUid(uid); 16811 } 16812 return false; 16813 } 16814 16815 /** 16816 * Return the process list instance 16817 */ 16818 public ProcessList getProcessList(ActivityManagerService service) { 16819 return new ProcessList(); 16820 } 16821 16822 private boolean ensureHasNetworkManagementInternal() { 16823 if (mNmi == null) { 16824 mNmi = LocalServices.getService(NetworkManagementInternal.class); 16825 } 16826 return mNmi != null; 16827 } 16828 } 16829 16830 @Override 16831 public void startDelegateShellPermissionIdentity(int delegateUid, 16832 @Nullable String[] permissions) { 16833 if (UserHandle.getCallingAppId() != Process.SHELL_UID 16834 && UserHandle.getCallingAppId() != Process.ROOT_UID) { 16835 throw new SecurityException("Only the shell can delegate its permissions"); 16836 } 16837 16838 // We allow delegation only to one instrumentation started from the shell 16839 synchronized (mProcLock) { 16840 // If the delegate is already set up for the target UID, nothing to do. 16841 if (mAppOpsService.getAppOpsServiceDelegate() != null) { 16842 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) { 16843 throw new IllegalStateException("Bad shell delegate state"); 16844 } 16845 final ShellDelegate delegate = (ShellDelegate) mAppOpsService 16846 .getAppOpsServiceDelegate(); 16847 if (delegate.getDelegateUid() != delegateUid) { 16848 throw new SecurityException("Shell can delegate permissions only " 16849 + "to one instrumentation at a time"); 16850 } 16851 } 16852 16853 final int instrCount = mActiveInstrumentation.size(); 16854 for (int i = 0; i < instrCount; i++) { 16855 final ActiveInstrumentation instr = mActiveInstrumentation.get(i); 16856 if (instr.mTargetInfo.uid != delegateUid) { 16857 continue; 16858 } 16859 // If instrumentation started from the shell the connection is not null 16860 if (instr.mUiAutomationConnection == null) { 16861 throw new SecurityException("Shell can delegate its permissions" + 16862 " only to an instrumentation started from the shell"); 16863 } 16864 16865 // Hook them up... 16866 final ShellDelegate shellDelegate = new ShellDelegate(delegateUid, 16867 permissions); 16868 mAppOpsService.setAppOpsServiceDelegate(shellDelegate); 16869 final String packageName = instr.mTargetInfo.packageName; 16870 final List<String> permissionNames = permissions != null ? 16871 Arrays.asList(permissions) : null; 16872 getPermissionManagerInternal().startShellPermissionIdentityDelegation( 16873 delegateUid, packageName, permissionNames); 16874 return; 16875 } 16876 } 16877 } 16878 16879 @Override 16880 public void stopDelegateShellPermissionIdentity() { 16881 if (UserHandle.getCallingAppId() != Process.SHELL_UID 16882 && UserHandle.getCallingAppId() != Process.ROOT_UID) { 16883 throw new SecurityException("Only the shell can delegate its permissions"); 16884 } 16885 synchronized (mProcLock) { 16886 mAppOpsService.setAppOpsServiceDelegate(null); 16887 getPermissionManagerInternal().stopShellPermissionIdentityDelegation(); 16888 } 16889 } 16890 16891 @Override 16892 public List<String> getDelegatedShellPermissions() { 16893 if (UserHandle.getCallingAppId() != Process.SHELL_UID 16894 && UserHandle.getCallingAppId() != Process.ROOT_UID) { 16895 throw new SecurityException("Only the shell can get delegated permissions"); 16896 } 16897 synchronized (mProcLock) { 16898 return getPermissionManagerInternal().getDelegatedShellPermissions(); 16899 } 16900 } 16901 16902 private class ShellDelegate implements CheckOpsDelegate { 16903 private final int mTargetUid; 16904 @Nullable 16905 private final String[] mPermissions; 16906 16907 ShellDelegate(int targetUid, @Nullable String[] permissions) { 16908 mTargetUid = targetUid; 16909 mPermissions = permissions; 16910 } 16911 16912 int getDelegateUid() { 16913 return mTargetUid; 16914 } 16915 16916 @Override 16917 public int checkOperation(int code, int uid, String packageName, 16918 String attributionTag, boolean raw, 16919 QuintFunction<Integer, Integer, String, String, Boolean, Integer> superImpl) { 16920 if (uid == mTargetUid && isTargetOp(code)) { 16921 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid), 16922 Process.SHELL_UID); 16923 final long identity = Binder.clearCallingIdentity(); 16924 try { 16925 return superImpl.apply(code, shellUid, "com.android.shell", null, raw); 16926 } finally { 16927 Binder.restoreCallingIdentity(identity); 16928 } 16929 } 16930 return superImpl.apply(code, uid, packageName, attributionTag, raw); 16931 } 16932 16933 @Override 16934 public int checkAudioOperation(int code, int usage, int uid, String packageName, 16935 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) { 16936 if (uid == mTargetUid && isTargetOp(code)) { 16937 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid), 16938 Process.SHELL_UID); 16939 final long identity = Binder.clearCallingIdentity(); 16940 try { 16941 return superImpl.apply(code, usage, shellUid, "com.android.shell"); 16942 } finally { 16943 Binder.restoreCallingIdentity(identity); 16944 } 16945 } 16946 return superImpl.apply(code, usage, uid, packageName); 16947 } 16948 16949 @Override 16950 public SyncNotedAppOp noteOperation(int code, int uid, @Nullable String packageName, 16951 @Nullable String featureId, boolean shouldCollectAsyncNotedOp, 16952 @Nullable String message, boolean shouldCollectMessage, 16953 @NonNull HeptFunction<Integer, Integer, String, String, Boolean, String, Boolean, 16954 SyncNotedAppOp> superImpl) { 16955 if (uid == mTargetUid && isTargetOp(code)) { 16956 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid), 16957 Process.SHELL_UID); 16958 final long identity = Binder.clearCallingIdentity(); 16959 try { 16960 return superImpl.apply(code, shellUid, "com.android.shell", featureId, 16961 shouldCollectAsyncNotedOp, message, shouldCollectMessage); 16962 } finally { 16963 Binder.restoreCallingIdentity(identity); 16964 } 16965 } 16966 return superImpl.apply(code, uid, packageName, featureId, shouldCollectAsyncNotedOp, 16967 message, shouldCollectMessage); 16968 } 16969 16970 @Override 16971 public SyncNotedAppOp noteProxyOperation(int code, 16972 @NonNull AttributionSource attributionSource, boolean shouldCollectAsyncNotedOp, 16973 @Nullable String message, boolean shouldCollectMessage, boolean skiProxyOperation, 16974 @NonNull HexFunction<Integer, AttributionSource, Boolean, String, Boolean, 16975 Boolean, SyncNotedAppOp> superImpl) { 16976 if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) { 16977 final int shellUid = UserHandle.getUid(UserHandle.getUserId( 16978 attributionSource.getUid()), Process.SHELL_UID); 16979 final long identity = Binder.clearCallingIdentity(); 16980 try { 16981 return superImpl.apply(code, new AttributionSource(shellUid, 16982 "com.android.shell", attributionSource.getAttributionTag(), 16983 attributionSource.getToken(), attributionSource.getNext()), 16984 shouldCollectAsyncNotedOp, message, shouldCollectMessage, 16985 skiProxyOperation); 16986 } finally { 16987 Binder.restoreCallingIdentity(identity); 16988 } 16989 } 16990 return superImpl.apply(code, attributionSource, shouldCollectAsyncNotedOp, 16991 message, shouldCollectMessage, skiProxyOperation); 16992 } 16993 16994 @Override 16995 public SyncNotedAppOp startOperation(IBinder token, int code, int uid, 16996 @Nullable String packageName, @Nullable String attributionTag, 16997 boolean startIfModeDefault, boolean shouldCollectAsyncNotedOp, 16998 @Nullable String message, boolean shouldCollectMessage, 16999 @AttributionFlags int attributionFlags, int attributionChainId, 17000 @NonNull UndecFunction<IBinder, Integer, Integer, String, String, Boolean, 17001 Boolean, String, Boolean, Integer, Integer, SyncNotedAppOp> superImpl) { 17002 if (uid == mTargetUid && isTargetOp(code)) { 17003 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid), 17004 Process.SHELL_UID); 17005 final long identity = Binder.clearCallingIdentity(); 17006 try { 17007 return superImpl.apply(token, code, shellUid, "com.android.shell", 17008 attributionTag, startIfModeDefault, shouldCollectAsyncNotedOp, message, 17009 shouldCollectMessage, attributionFlags, attributionChainId); 17010 } finally { 17011 Binder.restoreCallingIdentity(identity); 17012 } 17013 } 17014 return superImpl.apply(token, code, uid, packageName, attributionTag, 17015 startIfModeDefault, shouldCollectAsyncNotedOp, message, shouldCollectMessage, 17016 attributionFlags, attributionChainId); 17017 } 17018 17019 @Override 17020 public SyncNotedAppOp startProxyOperation(int code, 17021 @NonNull AttributionSource attributionSource, boolean startIfModeDefault, 17022 boolean shouldCollectAsyncNotedOp, String message, boolean shouldCollectMessage, 17023 boolean skipProxyOperation, @AttributionFlags int proxyAttributionFlags, 17024 @AttributionFlags int proxiedAttributionFlags, int attributionChainId, 17025 @NonNull DecFunction<Integer, AttributionSource, Boolean, Boolean, String, Boolean, 17026 Boolean, Integer, Integer, Integer, SyncNotedAppOp> superImpl) { 17027 if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) { 17028 final int shellUid = UserHandle.getUid(UserHandle.getUserId( 17029 attributionSource.getUid()), Process.SHELL_UID); 17030 final long identity = Binder.clearCallingIdentity(); 17031 try { 17032 return superImpl.apply(code, new AttributionSource(shellUid, 17033 "com.android.shell", attributionSource.getAttributionTag(), 17034 attributionSource.getToken(), attributionSource.getNext()), 17035 startIfModeDefault, shouldCollectAsyncNotedOp, message, 17036 shouldCollectMessage, skipProxyOperation, proxyAttributionFlags, 17037 proxiedAttributionFlags, attributionChainId); 17038 } finally { 17039 Binder.restoreCallingIdentity(identity); 17040 } 17041 } 17042 return superImpl.apply(code, attributionSource, startIfModeDefault, 17043 shouldCollectAsyncNotedOp, message, shouldCollectMessage, skipProxyOperation, 17044 proxyAttributionFlags, proxiedAttributionFlags, attributionChainId); 17045 } 17046 17047 @Override 17048 public void finishProxyOperation(int code, @NonNull AttributionSource attributionSource, 17049 boolean skipProxyOperation, @NonNull TriFunction<Integer, AttributionSource, 17050 Boolean, Void> superImpl) { 17051 if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) { 17052 final int shellUid = UserHandle.getUid(UserHandle.getUserId( 17053 attributionSource.getUid()), Process.SHELL_UID); 17054 final long identity = Binder.clearCallingIdentity(); 17055 try { 17056 superImpl.apply(code, new AttributionSource(shellUid, 17057 "com.android.shell", attributionSource.getAttributionTag(), 17058 attributionSource.getToken(), attributionSource.getNext()), 17059 skipProxyOperation); 17060 } finally { 17061 Binder.restoreCallingIdentity(identity); 17062 } 17063 } 17064 superImpl.apply(code, attributionSource, skipProxyOperation); 17065 } 17066 17067 private boolean isTargetOp(int code) { 17068 // null permissions means all ops are targeted 17069 if (mPermissions == null) { 17070 return true; 17071 } 17072 // no permission for the op means the op is targeted 17073 final String permission = AppOpsManager.opToPermission(code); 17074 if (permission == null) { 17075 return true; 17076 } 17077 return isTargetPermission(permission); 17078 } 17079 17080 private boolean isTargetPermission(@NonNull String permission) { 17081 // null permissions means all permissions are targeted 17082 return (mPermissions == null || ArrayUtils.contains(mPermissions, permission)); 17083 } 17084 } 17085 17086 /** 17087 * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would 17088 * cause a watchdog kill. 17089 */ 17090 void maybeTriggerWatchdog() { 17091 final String key = "debug.trigger.watchdog"; 17092 if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) { 17093 Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!"); 17094 17095 // Clear the property; otherwise the system would hang again after a watchdog restart. 17096 SystemProperties.set(key, ""); 17097 synchronized (ActivityManagerService.this) { 17098 try { 17099 // Arbitrary long sleep for watchdog to catch. 17100 Thread.sleep(60 * 60 * 1000); 17101 } catch (InterruptedException e) { 17102 } 17103 } 17104 } 17105 } 17106 17107 private boolean isOnOffloadQueue(int flags) { 17108 return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0)); 17109 } 17110 17111 @Override 17112 public ParcelFileDescriptor getLifeMonitor() { 17113 if (!isCallerShell()) { 17114 throw new SecurityException("Only shell can call it"); 17115 } 17116 synchronized (mProcLock) { 17117 try { 17118 if (mLifeMonitorFds == null) { 17119 mLifeMonitorFds = ParcelFileDescriptor.createPipe(); 17120 } 17121 // The returned FD will be closed, but we want to keep our reader open, 17122 // so return a dup instead. 17123 return mLifeMonitorFds[0].dup(); 17124 } catch (IOException e) { 17125 Slog.w(TAG, "Unable to create pipe", e); 17126 return null; 17127 } 17128 } 17129 } 17130 17131 @Override 17132 public void setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken) { 17133 final int callingUid = Binder.getCallingUid(); 17134 final int userId = UserHandle.getCallingUserId(); 17135 if (getPackageManagerInternal().getPackageUid(activity.getPackageName(), 17136 /*flags=*/ 0, userId) != callingUid) { 17137 throw new SecurityException("Calling uid " + callingUid + " cannot set locusId" 17138 + "for package " + activity.getPackageName()); 17139 } 17140 mActivityTaskManager.setLocusId(locusId, appToken); 17141 if (mUsageStatsService != null) { 17142 mUsageStatsService.reportLocusUpdate(activity, userId, locusId, appToken); 17143 } 17144 } 17145 17146 @Override 17147 public boolean isAppFreezerSupported() { 17148 final long token = Binder.clearCallingIdentity(); 17149 17150 try { 17151 return mOomAdjuster.mCachedAppOptimizer.isFreezerSupported(); 17152 } finally { 17153 Binder.restoreCallingIdentity(token); 17154 } 17155 } 17156 17157 /** 17158 * Resets the state of the {@link com.android.server.am.AppErrors} instance. 17159 * This is intended for testing within the CTS only and is protected by 17160 * android.permission.RESET_APP_ERRORS. 17161 */ 17162 @Override 17163 public void resetAppErrors() { 17164 enforceCallingPermission(Manifest.permission.RESET_APP_ERRORS, "resetAppErrors"); 17165 mAppErrors.resetState(); 17166 } 17167 17168 @Override 17169 public boolean enableAppFreezer(boolean enable) { 17170 int callerUid = Binder.getCallingUid(); 17171 17172 // Only system can toggle the freezer state 17173 if (callerUid == SYSTEM_UID || Build.IS_DEBUGGABLE) { 17174 return mOomAdjuster.mCachedAppOptimizer.enableFreezer(enable); 17175 } else { 17176 throw new SecurityException("Caller uid " + callerUid + " cannot set freezer state "); 17177 } 17178 } 17179 17180 /** 17181 * Suppress or reenable the rate limit on foreground service notification deferral. 17182 * @param enable false to suppress rate-limit policy; true to reenable it. 17183 */ 17184 @Override 17185 public boolean enableFgsNotificationRateLimit(boolean enable) { 17186 enforceCallingPermission(permission.WRITE_DEVICE_CONFIG, 17187 "enableFgsNotificationRateLimit"); 17188 synchronized (this) { 17189 return mServices.enableFgsNotificationRateLimitLocked(enable); 17190 } 17191 } 17192 17193 /** 17194 * Holds the AM lock for the specified amount of milliseconds. 17195 * Intended for use by the tests that need to imitate lock contention. 17196 * The token should be obtained by 17197 * {@link android.content.pm.PackageManager#getHoldLockToken()}. 17198 */ 17199 @Override 17200 public void holdLock(IBinder token, int durationMs) { 17201 getTestUtilityServiceLocked().verifyHoldLockToken(token); 17202 17203 synchronized (this) { 17204 SystemClock.sleep(durationMs); 17205 } 17206 } 17207 17208 static void traceBegin(long traceTag, String methodName, String subInfo) { 17209 if (Trace.isTagEnabled(traceTag)) { 17210 Trace.traceBegin(traceTag, methodName + subInfo); 17211 } 17212 } 17213 } 17214