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.INTERACT_ACROSS_USERS; 22 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL; 23 import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW; 24 import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS; 25 import static android.Manifest.permission.READ_FRAME_BUFFER; 26 import static android.Manifest.permission.START_TASKS_FROM_RECENTS; 27 import static android.app.ActivityManager.DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT; 28 import static android.app.ActivityManager.RESIZE_MODE_PRESERVE_WINDOW; 29 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID; 30 import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID; 31 import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID; 32 import static android.app.ActivityManager.StackId.INVALID_STACK_ID; 33 import static android.app.ActivityManager.StackId.PINNED_STACK_ID; 34 import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS; 35 import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT; 36 import static android.content.pm.PackageManager.FEATURE_LEANBACK_ONLY; 37 import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE; 38 import static android.content.pm.PackageManager.GET_PROVIDERS; 39 import static android.content.pm.PackageManager.MATCH_ANY_USER; 40 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 41 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 42 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 43 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 44 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 45 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 46 import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION; 47 import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode; 48 import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground; 49 import static android.os.Build.VERSION_CODES.N; 50 import static android.os.Process.BLUETOOTH_UID; 51 import static android.os.Process.FIRST_APPLICATION_UID; 52 import static android.os.Process.FIRST_ISOLATED_UID; 53 import static android.os.Process.LAST_ISOLATED_UID; 54 import static android.os.Process.NFC_UID; 55 import static android.os.Process.PHONE_UID; 56 import static android.os.Process.PROC_CHAR; 57 import static android.os.Process.PROC_OUT_LONG; 58 import static android.os.Process.PROC_PARENS; 59 import static android.os.Process.PROC_SPACE_TERM; 60 import static android.os.Process.ProcessStartResult; 61 import static android.os.Process.ROOT_UID; 62 import static android.os.Process.SCHED_FIFO; 63 import static android.os.Process.SCHED_OTHER; 64 import static android.os.Process.SCHED_RESET_ON_FORK; 65 import static android.os.Process.SHELL_UID; 66 import static android.os.Process.SIGNAL_QUIT; 67 import static android.os.Process.SIGNAL_USR1; 68 import static android.os.Process.SYSTEM_UID; 69 import static android.os.Process.THREAD_GROUP_BG_NONINTERACTIVE; 70 import static android.os.Process.THREAD_GROUP_DEFAULT; 71 import static android.os.Process.THREAD_GROUP_TOP_APP; 72 import static android.os.Process.THREAD_PRIORITY_BACKGROUND; 73 import static android.os.Process.THREAD_PRIORITY_FOREGROUND; 74 import static android.os.Process.getFreeMemory; 75 import static android.os.Process.getTotalMemory; 76 import static android.os.Process.isThreadInProcess; 77 import static android.os.Process.killProcess; 78 import static android.os.Process.killProcessQuiet; 79 import static android.os.Process.myPid; 80 import static android.os.Process.myUid; 81 import static android.os.Process.readProcFile; 82 import static android.os.Process.removeAllProcessGroups; 83 import static android.os.Process.sendSignal; 84 import static android.os.Process.setProcessGroup; 85 import static android.os.Process.setThreadPriority; 86 import static android.os.Process.setThreadScheduler; 87 import static android.os.Process.startWebView; 88 import static android.os.Process.zygoteProcess; 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.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT; 92 import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES; 93 import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL; 94 import static android.provider.Settings.Global.NETWORK_ACCESS_TIMEOUT_MS; 95 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER; 96 import static android.provider.Settings.System.FONT_SCALE; 97 import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION; 98 import static android.view.Display.DEFAULT_DISPLAY; 99 import static android.view.Display.INVALID_DISPLAY; 100 import static com.android.internal.util.XmlUtils.readBooleanAttribute; 101 import static com.android.internal.util.XmlUtils.readIntAttribute; 102 import static com.android.internal.util.XmlUtils.readLongAttribute; 103 import static com.android.internal.util.XmlUtils.writeBooleanAttribute; 104 import static com.android.internal.util.XmlUtils.writeIntAttribute; 105 import static com.android.internal.util.XmlUtils.writeLongAttribute; 106 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL; 107 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR; 108 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK; 109 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP; 110 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; 111 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND; 112 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; 113 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CLEANUP; 114 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION; 115 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS; 116 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IMMERSIVE; 117 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK; 118 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LRU; 119 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 120 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK; 121 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ; 122 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ_REASON; 123 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW; 124 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER; 125 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES; 126 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESS_OBSERVERS; 127 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROVIDER; 128 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PSS; 129 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS; 130 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE; 131 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK; 132 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH; 133 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS; 134 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_UID_OBSERVERS; 135 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_URI_PERMISSION; 136 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_USAGE_STATS; 137 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY; 138 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBLE_BEHIND; 139 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_WHITELISTS; 140 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP; 141 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; 142 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP; 143 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONFIGURATION; 144 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS; 145 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IMMERSIVE; 146 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKSCREEN; 147 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK; 148 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU; 149 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; 150 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK; 151 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ; 152 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER; 153 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES; 154 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESS_OBSERVERS; 155 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROVIDER; 156 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PSS; 157 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS; 158 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE; 159 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK; 160 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH; 161 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS; 162 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_URI_PERMISSION; 163 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBILITY; 164 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBLE_BEHIND; 165 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 166 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 167 import static com.android.server.am.ActivityStackSupervisor.ActivityContainer.FORCE_NEW_TASK_FLAGS; 168 import static com.android.server.am.ActivityStackSupervisor.CREATE_IF_NEEDED; 169 import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME; 170 import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY; 171 import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS; 172 import static com.android.server.am.ActivityStackSupervisor.ON_TOP; 173 import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS; 174 import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS; 175 import static com.android.server.am.TaskRecord.INVALID_TASK_ID; 176 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK; 177 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV; 178 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE; 179 import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT; 180 import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE; 181 import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_OPEN; 182 import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_RELAUNCH; 183 import static com.android.server.wm.AppTransition.TRANSIT_NONE; 184 import static com.android.server.wm.AppTransition.TRANSIT_TASK_IN_PLACE; 185 import static com.android.server.wm.AppTransition.TRANSIT_TASK_OPEN; 186 import static com.android.server.wm.AppTransition.TRANSIT_TASK_TO_FRONT; 187 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 188 import static org.xmlpull.v1.XmlPullParser.START_TAG; 189 190 import android.Manifest; 191 import android.Manifest.permission; 192 import android.annotation.NonNull; 193 import android.annotation.Nullable; 194 import android.annotation.UserIdInt; 195 import android.app.Activity; 196 import android.app.ActivityManager; 197 import android.app.ActivityManager.RunningTaskInfo; 198 import android.app.ActivityManager.StackId; 199 import android.app.ActivityManager.StackInfo; 200 import android.app.ActivityManager.TaskSnapshot; 201 import android.app.ActivityManager.TaskThumbnailInfo; 202 import android.app.ActivityManagerInternal; 203 import android.app.ActivityManagerInternal.SleepToken; 204 import android.app.ActivityOptions; 205 import android.app.ActivityThread; 206 import android.app.AlertDialog; 207 import android.app.AppGlobals; 208 import android.app.AppOpsManager; 209 import android.app.ApplicationErrorReport; 210 import android.app.ApplicationThreadConstants; 211 import android.app.BroadcastOptions; 212 import android.app.ContentProviderHolder; 213 import android.app.Dialog; 214 import android.app.IActivityContainer; 215 import android.app.IActivityContainerCallback; 216 import android.app.IActivityController; 217 import android.app.IActivityManager; 218 import android.app.IAppTask; 219 import android.app.IApplicationThread; 220 import android.app.IInstrumentationWatcher; 221 import android.app.INotificationManager; 222 import android.app.IProcessObserver; 223 import android.app.IServiceConnection; 224 import android.app.IStopUserCallback; 225 import android.app.ITaskStackListener; 226 import android.app.IUiAutomationConnection; 227 import android.app.IUidObserver; 228 import android.app.IUserSwitchObserver; 229 import android.app.Instrumentation; 230 import android.app.Notification; 231 import android.app.NotificationManager; 232 import android.app.PendingIntent; 233 import android.app.PictureInPictureParams; 234 import android.app.ProfilerInfo; 235 import android.app.RemoteAction; 236 import android.app.WaitResult; 237 import android.app.admin.DevicePolicyManager; 238 import android.app.assist.AssistContent; 239 import android.app.assist.AssistStructure; 240 import android.app.backup.IBackupManager; 241 import android.app.usage.UsageEvents; 242 import android.app.usage.UsageStatsManagerInternal; 243 import android.appwidget.AppWidgetManager; 244 import android.content.ActivityNotFoundException; 245 import android.content.BroadcastReceiver; 246 import android.content.ClipData; 247 import android.content.ComponentCallbacks2; 248 import android.content.ComponentName; 249 import android.content.ContentProvider; 250 import android.content.ContentResolver; 251 import android.content.Context; 252 import android.content.DialogInterface; 253 import android.content.IContentProvider; 254 import android.content.IIntentReceiver; 255 import android.content.IIntentSender; 256 import android.content.Intent; 257 import android.content.IntentFilter; 258 import android.content.IntentSender; 259 import android.content.pm.ActivityInfo; 260 import android.content.pm.ApplicationInfo; 261 import android.content.pm.ConfigurationInfo; 262 import android.content.pm.IPackageDataObserver; 263 import android.content.pm.IPackageManager; 264 import android.content.pm.InstrumentationInfo; 265 import android.content.pm.PackageInfo; 266 import android.content.pm.PackageManager; 267 import android.content.pm.PackageManager.NameNotFoundException; 268 import android.content.pm.PackageManagerInternal; 269 import android.content.pm.ParceledListSlice; 270 import android.content.pm.PathPermission; 271 import android.content.pm.PermissionInfo; 272 import android.content.pm.ProviderInfo; 273 import android.content.pm.ResolveInfo; 274 import android.content.pm.SELinuxUtil; 275 import android.content.pm.ServiceInfo; 276 import android.content.pm.UserInfo; 277 import android.content.res.CompatibilityInfo; 278 import android.content.res.Configuration; 279 import android.content.res.Resources; 280 import android.database.ContentObserver; 281 import android.graphics.Bitmap; 282 import android.graphics.Point; 283 import android.graphics.Rect; 284 import android.location.LocationManager; 285 import android.media.audiofx.AudioEffect; 286 import android.metrics.LogMaker; 287 import android.net.Proxy; 288 import android.net.ProxyInfo; 289 import android.net.Uri; 290 import android.os.BatteryStats; 291 import android.os.Binder; 292 import android.os.Build; 293 import android.os.Bundle; 294 import android.os.Debug; 295 import android.os.DropBoxManager; 296 import android.os.Environment; 297 import android.os.FactoryTest; 298 import android.os.FileObserver; 299 import android.os.FileUtils; 300 import android.os.Handler; 301 import android.os.IBinder; 302 import android.os.IDeviceIdentifiersPolicyService; 303 import android.os.IPermissionController; 304 import android.os.IProcessInfoService; 305 import android.os.IProgressListener; 306 import android.os.LocaleList; 307 import android.os.Looper; 308 import android.os.Message; 309 import android.os.Parcel; 310 import android.os.ParcelFileDescriptor; 311 import android.os.PersistableBundle; 312 import android.os.PowerManager; 313 import android.os.PowerManagerInternal; 314 import android.os.Process; 315 import android.os.RemoteCallbackList; 316 import android.os.RemoteException; 317 import android.os.ResultReceiver; 318 import android.os.ServiceManager; 319 import android.os.ShellCallback; 320 import android.os.StrictMode; 321 import android.os.SystemClock; 322 import android.os.SystemProperties; 323 import android.os.Trace; 324 import android.os.TransactionTooLargeException; 325 import android.os.UpdateLock; 326 import android.os.UserHandle; 327 import android.os.UserManager; 328 import android.os.WorkSource; 329 import android.os.storage.IStorageManager; 330 import android.os.storage.StorageManager; 331 import android.os.storage.StorageManagerInternal; 332 import android.provider.Downloads; 333 import android.provider.Settings; 334 import android.service.voice.IVoiceInteractionSession; 335 import android.service.voice.VoiceInteractionManagerInternal; 336 import android.service.voice.VoiceInteractionSession; 337 import android.telecom.TelecomManager; 338 import android.text.TextUtils; 339 import android.text.format.DateUtils; 340 import android.text.format.Time; 341 import android.text.style.SuggestionSpan; 342 import android.util.ArrayMap; 343 import android.util.ArraySet; 344 import android.util.AtomicFile; 345 import android.util.BootTimingsTraceLog; 346 import android.util.DebugUtils; 347 import android.util.DisplayMetrics; 348 import android.util.EventLog; 349 import android.util.Log; 350 import android.util.Pair; 351 import android.util.PrintWriterPrinter; 352 import android.util.Slog; 353 import android.util.SparseArray; 354 import android.util.SparseIntArray; 355 import android.util.TimeUtils; 356 import android.util.Xml; 357 import android.view.Gravity; 358 import android.view.LayoutInflater; 359 import android.view.View; 360 import android.view.WindowManager; 361 362 import com.android.server.job.JobSchedulerInternal; 363 import com.google.android.collect.Lists; 364 import com.google.android.collect.Maps; 365 366 import com.android.internal.R; 367 import com.android.internal.annotations.GuardedBy; 368 import com.android.internal.annotations.VisibleForTesting; 369 import com.android.internal.app.AssistUtils; 370 import com.android.internal.app.DumpHeapActivity; 371 import com.android.internal.app.IAppOpsCallback; 372 import com.android.internal.app.IAppOpsService; 373 import com.android.internal.app.IVoiceInteractor; 374 import com.android.internal.app.ProcessMap; 375 import com.android.internal.app.SystemUserHomeActivity; 376 import com.android.internal.app.procstats.ProcessStats; 377 import com.android.internal.logging.MetricsLogger; 378 import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 379 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 380 import com.android.internal.notification.SystemNotificationChannels; 381 import com.android.internal.os.BackgroundThread; 382 import com.android.internal.os.BatteryStatsImpl; 383 import com.android.internal.os.IResultReceiver; 384 import com.android.internal.os.ProcessCpuTracker; 385 import com.android.internal.os.TransferPipe; 386 import com.android.internal.os.Zygote; 387 import com.android.internal.policy.IKeyguardDismissCallback; 388 import com.android.internal.telephony.TelephonyIntents; 389 import com.android.internal.util.ArrayUtils; 390 import com.android.internal.util.DumpUtils; 391 import com.android.internal.util.FastPrintWriter; 392 import com.android.internal.util.FastXmlSerializer; 393 import com.android.internal.util.MemInfoReader; 394 import com.android.internal.util.Preconditions; 395 import com.android.server.AppOpsService; 396 import com.android.server.AttributeCache; 397 import com.android.server.DeviceIdleController; 398 import com.android.server.IntentResolver; 399 import com.android.server.LocalServices; 400 import com.android.server.LockGuard; 401 import com.android.server.NetworkManagementInternal; 402 import com.android.server.RescueParty; 403 import com.android.server.ServiceThread; 404 import com.android.server.SystemConfig; 405 import com.android.server.SystemService; 406 import com.android.server.SystemServiceManager; 407 import com.android.server.ThreadPriorityBooster; 408 import com.android.server.Watchdog; 409 import com.android.server.am.ActivityStack.ActivityState; 410 import com.android.server.firewall.IntentFirewall; 411 import com.android.server.pm.Installer; 412 import com.android.server.pm.Installer.InstallerException; 413 import com.android.server.statusbar.StatusBarManagerInternal; 414 import com.android.server.vr.VrManagerInternal; 415 import com.android.server.wm.PinnedStackWindowController; 416 import com.android.server.wm.WindowManagerService; 417 418 import org.xmlpull.v1.XmlPullParser; 419 import org.xmlpull.v1.XmlPullParserException; 420 import org.xmlpull.v1.XmlSerializer; 421 422 import java.io.File; 423 import java.io.FileDescriptor; 424 import java.io.FileInputStream; 425 import java.io.FileNotFoundException; 426 import java.io.FileOutputStream; 427 import java.io.IOException; 428 import java.io.InputStreamReader; 429 import java.io.PrintWriter; 430 import java.io.StringWriter; 431 import java.io.UnsupportedEncodingException; 432 import java.lang.ref.WeakReference; 433 import java.nio.charset.StandardCharsets; 434 import java.text.DateFormat; 435 import java.util.ArrayList; 436 import java.util.Arrays; 437 import java.util.Collections; 438 import java.util.Comparator; 439 import java.util.Date; 440 import java.util.HashMap; 441 import java.util.HashSet; 442 import java.util.Iterator; 443 import java.util.List; 444 import java.util.Locale; 445 import java.util.Map; 446 import java.util.Objects; 447 import java.util.Set; 448 import java.util.concurrent.CountDownLatch; 449 import java.util.concurrent.atomic.AtomicBoolean; 450 import java.util.concurrent.atomic.AtomicLong; 451 452 import dalvik.system.VMRuntime; 453 import libcore.io.IoUtils; 454 import libcore.util.EmptyArray; 455 456 public class ActivityManagerService extends IActivityManager.Stub 457 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 458 459 /** 460 * Priority we boost main thread and RT of top app to. 461 */ 462 public static final int TOP_APP_PRIORITY_BOOST = -10; 463 464 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM; 465 private static final String TAG_BACKUP = TAG + POSTFIX_BACKUP; 466 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 467 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 468 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION; 469 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS; 470 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE; 471 private static final String TAG_LOCKSCREEN = TAG + POSTFIX_LOCKSCREEN; 472 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; 473 private static final String TAG_LRU = TAG + POSTFIX_LRU; 474 private static final String TAG_MU = TAG + POSTFIX_MU; 475 private static final String TAG_NETWORK = TAG + POSTFIX_NETWORK; 476 private static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ; 477 private static final String TAG_POWER = TAG + POSTFIX_POWER; 478 private static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS; 479 private static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES; 480 private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER; 481 private static final String TAG_PSS = TAG + POSTFIX_PSS; 482 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS; 483 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 484 private static final String TAG_STACK = TAG + POSTFIX_STACK; 485 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 486 private static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS; 487 private static final String TAG_URI_PERMISSION = TAG + POSTFIX_URI_PERMISSION; 488 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY; 489 private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND; 490 491 // Mock "pretend we're idle now" broadcast action to the job scheduler; declared 492 // here so that while the job scheduler can depend on AMS, the other way around 493 // need not be the case. 494 public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE"; 495 496 /** Control over CPU and battery monitoring */ 497 // write battery stats every 30 minutes. 498 static final long BATTERY_STATS_TIME = 30 * 60 * 1000; 499 static final boolean MONITOR_CPU_USAGE = true; 500 // don't sample cpu less than every 5 seconds. 501 static final long MONITOR_CPU_MIN_TIME = 5 * 1000; 502 // wait possibly forever for next cpu sample. 503 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; 504 static final boolean MONITOR_THREAD_CPU_USAGE = false; 505 506 // The flags that are set for all calls we make to the package manager. 507 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 508 509 static final String SYSTEM_DEBUGGABLE = "ro.debuggable"; 510 511 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE); 512 513 // Amount of time after a call to stopAppSwitches() during which we will 514 // prevent further untrusted switches from happening. 515 static final long APP_SWITCH_DELAY_TIME = 5*1000; 516 517 // How long we wait for a launched process to attach to the activity manager 518 // before we decide it's never going to come up for real. 519 static final int PROC_START_TIMEOUT = 10*1000; 520 // How long we wait for an attached process to publish its content providers 521 // before we decide it must be hung. 522 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000; 523 524 // How long we wait for a launched process to attach to the activity manager 525 // before we decide it's never going to come up for real, when the process was 526 // started with a wrapper for instrumentation (such as Valgrind) because it 527 // could take much longer than usual. 528 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 529 530 // How long we allow a receiver to run before giving up on it. 531 static final int BROADCAST_FG_TIMEOUT = 10*1000; 532 static final int BROADCAST_BG_TIMEOUT = 60*1000; 533 534 // How long we wait until we timeout on key dispatching. 535 static final int KEY_DISPATCHING_TIMEOUT = 5*1000; 536 537 // How long we wait until we timeout on key dispatching during instrumentation. 538 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000; 539 540 // How long to wait in getAssistContextExtras for the activity and foreground services 541 // to respond with the result. 542 static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500; 543 544 // How long top wait when going through the modern assist (which doesn't need to block 545 // on getting this result before starting to launch its UI). 546 static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000; 547 548 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result. 549 static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000; 550 551 // Maximum number of persisted Uri grants a package is allowed 552 static final int MAX_PERSISTED_URI_GRANTS = 128; 553 554 static final int MY_PID = myPid(); 555 556 static final String[] EMPTY_STRING_ARRAY = new String[0]; 557 558 // How many bytes to write into the dropbox log before truncating 559 static final int DROPBOX_MAX_SIZE = 192 * 1024; 560 // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count 561 // as one line, but close enough for now. 562 static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100; 563 564 // Access modes for handleIncomingUser. 565 static final int ALLOW_NON_FULL = 0; 566 static final int ALLOW_NON_FULL_IN_PROFILE = 1; 567 static final int ALLOW_FULL_ONLY = 2; 568 569 // Necessary ApplicationInfo flags to mark an app as persistent 570 private static final int PERSISTENT_MASK = 571 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT; 572 573 // Intent sent when remote bugreport collection has been completed 574 private static final String INTENT_REMOTE_BUGREPORT_FINISHED = 575 "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED"; 576 577 // Used to indicate that an app transition should be animated. 578 static final boolean ANIMATE = true; 579 580 // Determines whether to take full screen screenshots 581 static final boolean TAKE_FULLSCREEN_SCREENSHOTS = true; 582 583 /** 584 * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}. 585 */ 586 private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec 587 588 /** 589 * State indicating that there is no need for any blocking for network. 590 */ 591 @VisibleForTesting 592 static final int NETWORK_STATE_NO_CHANGE = 0; 593 594 /** 595 * State indicating that the main thread needs to be informed about the network wait. 596 */ 597 @VisibleForTesting 598 static final int NETWORK_STATE_BLOCK = 1; 599 600 /** 601 * State indicating that any threads waiting for network state to get updated can be unblocked. 602 */ 603 @VisibleForTesting 604 static final int NETWORK_STATE_UNBLOCK = 2; 605 606 // Max character limit for a notification title. If the notification title is larger than this 607 // the notification will not be legible to the user. 608 private static final int MAX_BUGREPORT_TITLE_SIZE = 50; 609 610 /** All system services */ 611 SystemServiceManager mSystemServiceManager; 612 AssistUtils mAssistUtils; 613 614 private Installer mInstaller; 615 616 /** Run all ActivityStacks through this */ 617 final ActivityStackSupervisor mStackSupervisor; 618 private final KeyguardController mKeyguardController; 619 620 final ActivityStarter mActivityStarter; 621 622 final TaskChangeNotificationController mTaskChangeNotificationController; 623 624 final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter(); 625 626 final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>(); 627 628 public final IntentFirewall mIntentFirewall; 629 630 // Whether we should show our dialogs (ANR, crash, etc) or just perform their 631 // default action automatically. Important for devices without direct input 632 // devices. 633 private boolean mShowDialogs = true; 634 635 private final VrController mVrController; 636 637 // VR Vr2d Display Id. 638 int mVr2dDisplayId = INVALID_DISPLAY; 639 640 // Whether we should use SCHED_FIFO for UI and RenderThreads. 641 private boolean mUseFifoUiScheduling = false; 642 643 BroadcastQueue mFgBroadcastQueue; 644 BroadcastQueue mBgBroadcastQueue; 645 // Convenient for easy iteration over the queues. Foreground is first 646 // so that dispatch of foreground broadcasts gets precedence. 647 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2]; 648 649 BroadcastStats mLastBroadcastStats; 650 BroadcastStats mCurBroadcastStats; 651 652 BroadcastQueue broadcastQueueForIntent(Intent intent) { 653 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 654 if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST, 655 "Broadcast intent " + intent + " on " 656 + (isFg ? "foreground" : "background") + " queue"); 657 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 658 } 659 660 /** 661 * The last resumed activity. This is identical to the current resumed activity most 662 * of the time but could be different when we're pausing one activity before we resume 663 * another activity. 664 */ 665 private ActivityRecord mLastResumedActivity; 666 667 /** 668 * If non-null, we are tracking the time the user spends in the currently focused app. 669 */ 670 private AppTimeTracker mCurAppTimeTracker; 671 672 /** 673 * List of intents that were used to start the most recent tasks. 674 */ 675 final RecentTasks mRecentTasks; 676 677 /** 678 * For addAppTask: cached of the last activity component that was added. 679 */ 680 ComponentName mLastAddedTaskComponent; 681 682 /** 683 * For addAppTask: cached of the last activity uid that was added. 684 */ 685 int mLastAddedTaskUid; 686 687 /** 688 * For addAppTask: cached of the last ActivityInfo that was added. 689 */ 690 ActivityInfo mLastAddedTaskActivity; 691 692 /** 693 * List of packages whitelisted by DevicePolicyManager for locktask. Indexed by userId. 694 */ 695 SparseArray<String[]> mLockTaskPackages = new SparseArray<>(); 696 697 /** 698 * The package name of the DeviceOwner. This package is not permitted to have its data cleared. 699 */ 700 String mDeviceOwnerName; 701 702 final UserController mUserController; 703 704 final AppErrors mAppErrors; 705 706 /** 707 * Dump of the activity state at the time of the last ANR. Cleared after 708 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS} 709 */ 710 String mLastANRState; 711 712 /** 713 * Indicates the maximum time spent waiting for the network rules to get updated. 714 */ 715 @VisibleForTesting 716 long mWaitForNetworkTimeoutMs; 717 718 public boolean canShowErrorDialogs() { 719 return mShowDialogs && !mSleeping && !mShuttingDown 720 && !mKeyguardController.isKeyguardShowing(); 721 } 722 723 private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster( 724 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY); 725 726 static void boostPriorityForLockedSection() { 727 sThreadPriorityBooster.boost(); 728 } 729 730 static void resetPriorityAfterLockedSection() { 731 sThreadPriorityBooster.reset(); 732 } 733 734 public class PendingAssistExtras extends Binder implements Runnable { 735 public final ActivityRecord activity; 736 public boolean isHome; 737 public final Bundle extras; 738 public final Intent intent; 739 public final String hint; 740 public final IResultReceiver receiver; 741 public final int userHandle; 742 public boolean haveResult = false; 743 public Bundle result = null; 744 public AssistStructure structure = null; 745 public AssistContent content = null; 746 public Bundle receiverExtras; 747 748 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent, 749 String _hint, IResultReceiver _receiver, Bundle _receiverExtras, int _userHandle) { 750 activity = _activity; 751 extras = _extras; 752 intent = _intent; 753 hint = _hint; 754 receiver = _receiver; 755 receiverExtras = _receiverExtras; 756 userHandle = _userHandle; 757 } 758 759 @Override 760 public void run() { 761 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity); 762 synchronized (this) { 763 haveResult = true; 764 notifyAll(); 765 } 766 pendingAssistExtrasTimedOut(this); 767 } 768 } 769 770 final ArrayList<PendingAssistExtras> mPendingAssistExtras 771 = new ArrayList<PendingAssistExtras>(); 772 773 /** 774 * Process management. 775 */ 776 final ProcessList mProcessList = new ProcessList(); 777 778 /** 779 * All of the applications we currently have running organized by name. 780 * The keys are strings of the application package name (as 781 * returned by the package manager), and the keys are ApplicationRecord 782 * objects. 783 */ 784 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>(); 785 786 /** 787 * Tracking long-term execution of processes to look for abuse and other 788 * bad app behavior. 789 */ 790 final ProcessStatsService mProcessStats; 791 792 /** 793 * The currently running isolated processes. 794 */ 795 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>(); 796 797 /** 798 * Counter for assigning isolated process uids, to avoid frequently reusing the 799 * same ones. 800 */ 801 int mNextIsolatedProcessUid = 0; 802 803 /** 804 * The currently running heavy-weight process, if any. 805 */ 806 ProcessRecord mHeavyWeightProcess = null; 807 808 /** 809 * Non-persistent appId whitelist for background restrictions 810 */ 811 int[] mBackgroundAppIdWhitelist = new int[] { 812 BLUETOOTH_UID 813 }; 814 815 /** 816 * Broadcast actions that will always be deliverable to unlaunched/background apps 817 */ 818 ArraySet<String> mBackgroundLaunchBroadcasts; 819 820 /** 821 * All of the processes we currently have running organized by pid. 822 * The keys are the pid running the application. 823 * 824 * <p>NOTE: This object is protected by its own lock, NOT the global 825 * activity manager lock! 826 */ 827 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>(); 828 829 /** 830 * All of the processes that have been forced to be important. The key 831 * is the pid of the caller who requested it (we hold a death 832 * link on it). 833 */ 834 abstract class ImportanceToken implements IBinder.DeathRecipient { 835 final int pid; 836 final IBinder token; 837 final String reason; 838 839 ImportanceToken(int _pid, IBinder _token, String _reason) { 840 pid = _pid; 841 token = _token; 842 reason = _reason; 843 } 844 845 @Override 846 public String toString() { 847 return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this)) 848 + " " + reason + " " + pid + " " + token + " }"; 849 } 850 } 851 final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>(); 852 853 /** 854 * List of records for processes that someone had tried to start before the 855 * system was ready. We don't start them at that point, but ensure they 856 * are started by the time booting is complete. 857 */ 858 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 859 860 /** 861 * List of persistent applications that are in the process 862 * of being started. 863 */ 864 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 865 866 /** 867 * Processes that are being forcibly torn down. 868 */ 869 final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>(); 870 871 /** 872 * List of running applications, sorted by recent usage. 873 * The first entry in the list is the least recently used. 874 */ 875 final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>(); 876 877 /** 878 * Where in mLruProcesses that the processes hosting activities start. 879 */ 880 int mLruProcessActivityStart = 0; 881 882 /** 883 * Where in mLruProcesses that the processes hosting services start. 884 * This is after (lower index) than mLruProcessesActivityStart. 885 */ 886 int mLruProcessServiceStart = 0; 887 888 /** 889 * List of processes that should gc as soon as things are idle. 890 */ 891 final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>(); 892 893 /** 894 * Processes we want to collect PSS data from. 895 */ 896 final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>(); 897 898 private boolean mBinderTransactionTrackingEnabled = false; 899 900 /** 901 * Last time we requested PSS data of all processes. 902 */ 903 long mLastFullPssTime = SystemClock.uptimeMillis(); 904 905 /** 906 * If set, the next time we collect PSS data we should do a full collection 907 * with data from native processes and the kernel. 908 */ 909 boolean mFullPssPending = false; 910 911 /** 912 * This is the process holding what we currently consider to be 913 * the "home" activity. 914 */ 915 ProcessRecord mHomeProcess; 916 917 /** 918 * This is the process holding the activity the user last visited that 919 * is in a different process from the one they are currently in. 920 */ 921 ProcessRecord mPreviousProcess; 922 923 /** 924 * The time at which the previous process was last visible. 925 */ 926 long mPreviousProcessVisibleTime; 927 928 /** 929 * Track all uids that have actively running processes. 930 */ 931 final SparseArray<UidRecord> mActiveUids = new SparseArray<>(); 932 933 /** 934 * This is for verifying the UID report flow. 935 */ 936 static final boolean VALIDATE_UID_STATES = true; 937 final SparseArray<UidRecord> mValidateUids = new SparseArray<>(); 938 939 /** 940 * Packages that the user has asked to have run in screen size 941 * compatibility mode instead of filling the screen. 942 */ 943 final CompatModePackages mCompatModePackages; 944 945 /** 946 * Set of IntentSenderRecord objects that are currently active. 947 */ 948 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords 949 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>(); 950 951 /** 952 * Fingerprints (hashCode()) of stack traces that we've 953 * already logged DropBox entries for. Guarded by itself. If 954 * something (rogue user app) forces this over 955 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 956 */ 957 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 958 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 959 960 /** 961 * Strict Mode background batched logging state. 962 * 963 * The string buffer is guarded by itself, and its lock is also 964 * used to determine if another batched write is already 965 * in-flight. 966 */ 967 private final StringBuilder mStrictModeBuffer = new StringBuilder(); 968 969 /** 970 * Keeps track of all IIntentReceivers that have been registered for broadcasts. 971 * Hash keys are the receiver IBinder, hash value is a ReceiverList. 972 */ 973 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>(); 974 975 /** 976 * Resolver for broadcast intents to registered receivers. 977 * Holds BroadcastFilter (subclass of IntentFilter). 978 */ 979 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 980 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 981 @Override 982 protected boolean allowFilterResult( 983 BroadcastFilter filter, List<BroadcastFilter> dest) { 984 IBinder target = filter.receiverList.receiver.asBinder(); 985 for (int i = dest.size() - 1; i >= 0; i--) { 986 if (dest.get(i).receiverList.receiver.asBinder() == target) { 987 return false; 988 } 989 } 990 return true; 991 } 992 993 @Override 994 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 995 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 996 || userId == filter.owningUserId) { 997 return super.newResult(filter, match, userId); 998 } 999 return null; 1000 } 1001 1002 @Override 1003 protected BroadcastFilter[] newArray(int size) { 1004 return new BroadcastFilter[size]; 1005 } 1006 1007 @Override 1008 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 1009 return packageName.equals(filter.packageName); 1010 } 1011 }; 1012 1013 /** 1014 * State of all active sticky broadcasts per user. Keys are the action of the 1015 * sticky Intent, values are an ArrayList of all broadcasted intents with 1016 * that action (which should usually be one). The SparseArray is keyed 1017 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 1018 * for stickies that are sent to all users. 1019 */ 1020 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts = 1021 new SparseArray<ArrayMap<String, ArrayList<Intent>>>(); 1022 1023 final ActiveServices mServices; 1024 1025 final static class Association { 1026 final int mSourceUid; 1027 final String mSourceProcess; 1028 final int mTargetUid; 1029 final ComponentName mTargetComponent; 1030 final String mTargetProcess; 1031 1032 int mCount; 1033 long mTime; 1034 1035 int mNesting; 1036 long mStartTime; 1037 1038 // states of the source process when the bind occurred. 1039 int mLastState = ActivityManager.MAX_PROCESS_STATE + 1; 1040 long mLastStateUptime; 1041 long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE 1042 - ActivityManager.MIN_PROCESS_STATE+1]; 1043 1044 Association(int sourceUid, String sourceProcess, int targetUid, 1045 ComponentName targetComponent, String targetProcess) { 1046 mSourceUid = sourceUid; 1047 mSourceProcess = sourceProcess; 1048 mTargetUid = targetUid; 1049 mTargetComponent = targetComponent; 1050 mTargetProcess = targetProcess; 1051 } 1052 } 1053 1054 /** 1055 * When service association tracking is enabled, this is all of the associations we 1056 * have seen. Mapping is target uid -> target component -> source uid -> source process name 1057 * -> association data. 1058 */ 1059 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>> 1060 mAssociations = new SparseArray<>(); 1061 boolean mTrackingAssociations; 1062 1063 /** 1064 * Backup/restore process management 1065 */ 1066 String mBackupAppName = null; 1067 BackupRecord mBackupTarget = null; 1068 1069 final ProviderMap mProviderMap; 1070 1071 /** 1072 * List of content providers who have clients waiting for them. The 1073 * application is currently being launched and the provider will be 1074 * removed from this list once it is published. 1075 */ 1076 final ArrayList<ContentProviderRecord> mLaunchingProviders 1077 = new ArrayList<ContentProviderRecord>(); 1078 1079 /** 1080 * File storing persisted {@link #mGrantedUriPermissions}. 1081 */ 1082 private final AtomicFile mGrantFile; 1083 1084 /** XML constants used in {@link #mGrantFile} */ 1085 private static final String TAG_URI_GRANTS = "uri-grants"; 1086 private static final String TAG_URI_GRANT = "uri-grant"; 1087 private static final String ATTR_USER_HANDLE = "userHandle"; 1088 private static final String ATTR_SOURCE_USER_ID = "sourceUserId"; 1089 private static final String ATTR_TARGET_USER_ID = "targetUserId"; 1090 private static final String ATTR_SOURCE_PKG = "sourcePkg"; 1091 private static final String ATTR_TARGET_PKG = "targetPkg"; 1092 private static final String ATTR_URI = "uri"; 1093 private static final String ATTR_MODE_FLAGS = "modeFlags"; 1094 private static final String ATTR_CREATED_TIME = "createdTime"; 1095 private static final String ATTR_PREFIX = "prefix"; 1096 1097 /** 1098 * Global set of specific {@link Uri} permissions that have been granted. 1099 * This optimized lookup structure maps from {@link UriPermission#targetUid} 1100 * to {@link UriPermission#uri} to {@link UriPermission}. 1101 */ 1102 @GuardedBy("this") 1103 private final SparseArray<ArrayMap<GrantUri, UriPermission>> 1104 mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>(); 1105 1106 public static class GrantUri { 1107 public final int sourceUserId; 1108 public final Uri uri; 1109 public boolean prefix; 1110 1111 public GrantUri(int sourceUserId, Uri uri, boolean prefix) { 1112 this.sourceUserId = sourceUserId; 1113 this.uri = uri; 1114 this.prefix = prefix; 1115 } 1116 1117 @Override 1118 public int hashCode() { 1119 int hashCode = 1; 1120 hashCode = 31 * hashCode + sourceUserId; 1121 hashCode = 31 * hashCode + uri.hashCode(); 1122 hashCode = 31 * hashCode + (prefix ? 1231 : 1237); 1123 return hashCode; 1124 } 1125 1126 @Override 1127 public boolean equals(Object o) { 1128 if (o instanceof GrantUri) { 1129 GrantUri other = (GrantUri) o; 1130 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId) 1131 && prefix == other.prefix; 1132 } 1133 return false; 1134 } 1135 1136 @Override 1137 public String toString() { 1138 String result = uri.toString() + " [user " + sourceUserId + "]"; 1139 if (prefix) result += " [prefix]"; 1140 return result; 1141 } 1142 1143 public String toSafeString() { 1144 String result = uri.toSafeString() + " [user " + sourceUserId + "]"; 1145 if (prefix) result += " [prefix]"; 1146 return result; 1147 } 1148 1149 public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) { 1150 return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle), 1151 ContentProvider.getUriWithoutUserId(uri), false); 1152 } 1153 } 1154 1155 CoreSettingsObserver mCoreSettingsObserver; 1156 1157 FontScaleSettingObserver mFontScaleSettingObserver; 1158 1159 private final class FontScaleSettingObserver extends ContentObserver { 1160 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE); 1161 1162 public FontScaleSettingObserver() { 1163 super(mHandler); 1164 ContentResolver resolver = mContext.getContentResolver(); 1165 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL); 1166 } 1167 1168 @Override 1169 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) { 1170 if (mFontScaleUri.equals(uri)) { 1171 updateFontScaleIfNeeded(userId); 1172 } 1173 } 1174 } 1175 1176 /** 1177 * Thread-local storage used to carry caller permissions over through 1178 * indirect content-provider access. 1179 */ 1180 private class Identity { 1181 public final IBinder token; 1182 public final int pid; 1183 public final int uid; 1184 1185 Identity(IBinder _token, int _pid, int _uid) { 1186 token = _token; 1187 pid = _pid; 1188 uid = _uid; 1189 } 1190 } 1191 1192 private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>(); 1193 1194 /** 1195 * All information we have collected about the runtime performance of 1196 * any user id that can impact battery performance. 1197 */ 1198 final BatteryStatsService mBatteryStatsService; 1199 1200 /** 1201 * Information about component usage 1202 */ 1203 UsageStatsManagerInternal mUsageStatsService; 1204 1205 /** 1206 * Access to DeviceIdleController service. 1207 */ 1208 DeviceIdleController.LocalService mLocalDeviceIdleController; 1209 1210 /** 1211 * Set of app ids that are whitelisted for device idle and thus background check. 1212 */ 1213 int[] mDeviceIdleWhitelist = new int[0]; 1214 1215 /** 1216 * Set of app ids that are temporarily allowed to escape bg check due to high-pri message 1217 */ 1218 int[] mDeviceIdleTempWhitelist = new int[0]; 1219 1220 static final class PendingTempWhitelist { 1221 final int targetUid; 1222 final long duration; 1223 final String tag; 1224 1225 PendingTempWhitelist(int _targetUid, long _duration, String _tag) { 1226 targetUid = _targetUid; 1227 duration = _duration; 1228 tag = _tag; 1229 } 1230 } 1231 1232 final SparseArray<PendingTempWhitelist> mPendingTempWhitelist = new SparseArray<>(); 1233 1234 /** 1235 * Information about and control over application operations 1236 */ 1237 final AppOpsService mAppOpsService; 1238 1239 /** Current sequencing integer of the configuration, for skipping old configurations. */ 1240 private int mConfigurationSeq; 1241 1242 /** 1243 * Temp object used when global and/or display override configuration is updated. It is also 1244 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust 1245 * anyone... 1246 */ 1247 private Configuration mTempConfig = new Configuration(); 1248 1249 private final UpdateConfigurationResult mTmpUpdateConfigurationResult = 1250 new UpdateConfigurationResult(); 1251 private static final class UpdateConfigurationResult { 1252 // Configuration changes that were updated. 1253 int changes; 1254 // If the activity was relaunched to match the new configuration. 1255 boolean activityRelaunched; 1256 1257 void reset() { 1258 changes = 0; 1259 activityRelaunched = false; 1260 } 1261 } 1262 1263 boolean mSuppressResizeConfigChanges; 1264 1265 /** 1266 * Hardware-reported OpenGLES version. 1267 */ 1268 final int GL_ES_VERSION; 1269 1270 /** 1271 * List of initialization arguments to pass to all processes when binding applications to them. 1272 * For example, references to the commonly used services. 1273 */ 1274 HashMap<String, IBinder> mAppBindArgs; 1275 HashMap<String, IBinder> mIsolatedAppBindArgs; 1276 1277 /** 1278 * Temporary to avoid allocations. Protected by main lock. 1279 */ 1280 final StringBuilder mStringBuilder = new StringBuilder(256); 1281 1282 /** 1283 * Used to control how we initialize the service. 1284 */ 1285 ComponentName mTopComponent; 1286 String mTopAction = Intent.ACTION_MAIN; 1287 String mTopData; 1288 1289 volatile boolean mProcessesReady = false; 1290 volatile boolean mSystemReady = false; 1291 volatile boolean mOnBattery = false; 1292 volatile int mFactoryTest; 1293 1294 @GuardedBy("this") boolean mBooting = false; 1295 @GuardedBy("this") boolean mCallFinishBooting = false; 1296 @GuardedBy("this") boolean mBootAnimationComplete = false; 1297 @GuardedBy("this") boolean mLaunchWarningShown = false; 1298 @GuardedBy("this") boolean mCheckedForSetup = false; 1299 1300 final Context mContext; 1301 1302 /** 1303 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can 1304 * change at runtime. Use mContext for non-UI purposes. 1305 */ 1306 final Context mUiContext; 1307 1308 /** 1309 * The time at which we will allow normal application switches again, 1310 * after a call to {@link #stopAppSwitches()}. 1311 */ 1312 long mAppSwitchesAllowedTime; 1313 1314 /** 1315 * This is set to true after the first switch after mAppSwitchesAllowedTime 1316 * is set; any switches after that will clear the time. 1317 */ 1318 boolean mDidAppSwitch; 1319 1320 /** 1321 * Last time (in realtime) at which we checked for power usage. 1322 */ 1323 long mLastPowerCheckRealtime; 1324 1325 /** 1326 * Last time (in uptime) at which we checked for power usage. 1327 */ 1328 long mLastPowerCheckUptime; 1329 1330 /** 1331 * Set while we are wanting to sleep, to prevent any 1332 * activities from being started/resumed. 1333 * 1334 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping. 1335 * 1336 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true 1337 * while in the sleep state until there is a pending transition out of sleep, in which case 1338 * mSleeping is set to false, and remains false while awake. 1339 * 1340 * Whether mSleeping can quickly toggled between true/false without the device actually 1341 * display changing states is undefined. 1342 */ 1343 private boolean mSleeping = false; 1344 1345 /** 1346 * The process state used for processes that are running the top activities. 1347 * This changes between TOP and TOP_SLEEPING to following mSleeping. 1348 */ 1349 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP; 1350 1351 /** 1352 * Set while we are running a voice interaction. This overrides 1353 * sleeping while it is active. 1354 */ 1355 private IVoiceInteractionSession mRunningVoice; 1356 1357 /** 1358 * For some direct access we need to power manager. 1359 */ 1360 PowerManagerInternal mLocalPowerManager; 1361 1362 /** 1363 * We want to hold a wake lock while running a voice interaction session, since 1364 * this may happen with the screen off and we need to keep the CPU running to 1365 * be able to continue to interact with the user. 1366 */ 1367 PowerManager.WakeLock mVoiceWakeLock; 1368 1369 /** 1370 * State of external calls telling us if the device is awake or asleep. 1371 */ 1372 private int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE; 1373 1374 /** 1375 * A list of tokens that cause the top activity to be put to sleep. 1376 * They are used by components that may hide and block interaction with underlying 1377 * activities. 1378 */ 1379 final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>(); 1380 1381 /** 1382 * Set if we are shutting down the system, similar to sleeping. 1383 */ 1384 boolean mShuttingDown = false; 1385 1386 /** 1387 * Current sequence id for oom_adj computation traversal. 1388 */ 1389 int mAdjSeq = 0; 1390 1391 /** 1392 * Current sequence id for process LRU updating. 1393 */ 1394 int mLruSeq = 0; 1395 1396 /** 1397 * Keep track of the non-cached/empty process we last found, to help 1398 * determine how to distribute cached/empty processes next time. 1399 */ 1400 int mNumNonCachedProcs = 0; 1401 1402 /** 1403 * Keep track of the number of cached hidden procs, to balance oom adj 1404 * distribution between those and empty procs. 1405 */ 1406 int mNumCachedHiddenProcs = 0; 1407 1408 /** 1409 * Keep track of the number of service processes we last found, to 1410 * determine on the next iteration which should be B services. 1411 */ 1412 int mNumServiceProcs = 0; 1413 int mNewNumAServiceProcs = 0; 1414 int mNewNumServiceProcs = 0; 1415 1416 /** 1417 * Allow the current computed overall memory level of the system to go down? 1418 * This is set to false when we are killing processes for reasons other than 1419 * memory management, so that the now smaller process list will not be taken as 1420 * an indication that memory is tighter. 1421 */ 1422 boolean mAllowLowerMemLevel = false; 1423 1424 /** 1425 * The last computed memory level, for holding when we are in a state that 1426 * processes are going away for other reasons. 1427 */ 1428 int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 1429 1430 /** 1431 * The last total number of process we have, to determine if changes actually look 1432 * like a shrinking number of process due to lower RAM. 1433 */ 1434 int mLastNumProcesses; 1435 1436 /** 1437 * The uptime of the last time we performed idle maintenance. 1438 */ 1439 long mLastIdleTime = SystemClock.uptimeMillis(); 1440 1441 /** 1442 * Total time spent with RAM that has been added in the past since the last idle time. 1443 */ 1444 long mLowRamTimeSinceLastIdle = 0; 1445 1446 /** 1447 * If RAM is currently low, when that horrible situation started. 1448 */ 1449 long mLowRamStartTime = 0; 1450 1451 /** 1452 * For reporting to battery stats the current top application. 1453 */ 1454 private String mCurResumedPackage = null; 1455 private int mCurResumedUid = -1; 1456 1457 /** 1458 * For reporting to battery stats the apps currently running foreground 1459 * service. The ProcessMap is package/uid tuples; each of these contain 1460 * an array of the currently foreground processes. 1461 */ 1462 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1463 = new ProcessMap<ArrayList<ProcessRecord>>(); 1464 1465 /** 1466 * This is set if we had to do a delayed dexopt of an app before launching 1467 * it, to increase the ANR timeouts in that case. 1468 */ 1469 boolean mDidDexOpt; 1470 1471 /** 1472 * Set if the systemServer made a call to enterSafeMode. 1473 */ 1474 boolean mSafeMode; 1475 1476 /** 1477 * If true, we are running under a test environment so will sample PSS from processes 1478 * much more rapidly to try to collect better data when the tests are rapidly 1479 * running through apps. 1480 */ 1481 boolean mTestPssMode = false; 1482 1483 String mDebugApp = null; 1484 boolean mWaitForDebugger = false; 1485 boolean mDebugTransient = false; 1486 String mOrigDebugApp = null; 1487 boolean mOrigWaitForDebugger = false; 1488 boolean mAlwaysFinishActivities = false; 1489 boolean mForceResizableActivities; 1490 /** 1491 * Flag that indicates if multi-window is enabled. 1492 * 1493 * For any particular form of multi-window to be enabled, generic multi-window must be enabled 1494 * in {@link com.android.internal.R.bool.config_supportsMultiWindow} config or 1495 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set. 1496 * At least one of the forms of multi-window must be enabled in order for this flag to be 1497 * initialized to 'true'. 1498 * 1499 * @see #mSupportsSplitScreenMultiWindow 1500 * @see #mSupportsFreeformWindowManagement 1501 * @see #mSupportsPictureInPicture 1502 * @see #mSupportsMultiDisplay 1503 */ 1504 boolean mSupportsMultiWindow; 1505 boolean mSupportsSplitScreenMultiWindow; 1506 boolean mSupportsFreeformWindowManagement; 1507 boolean mSupportsPictureInPicture; 1508 boolean mSupportsMultiDisplay; 1509 boolean mSupportsLeanbackOnly; 1510 IActivityController mController = null; 1511 boolean mControllerIsAMonkey = false; 1512 String mProfileApp = null; 1513 ProcessRecord mProfileProc = null; 1514 String mProfileFile; 1515 ParcelFileDescriptor mProfileFd; 1516 int mSamplingInterval = 0; 1517 boolean mAutoStopProfiler = false; 1518 boolean mStreamingOutput = false; 1519 int mProfileType = 0; 1520 final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>(); 1521 String mMemWatchDumpProcName; 1522 String mMemWatchDumpFile; 1523 int mMemWatchDumpPid; 1524 int mMemWatchDumpUid; 1525 String mTrackAllocationApp = null; 1526 String mNativeDebuggingApp = null; 1527 1528 final long[] mTmpLong = new long[2]; 1529 1530 private final ArraySet<BroadcastQueue> mTmpBroadcastQueue = new ArraySet(); 1531 1532 /** 1533 * A global counter for generating sequence numbers. 1534 * This value will be used when incrementing sequence numbers in individual uidRecords. 1535 * 1536 * Having a global counter ensures that seq numbers are monotonically increasing for a 1537 * particular uid even when the uidRecord is re-created. 1538 */ 1539 @GuardedBy("this") 1540 @VisibleForTesting 1541 long mProcStateSeqCounter = 0; 1542 1543 private final Injector mInjector; 1544 1545 static final class ProcessChangeItem { 1546 static final int CHANGE_ACTIVITIES = 1<<0; 1547 int changes; 1548 int uid; 1549 int pid; 1550 int processState; 1551 boolean foregroundActivities; 1552 } 1553 1554 static final class UidObserverRegistration { 1555 final int uid; 1556 final String pkg; 1557 final int which; 1558 final int cutpoint; 1559 1560 final SparseIntArray lastProcStates; 1561 1562 UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint) { 1563 uid = _uid; 1564 pkg = _pkg; 1565 which = _which; 1566 cutpoint = _cutpoint; 1567 if (cutpoint >= ActivityManager.MIN_PROCESS_STATE) { 1568 lastProcStates = new SparseIntArray(); 1569 } else { 1570 lastProcStates = null; 1571 } 1572 } 1573 } 1574 1575 final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>(); 1576 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5]; 1577 1578 final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>(); 1579 final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>(); 1580 1581 final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>(); 1582 UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5]; 1583 1584 final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>(); 1585 final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>(); 1586 1587 /** 1588 * Runtime CPU use collection thread. This object's lock is used to 1589 * perform synchronization with the thread (notifying it to run). 1590 */ 1591 final Thread mProcessCpuThread; 1592 1593 /** 1594 * Used to collect per-process CPU use for ANRs, battery stats, etc. 1595 * Must acquire this object's lock when accessing it. 1596 * NOTE: this lock will be held while doing long operations (trawling 1597 * through all processes in /proc), so it should never be acquired by 1598 * any critical paths such as when holding the main activity manager lock. 1599 */ 1600 final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker( 1601 MONITOR_THREAD_CPU_USAGE); 1602 final AtomicLong mLastCpuTime = new AtomicLong(0); 1603 final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true); 1604 final CountDownLatch mProcessCpuInitLatch = new CountDownLatch(1); 1605 1606 long mLastWriteTime = 0; 1607 1608 /** 1609 * Used to retain an update lock when the foreground activity is in 1610 * immersive mode. 1611 */ 1612 final UpdateLock mUpdateLock = new UpdateLock("immersive"); 1613 1614 /** 1615 * Set to true after the system has finished booting. 1616 */ 1617 boolean mBooted = false; 1618 1619 WindowManagerService mWindowManager; 1620 final ActivityThread mSystemThread; 1621 1622 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1623 final ProcessRecord mApp; 1624 final int mPid; 1625 final IApplicationThread mAppThread; 1626 1627 AppDeathRecipient(ProcessRecord app, int pid, 1628 IApplicationThread thread) { 1629 if (DEBUG_ALL) Slog.v( 1630 TAG, "New death recipient " + this 1631 + " for thread " + thread.asBinder()); 1632 mApp = app; 1633 mPid = pid; 1634 mAppThread = thread; 1635 } 1636 1637 @Override 1638 public void binderDied() { 1639 if (DEBUG_ALL) Slog.v( 1640 TAG, "Death received in " + this 1641 + " for thread " + mAppThread.asBinder()); 1642 synchronized(ActivityManagerService.this) { 1643 appDiedLocked(mApp, mPid, mAppThread, true); 1644 } 1645 } 1646 } 1647 1648 static final int SHOW_ERROR_UI_MSG = 1; 1649 static final int SHOW_NOT_RESPONDING_UI_MSG = 2; 1650 static final int SHOW_FACTORY_ERROR_UI_MSG = 3; 1651 static final int UPDATE_CONFIGURATION_MSG = 4; 1652 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1653 static final int WAIT_FOR_DEBUGGER_UI_MSG = 6; 1654 static final int SERVICE_TIMEOUT_MSG = 12; 1655 static final int UPDATE_TIME_ZONE = 13; 1656 static final int SHOW_UID_ERROR_UI_MSG = 14; 1657 static final int SHOW_FINGERPRINT_ERROR_UI_MSG = 15; 1658 static final int PROC_START_TIMEOUT_MSG = 20; 1659 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21; 1660 static final int KILL_APPLICATION_MSG = 22; 1661 static final int FINALIZE_PENDING_INTENT_MSG = 23; 1662 static final int POST_HEAVY_NOTIFICATION_MSG = 24; 1663 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25; 1664 static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26; 1665 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27; 1666 static final int CLEAR_DNS_CACHE_MSG = 28; 1667 static final int UPDATE_HTTP_PROXY_MSG = 29; 1668 static final int SHOW_COMPAT_MODE_DIALOG_UI_MSG = 30; 1669 static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31; 1670 static final int DISPATCH_PROCESS_DIED_UI_MSG = 32; 1671 static final int REPORT_MEM_USAGE_MSG = 33; 1672 static final int REPORT_USER_SWITCH_MSG = 34; 1673 static final int CONTINUE_USER_SWITCH_MSG = 35; 1674 static final int USER_SWITCH_TIMEOUT_MSG = 36; 1675 static final int IMMERSIVE_MODE_LOCK_MSG = 37; 1676 static final int PERSIST_URI_GRANTS_MSG = 38; 1677 static final int REQUEST_ALL_PSS_MSG = 39; 1678 static final int START_PROFILES_MSG = 40; 1679 static final int UPDATE_TIME_PREFERENCE_MSG = 41; 1680 static final int SYSTEM_USER_START_MSG = 42; 1681 static final int SYSTEM_USER_CURRENT_MSG = 43; 1682 static final int ENTER_ANIMATION_COMPLETE_MSG = 44; 1683 static final int FINISH_BOOTING_MSG = 45; 1684 static final int START_USER_SWITCH_UI_MSG = 46; 1685 static final int SEND_LOCALE_TO_MOUNT_DAEMON_MSG = 47; 1686 static final int DISMISS_DIALOG_UI_MSG = 48; 1687 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49; 1688 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50; 1689 static final int DELETE_DUMPHEAP_MSG = 51; 1690 static final int FOREGROUND_PROFILE_CHANGED_MSG = 52; 1691 static final int DISPATCH_UIDS_CHANGED_UI_MSG = 53; 1692 static final int REPORT_TIME_TRACKER_MSG = 54; 1693 static final int REPORT_USER_SWITCH_COMPLETE_MSG = 55; 1694 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56; 1695 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57; 1696 static final int IDLE_UIDS_MSG = 58; 1697 static final int SYSTEM_USER_UNLOCK_MSG = 59; 1698 static final int LOG_STACK_STATE = 60; 1699 static final int VR_MODE_CHANGE_MSG = 61; 1700 static final int SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG = 62; 1701 static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63; 1702 static final int REPORT_LOCKED_BOOT_COMPLETE_MSG = 64; 1703 static final int NOTIFY_VR_SLEEPING_MSG = 65; 1704 static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66; 1705 static final int DISPATCH_PENDING_INTENT_CANCEL_MSG = 67; 1706 static final int PUSH_TEMP_WHITELIST_UI_MSG = 68; 1707 static final int SERVICE_FOREGROUND_CRASH_MSG = 69; 1708 static final int START_USER_SWITCH_FG_MSG = 712; 1709 1710 static final int FIRST_ACTIVITY_STACK_MSG = 100; 1711 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1712 static final int FIRST_COMPAT_MODE_MSG = 300; 1713 static final int FIRST_SUPERVISOR_STACK_MSG = 100; 1714 1715 static ServiceThread sKillThread = null; 1716 static KillHandler sKillHandler = null; 1717 1718 CompatModeDialog mCompatModeDialog; 1719 UnsupportedDisplaySizeDialog mUnsupportedDisplaySizeDialog; 1720 long mLastMemUsageReportTime = 0; 1721 1722 /** 1723 * Flag whether the current user is a "monkey", i.e. whether 1724 * the UI is driven by a UI automation tool. 1725 */ 1726 private boolean mUserIsMonkey; 1727 1728 /** Flag whether the device has a Recents UI */ 1729 boolean mHasRecents; 1730 1731 /** The dimensions of the thumbnails in the Recents UI. */ 1732 int mThumbnailWidth; 1733 int mThumbnailHeight; 1734 float mFullscreenThumbnailScale; 1735 1736 final ServiceThread mHandlerThread; 1737 final MainHandler mHandler; 1738 final Handler mUiHandler; 1739 1740 final ActivityManagerConstants mConstants; 1741 1742 PackageManagerInternal mPackageManagerInt; 1743 1744 // VoiceInteraction session ID that changes for each new request except when 1745 // being called for multiwindow assist in a single session. 1746 private int mViSessionId = 1000; 1747 1748 final boolean mPermissionReviewRequired; 1749 1750 /** 1751 * Current global configuration information. Contains general settings for the entire system, 1752 * also corresponds to the merged configuration of the default display. 1753 */ 1754 Configuration getGlobalConfiguration() { 1755 return mStackSupervisor.getConfiguration(); 1756 } 1757 1758 final class KillHandler extends Handler { 1759 static final int KILL_PROCESS_GROUP_MSG = 4000; 1760 1761 public KillHandler(Looper looper) { 1762 super(looper, null, true); 1763 } 1764 1765 @Override 1766 public void handleMessage(Message msg) { 1767 switch (msg.what) { 1768 case KILL_PROCESS_GROUP_MSG: 1769 { 1770 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup"); 1771 Process.killProcessGroup(msg.arg1 /* uid */, msg.arg2 /* pid */); 1772 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 1773 } 1774 break; 1775 1776 default: 1777 super.handleMessage(msg); 1778 } 1779 } 1780 } 1781 1782 final class UiHandler extends Handler { 1783 public UiHandler() { 1784 super(com.android.server.UiThread.get().getLooper(), null, true); 1785 } 1786 1787 @Override 1788 public void handleMessage(Message msg) { 1789 switch (msg.what) { 1790 case SHOW_ERROR_UI_MSG: { 1791 mAppErrors.handleShowAppErrorUi(msg); 1792 ensureBootCompleted(); 1793 } break; 1794 case SHOW_NOT_RESPONDING_UI_MSG: { 1795 mAppErrors.handleShowAnrUi(msg); 1796 ensureBootCompleted(); 1797 } break; 1798 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: { 1799 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1800 synchronized (ActivityManagerService.this) { 1801 ProcessRecord proc = (ProcessRecord) data.get("app"); 1802 if (proc == null) { 1803 Slog.e(TAG, "App not found when showing strict mode dialog."); 1804 break; 1805 } 1806 if (proc.crashDialog != null) { 1807 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1808 return; 1809 } 1810 AppErrorResult res = (AppErrorResult) data.get("result"); 1811 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1812 Dialog d = new StrictModeViolationDialog(mUiContext, 1813 ActivityManagerService.this, res, proc); 1814 d.show(); 1815 proc.crashDialog = d; 1816 } else { 1817 // The device is asleep, so just pretend that the user 1818 // saw a crash dialog and hit "force quit". 1819 res.set(0); 1820 } 1821 } 1822 ensureBootCompleted(); 1823 } break; 1824 case SHOW_FACTORY_ERROR_UI_MSG: { 1825 Dialog d = new FactoryErrorDialog( 1826 mUiContext, msg.getData().getCharSequence("msg")); 1827 d.show(); 1828 ensureBootCompleted(); 1829 } break; 1830 case WAIT_FOR_DEBUGGER_UI_MSG: { 1831 synchronized (ActivityManagerService.this) { 1832 ProcessRecord app = (ProcessRecord)msg.obj; 1833 if (msg.arg1 != 0) { 1834 if (!app.waitedForDebugger) { 1835 Dialog d = new AppWaitingForDebuggerDialog( 1836 ActivityManagerService.this, 1837 mUiContext, app); 1838 app.waitDialog = d; 1839 app.waitedForDebugger = true; 1840 d.show(); 1841 } 1842 } else { 1843 if (app.waitDialog != null) { 1844 app.waitDialog.dismiss(); 1845 app.waitDialog = null; 1846 } 1847 } 1848 } 1849 } break; 1850 case SHOW_UID_ERROR_UI_MSG: { 1851 if (mShowDialogs) { 1852 AlertDialog d = new BaseErrorDialog(mUiContext); 1853 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1854 d.setCancelable(false); 1855 d.setTitle(mUiContext.getText(R.string.android_system_label)); 1856 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data)); 1857 d.setButton(DialogInterface.BUTTON_POSITIVE, mUiContext.getText(R.string.ok), 1858 obtainMessage(DISMISS_DIALOG_UI_MSG, d)); 1859 d.show(); 1860 } 1861 } break; 1862 case SHOW_FINGERPRINT_ERROR_UI_MSG: { 1863 if (mShowDialogs) { 1864 AlertDialog d = new BaseErrorDialog(mUiContext); 1865 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1866 d.setCancelable(false); 1867 d.setTitle(mUiContext.getText(R.string.android_system_label)); 1868 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer)); 1869 d.setButton(DialogInterface.BUTTON_POSITIVE, mUiContext.getText(R.string.ok), 1870 obtainMessage(DISMISS_DIALOG_UI_MSG, d)); 1871 d.show(); 1872 } 1873 } break; 1874 case SHOW_COMPAT_MODE_DIALOG_UI_MSG: { 1875 synchronized (ActivityManagerService.this) { 1876 ActivityRecord ar = (ActivityRecord) msg.obj; 1877 if (mCompatModeDialog != null) { 1878 if (mCompatModeDialog.mAppInfo.packageName.equals( 1879 ar.info.applicationInfo.packageName)) { 1880 return; 1881 } 1882 mCompatModeDialog.dismiss(); 1883 mCompatModeDialog = null; 1884 } 1885 if (ar != null && false) { 1886 if (mCompatModePackages.getPackageAskCompatModeLocked( 1887 ar.packageName)) { 1888 int mode = mCompatModePackages.computeCompatModeLocked( 1889 ar.info.applicationInfo); 1890 if (mode == ActivityManager.COMPAT_MODE_DISABLED 1891 || mode == ActivityManager.COMPAT_MODE_ENABLED) { 1892 mCompatModeDialog = new CompatModeDialog( 1893 ActivityManagerService.this, mUiContext, 1894 ar.info.applicationInfo); 1895 mCompatModeDialog.show(); 1896 } 1897 } 1898 } 1899 } 1900 break; 1901 } 1902 case SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG: { 1903 synchronized (ActivityManagerService.this) { 1904 final ActivityRecord ar = (ActivityRecord) msg.obj; 1905 if (mUnsupportedDisplaySizeDialog != null) { 1906 mUnsupportedDisplaySizeDialog.dismiss(); 1907 mUnsupportedDisplaySizeDialog = null; 1908 } 1909 if (ar != null && mCompatModePackages.getPackageNotifyUnsupportedZoomLocked( 1910 ar.packageName)) { 1911 // TODO(multi-display): Show dialog on appropriate display. 1912 mUnsupportedDisplaySizeDialog = new UnsupportedDisplaySizeDialog( 1913 ActivityManagerService.this, mUiContext, ar.info.applicationInfo); 1914 mUnsupportedDisplaySizeDialog.show(); 1915 } 1916 } 1917 break; 1918 } 1919 case START_USER_SWITCH_UI_MSG: { 1920 mUserController.showUserSwitchDialog((Pair<UserInfo, UserInfo>) msg.obj); 1921 break; 1922 } 1923 case DISMISS_DIALOG_UI_MSG: { 1924 final Dialog d = (Dialog) msg.obj; 1925 d.dismiss(); 1926 break; 1927 } 1928 case DISPATCH_PROCESSES_CHANGED_UI_MSG: { 1929 dispatchProcessesChanged(); 1930 break; 1931 } 1932 case DISPATCH_PROCESS_DIED_UI_MSG: { 1933 final int pid = msg.arg1; 1934 final int uid = msg.arg2; 1935 dispatchProcessDied(pid, uid); 1936 break; 1937 } 1938 case DISPATCH_UIDS_CHANGED_UI_MSG: { 1939 dispatchUidsChanged(); 1940 } break; 1941 case PUSH_TEMP_WHITELIST_UI_MSG: { 1942 pushTempWhitelist(); 1943 } break; 1944 } 1945 } 1946 } 1947 1948 final class MainHandler extends Handler { 1949 public MainHandler(Looper looper) { 1950 super(looper, null, true); 1951 } 1952 1953 @Override 1954 public void handleMessage(Message msg) { 1955 switch (msg.what) { 1956 case UPDATE_CONFIGURATION_MSG: { 1957 final ContentResolver resolver = mContext.getContentResolver(); 1958 Settings.System.putConfigurationForUser(resolver, (Configuration) msg.obj, 1959 msg.arg1); 1960 } break; 1961 case GC_BACKGROUND_PROCESSES_MSG: { 1962 synchronized (ActivityManagerService.this) { 1963 performAppGcsIfAppropriateLocked(); 1964 } 1965 } break; 1966 case SERVICE_TIMEOUT_MSG: { 1967 if (mDidDexOpt) { 1968 mDidDexOpt = false; 1969 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG); 1970 nmsg.obj = msg.obj; 1971 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT); 1972 return; 1973 } 1974 mServices.serviceTimeout((ProcessRecord)msg.obj); 1975 } break; 1976 case SERVICE_FOREGROUND_TIMEOUT_MSG: { 1977 mServices.serviceForegroundTimeout((ServiceRecord)msg.obj); 1978 } break; 1979 case SERVICE_FOREGROUND_CRASH_MSG: { 1980 mServices.serviceForegroundCrash((ProcessRecord)msg.obj); 1981 } break; 1982 case DISPATCH_PENDING_INTENT_CANCEL_MSG: { 1983 RemoteCallbackList<IResultReceiver> callbacks 1984 = (RemoteCallbackList<IResultReceiver>)msg.obj; 1985 int N = callbacks.beginBroadcast(); 1986 for (int i = 0; i < N; i++) { 1987 try { 1988 callbacks.getBroadcastItem(i).send(Activity.RESULT_CANCELED, null); 1989 } catch (RemoteException e) { 1990 } 1991 } 1992 callbacks.finishBroadcast(); 1993 } break; 1994 case UPDATE_TIME_ZONE: { 1995 synchronized (ActivityManagerService.this) { 1996 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1997 ProcessRecord r = mLruProcesses.get(i); 1998 if (r.thread != null) { 1999 try { 2000 r.thread.updateTimeZone(); 2001 } catch (RemoteException ex) { 2002 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 2003 } 2004 } 2005 } 2006 } 2007 } break; 2008 case CLEAR_DNS_CACHE_MSG: { 2009 synchronized (ActivityManagerService.this) { 2010 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 2011 ProcessRecord r = mLruProcesses.get(i); 2012 if (r.thread != null) { 2013 try { 2014 r.thread.clearDnsCache(); 2015 } catch (RemoteException ex) { 2016 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 2017 } 2018 } 2019 } 2020 } 2021 } break; 2022 case UPDATE_HTTP_PROXY_MSG: { 2023 ProxyInfo proxy = (ProxyInfo)msg.obj; 2024 String host = ""; 2025 String port = ""; 2026 String exclList = ""; 2027 Uri pacFileUrl = Uri.EMPTY; 2028 if (proxy != null) { 2029 host = proxy.getHost(); 2030 port = Integer.toString(proxy.getPort()); 2031 exclList = proxy.getExclusionListAsString(); 2032 pacFileUrl = proxy.getPacFileUrl(); 2033 } 2034 synchronized (ActivityManagerService.this) { 2035 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 2036 ProcessRecord r = mLruProcesses.get(i); 2037 if (r.thread != null) { 2038 try { 2039 r.thread.setHttpProxy(host, port, exclList, pacFileUrl); 2040 } catch (RemoteException ex) { 2041 Slog.w(TAG, "Failed to update http proxy for: " + 2042 r.info.processName); 2043 } 2044 } 2045 } 2046 } 2047 } break; 2048 case PROC_START_TIMEOUT_MSG: { 2049 if (mDidDexOpt) { 2050 mDidDexOpt = false; 2051 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 2052 nmsg.obj = msg.obj; 2053 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT); 2054 return; 2055 } 2056 ProcessRecord app = (ProcessRecord)msg.obj; 2057 synchronized (ActivityManagerService.this) { 2058 processStartTimedOutLocked(app); 2059 } 2060 } break; 2061 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: { 2062 ProcessRecord app = (ProcessRecord)msg.obj; 2063 synchronized (ActivityManagerService.this) { 2064 processContentProviderPublishTimedOutLocked(app); 2065 } 2066 } break; 2067 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: { 2068 synchronized (ActivityManagerService.this) { 2069 mActivityStarter.doPendingActivityLaunchesLocked(true); 2070 } 2071 } break; 2072 case KILL_APPLICATION_MSG: { 2073 synchronized (ActivityManagerService.this) { 2074 final int appId = msg.arg1; 2075 final int userId = msg.arg2; 2076 Bundle bundle = (Bundle)msg.obj; 2077 String pkg = bundle.getString("pkg"); 2078 String reason = bundle.getString("reason"); 2079 forceStopPackageLocked(pkg, appId, false, false, true, false, 2080 false, userId, reason); 2081 } 2082 } break; 2083 case FINALIZE_PENDING_INTENT_MSG: { 2084 ((PendingIntentRecord)msg.obj).completeFinalize(); 2085 } break; 2086 case POST_HEAVY_NOTIFICATION_MSG: { 2087 INotificationManager inm = NotificationManager.getService(); 2088 if (inm == null) { 2089 return; 2090 } 2091 2092 ActivityRecord root = (ActivityRecord)msg.obj; 2093 ProcessRecord process = root.app; 2094 if (process == null) { 2095 return; 2096 } 2097 2098 try { 2099 Context context = mContext.createPackageContext(process.info.packageName, 0); 2100 String text = mContext.getString(R.string.heavy_weight_notification, 2101 context.getApplicationInfo().loadLabel(context.getPackageManager())); 2102 Notification notification = 2103 new Notification.Builder(context, SystemNotificationChannels.DEVELOPER) 2104 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 2105 .setWhen(0) 2106 .setOngoing(true) 2107 .setTicker(text) 2108 .setColor(mContext.getColor( 2109 com.android.internal.R.color.system_notification_accent_color)) 2110 .setContentTitle(text) 2111 .setContentText( 2112 mContext.getText(R.string.heavy_weight_notification_detail)) 2113 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, 2114 root.intent, PendingIntent.FLAG_CANCEL_CURRENT, null, 2115 new UserHandle(root.userId))) 2116 .build(); 2117 try { 2118 inm.enqueueNotificationWithTag("android", "android", null, 2119 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, 2120 notification, root.userId); 2121 } catch (RuntimeException e) { 2122 Slog.w(ActivityManagerService.TAG, 2123 "Error showing notification for heavy-weight app", e); 2124 } catch (RemoteException e) { 2125 } 2126 } catch (NameNotFoundException e) { 2127 Slog.w(TAG, "Unable to create context for heavy notification", e); 2128 } 2129 } break; 2130 case CANCEL_HEAVY_NOTIFICATION_MSG: { 2131 INotificationManager inm = NotificationManager.getService(); 2132 if (inm == null) { 2133 return; 2134 } 2135 try { 2136 inm.cancelNotificationWithTag("android", null, 2137 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, msg.arg1); 2138 } catch (RuntimeException e) { 2139 Slog.w(ActivityManagerService.TAG, 2140 "Error canceling notification for service", e); 2141 } catch (RemoteException e) { 2142 } 2143 } break; 2144 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: { 2145 synchronized (ActivityManagerService.this) { 2146 checkExcessivePowerUsageLocked(true); 2147 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 2148 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 2149 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY); 2150 } 2151 } break; 2152 case REPORT_MEM_USAGE_MSG: { 2153 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj; 2154 Thread thread = new Thread() { 2155 @Override public void run() { 2156 reportMemUsage(memInfos); 2157 } 2158 }; 2159 thread.start(); 2160 break; 2161 } 2162 case START_USER_SWITCH_FG_MSG: { 2163 mUserController.startUserInForeground(msg.arg1); 2164 break; 2165 } 2166 case REPORT_USER_SWITCH_MSG: { 2167 mUserController.dispatchUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 2168 break; 2169 } 2170 case CONTINUE_USER_SWITCH_MSG: { 2171 mUserController.continueUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 2172 break; 2173 } 2174 case USER_SWITCH_TIMEOUT_MSG: { 2175 mUserController.timeoutUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 2176 break; 2177 } 2178 case IMMERSIVE_MODE_LOCK_MSG: { 2179 final boolean nextState = (msg.arg1 != 0); 2180 if (mUpdateLock.isHeld() != nextState) { 2181 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, 2182 "Applying new update lock state '" + nextState 2183 + "' for " + (ActivityRecord)msg.obj); 2184 if (nextState) { 2185 mUpdateLock.acquire(); 2186 } else { 2187 mUpdateLock.release(); 2188 } 2189 } 2190 break; 2191 } 2192 case PERSIST_URI_GRANTS_MSG: { 2193 writeGrantedUriPermissions(); 2194 break; 2195 } 2196 case REQUEST_ALL_PSS_MSG: { 2197 synchronized (ActivityManagerService.this) { 2198 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false); 2199 } 2200 break; 2201 } 2202 case START_PROFILES_MSG: { 2203 synchronized (ActivityManagerService.this) { 2204 mUserController.startProfilesLocked(); 2205 } 2206 break; 2207 } 2208 case UPDATE_TIME_PREFERENCE_MSG: { 2209 // The user's time format preference might have changed. 2210 // For convenience we re-use the Intent extra values. 2211 synchronized (ActivityManagerService.this) { 2212 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 2213 ProcessRecord r = mLruProcesses.get(i); 2214 if (r.thread != null) { 2215 try { 2216 r.thread.updateTimePrefs(msg.arg1); 2217 } catch (RemoteException ex) { 2218 Slog.w(TAG, "Failed to update preferences for: " 2219 + r.info.processName); 2220 } 2221 } 2222 } 2223 } 2224 break; 2225 } 2226 case SYSTEM_USER_START_MSG: { 2227 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 2228 Integer.toString(msg.arg1), msg.arg1); 2229 mSystemServiceManager.startUser(msg.arg1); 2230 break; 2231 } 2232 case SYSTEM_USER_UNLOCK_MSG: { 2233 final int userId = msg.arg1; 2234 mSystemServiceManager.unlockUser(userId); 2235 synchronized (ActivityManagerService.this) { 2236 mRecentTasks.loadUserRecentsLocked(userId); 2237 } 2238 if (userId == UserHandle.USER_SYSTEM) { 2239 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_UNAWARE); 2240 } 2241 installEncryptionUnawareProviders(userId); 2242 mUserController.finishUserUnlocked((UserState) msg.obj); 2243 break; 2244 } 2245 case SYSTEM_USER_CURRENT_MSG: { 2246 mBatteryStatsService.noteEvent( 2247 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH, 2248 Integer.toString(msg.arg2), msg.arg2); 2249 mBatteryStatsService.noteEvent( 2250 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 2251 Integer.toString(msg.arg1), msg.arg1); 2252 mSystemServiceManager.switchUser(msg.arg1); 2253 break; 2254 } 2255 case ENTER_ANIMATION_COMPLETE_MSG: { 2256 synchronized (ActivityManagerService.this) { 2257 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj); 2258 if (r != null && r.app != null && r.app.thread != null) { 2259 try { 2260 r.app.thread.scheduleEnterAnimationComplete(r.appToken); 2261 } catch (RemoteException e) { 2262 } 2263 } 2264 } 2265 break; 2266 } 2267 case FINISH_BOOTING_MSG: { 2268 if (msg.arg1 != 0) { 2269 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting"); 2270 finishBooting(); 2271 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 2272 } 2273 if (msg.arg2 != 0) { 2274 enableScreenAfterBoot(); 2275 } 2276 break; 2277 } 2278 case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: { 2279 try { 2280 Locale l = (Locale) msg.obj; 2281 IBinder service = ServiceManager.getService("mount"); 2282 IStorageManager storageManager = IStorageManager.Stub.asInterface(service); 2283 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI"); 2284 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag()); 2285 } catch (RemoteException e) { 2286 Log.e(TAG, "Error storing locale for decryption UI", e); 2287 } 2288 break; 2289 } 2290 case NOTIFY_CLEARTEXT_NETWORK_MSG: { 2291 final int uid = msg.arg1; 2292 final byte[] firstPacket = (byte[]) msg.obj; 2293 2294 synchronized (mPidsSelfLocked) { 2295 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 2296 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 2297 if (p.uid == uid) { 2298 try { 2299 p.thread.notifyCleartextNetwork(firstPacket); 2300 } catch (RemoteException ignored) { 2301 } 2302 } 2303 } 2304 } 2305 break; 2306 } 2307 case POST_DUMP_HEAP_NOTIFICATION_MSG: { 2308 final String procName; 2309 final int uid; 2310 final long memLimit; 2311 final String reportPackage; 2312 synchronized (ActivityManagerService.this) { 2313 procName = mMemWatchDumpProcName; 2314 uid = mMemWatchDumpUid; 2315 Pair<Long, String> val = mMemWatchProcesses.get(procName, uid); 2316 if (val == null) { 2317 val = mMemWatchProcesses.get(procName, 0); 2318 } 2319 if (val != null) { 2320 memLimit = val.first; 2321 reportPackage = val.second; 2322 } else { 2323 memLimit = 0; 2324 reportPackage = null; 2325 } 2326 } 2327 if (procName == null) { 2328 return; 2329 } 2330 2331 if (DEBUG_PSS) Slog.d(TAG_PSS, 2332 "Showing dump heap notification from " + procName + "/" + uid); 2333 2334 INotificationManager inm = NotificationManager.getService(); 2335 if (inm == null) { 2336 return; 2337 } 2338 2339 String text = mContext.getString(R.string.dump_heap_notification, procName); 2340 2341 2342 Intent deleteIntent = new Intent(); 2343 deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP); 2344 Intent intent = new Intent(); 2345 intent.setClassName("android", DumpHeapActivity.class.getName()); 2346 intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName); 2347 intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit); 2348 if (reportPackage != null) { 2349 intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage); 2350 } 2351 int userId = UserHandle.getUserId(uid); 2352 Notification notification = 2353 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 2354 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 2355 .setWhen(0) 2356 .setOngoing(true) 2357 .setAutoCancel(true) 2358 .setTicker(text) 2359 .setColor(mContext.getColor( 2360 com.android.internal.R.color.system_notification_accent_color)) 2361 .setContentTitle(text) 2362 .setContentText( 2363 mContext.getText(R.string.dump_heap_notification_detail)) 2364 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, 2365 intent, PendingIntent.FLAG_CANCEL_CURRENT, null, 2366 new UserHandle(userId))) 2367 .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0, 2368 deleteIntent, 0, UserHandle.SYSTEM)) 2369 .build(); 2370 2371 try { 2372 inm.enqueueNotificationWithTag("android", "android", null, 2373 SystemMessage.NOTE_DUMP_HEAP_NOTIFICATION, 2374 notification, userId); 2375 } catch (RuntimeException e) { 2376 Slog.w(ActivityManagerService.TAG, 2377 "Error showing notification for dump heap", e); 2378 } catch (RemoteException e) { 2379 } 2380 } break; 2381 case DELETE_DUMPHEAP_MSG: { 2382 revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(), 2383 null, DumpHeapActivity.JAVA_URI, 2384 Intent.FLAG_GRANT_READ_URI_PERMISSION 2385 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 2386 UserHandle.myUserId()); 2387 synchronized (ActivityManagerService.this) { 2388 mMemWatchDumpFile = null; 2389 mMemWatchDumpProcName = null; 2390 mMemWatchDumpPid = -1; 2391 mMemWatchDumpUid = -1; 2392 } 2393 } break; 2394 case FOREGROUND_PROFILE_CHANGED_MSG: { 2395 mUserController.dispatchForegroundProfileChanged(msg.arg1); 2396 } break; 2397 case REPORT_TIME_TRACKER_MSG: { 2398 AppTimeTracker tracker = (AppTimeTracker)msg.obj; 2399 tracker.deliverResult(mContext); 2400 } break; 2401 case REPORT_USER_SWITCH_COMPLETE_MSG: { 2402 mUserController.dispatchUserSwitchComplete(msg.arg1); 2403 } break; 2404 case REPORT_LOCKED_BOOT_COMPLETE_MSG: { 2405 mUserController.dispatchLockedBootComplete(msg.arg1); 2406 } break; 2407 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: { 2408 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj; 2409 try { 2410 connection.shutdown(); 2411 } catch (RemoteException e) { 2412 Slog.w(TAG, "Error shutting down UiAutomationConnection"); 2413 } 2414 // Only a UiAutomation can set this flag and now that 2415 // it is finished we make sure it is reset to its default. 2416 mUserIsMonkey = false; 2417 } break; 2418 case IDLE_UIDS_MSG: { 2419 idleUids(); 2420 } break; 2421 case VR_MODE_CHANGE_MSG: { 2422 if (!mVrController.onVrModeChanged((ActivityRecord) msg.obj)) { 2423 return; 2424 } 2425 synchronized (ActivityManagerService.this) { 2426 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked(); 2427 mWindowManager.disableNonVrUi(disableNonVrUi); 2428 if (disableNonVrUi) { 2429 // If we are in a VR mode where Picture-in-Picture mode is unsupported, 2430 // then remove the pinned stack. 2431 final PinnedActivityStack pinnedStack = mStackSupervisor.getStack( 2432 PINNED_STACK_ID); 2433 if (pinnedStack != null) { 2434 mStackSupervisor.removeStackLocked(PINNED_STACK_ID); 2435 } 2436 } 2437 } 2438 } break; 2439 case NOTIFY_VR_SLEEPING_MSG: { 2440 notifyVrManagerOfSleepState(msg.arg1 != 0); 2441 } break; 2442 case HANDLE_TRUST_STORAGE_UPDATE_MSG: { 2443 synchronized (ActivityManagerService.this) { 2444 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 2445 ProcessRecord r = mLruProcesses.get(i); 2446 if (r.thread != null) { 2447 try { 2448 r.thread.handleTrustStorageUpdate(); 2449 } catch (RemoteException ex) { 2450 Slog.w(TAG, "Failed to handle trust storage update for: " + 2451 r.info.processName); 2452 } 2453 } 2454 } 2455 } 2456 } break; 2457 } 2458 } 2459 }; 2460 2461 static final int COLLECT_PSS_BG_MSG = 1; 2462 2463 final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) { 2464 @Override 2465 public void handleMessage(Message msg) { 2466 switch (msg.what) { 2467 case COLLECT_PSS_BG_MSG: { 2468 long start = SystemClock.uptimeMillis(); 2469 MemInfoReader memInfo = null; 2470 synchronized (ActivityManagerService.this) { 2471 if (mFullPssPending) { 2472 mFullPssPending = false; 2473 memInfo = new MemInfoReader(); 2474 } 2475 } 2476 if (memInfo != null) { 2477 updateCpuStatsNow(); 2478 long nativeTotalPss = 0; 2479 final List<ProcessCpuTracker.Stats> stats; 2480 synchronized (mProcessCpuTracker) { 2481 stats = mProcessCpuTracker.getStats( (st)-> { 2482 return st.vsize > 0 && st.uid < FIRST_APPLICATION_UID; 2483 }); 2484 } 2485 final int N = stats.size(); 2486 for (int j = 0; j < N; j++) { 2487 synchronized (mPidsSelfLocked) { 2488 if (mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) { 2489 // This is one of our own processes; skip it. 2490 continue; 2491 } 2492 } 2493 nativeTotalPss += Debug.getPss(stats.get(j).pid, null, null); 2494 } 2495 memInfo.readMemInfo(); 2496 synchronized (ActivityManagerService.this) { 2497 if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in " 2498 + (SystemClock.uptimeMillis()-start) + "ms"); 2499 final long cachedKb = memInfo.getCachedSizeKb(); 2500 final long freeKb = memInfo.getFreeSizeKb(); 2501 final long zramKb = memInfo.getZramTotalSizeKb(); 2502 final long kernelKb = memInfo.getKernelUsedSizeKb(); 2503 EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024, 2504 kernelKb*1024, nativeTotalPss*1024); 2505 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 2506 nativeTotalPss); 2507 } 2508 } 2509 2510 int num = 0; 2511 long[] tmp = new long[2]; 2512 do { 2513 ProcessRecord proc; 2514 int procState; 2515 int pid; 2516 long lastPssTime; 2517 synchronized (ActivityManagerService.this) { 2518 if (mPendingPssProcesses.size() <= 0) { 2519 if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS, 2520 "Collected PSS of " + num + " processes in " 2521 + (SystemClock.uptimeMillis() - start) + "ms"); 2522 mPendingPssProcesses.clear(); 2523 return; 2524 } 2525 proc = mPendingPssProcesses.remove(0); 2526 procState = proc.pssProcState; 2527 lastPssTime = proc.lastPssTime; 2528 if (proc.thread != null && procState == proc.setProcState 2529 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE) 2530 < SystemClock.uptimeMillis()) { 2531 pid = proc.pid; 2532 } else { 2533 proc = null; 2534 pid = 0; 2535 } 2536 } 2537 if (proc != null) { 2538 long pss = Debug.getPss(pid, tmp, null); 2539 synchronized (ActivityManagerService.this) { 2540 if (pss != 0 && proc.thread != null && proc.setProcState == procState 2541 && proc.pid == pid && proc.lastPssTime == lastPssTime) { 2542 num++; 2543 recordPssSampleLocked(proc, procState, pss, tmp[0], tmp[1], 2544 SystemClock.uptimeMillis()); 2545 } 2546 } 2547 } 2548 } while (true); 2549 } 2550 } 2551 } 2552 }; 2553 2554 public void setSystemProcess() { 2555 try { 2556 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true); 2557 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 2558 ServiceManager.addService("meminfo", new MemBinder(this)); 2559 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 2560 ServiceManager.addService("dbinfo", new DbBinder(this)); 2561 if (MONITOR_CPU_USAGE) { 2562 ServiceManager.addService("cpuinfo", new CpuBinder(this)); 2563 } 2564 ServiceManager.addService("permission", new PermissionController(this)); 2565 ServiceManager.addService("processinfo", new ProcessInfoService(this)); 2566 2567 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 2568 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); 2569 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 2570 2571 synchronized (this) { 2572 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0); 2573 app.persistent = true; 2574 app.pid = MY_PID; 2575 app.maxAdj = ProcessList.SYSTEM_ADJ; 2576 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 2577 synchronized (mPidsSelfLocked) { 2578 mPidsSelfLocked.put(app.pid, app); 2579 } 2580 updateLruProcessLocked(app, false, null); 2581 updateOomAdjLocked(); 2582 } 2583 } catch (PackageManager.NameNotFoundException e) { 2584 throw new RuntimeException( 2585 "Unable to find android system package", e); 2586 } 2587 } 2588 2589 public void setWindowManager(WindowManagerService wm) { 2590 mWindowManager = wm; 2591 mStackSupervisor.setWindowManager(wm); 2592 mActivityStarter.setWindowManager(wm); 2593 } 2594 2595 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) { 2596 mUsageStatsService = usageStatsManager; 2597 } 2598 2599 public void startObservingNativeCrashes() { 2600 final NativeCrashListener ncl = new NativeCrashListener(this); 2601 ncl.start(); 2602 } 2603 2604 public IAppOpsService getAppOpsService() { 2605 return mAppOpsService; 2606 } 2607 2608 static class MemBinder extends Binder { 2609 ActivityManagerService mActivityManagerService; 2610 MemBinder(ActivityManagerService activityManagerService) { 2611 mActivityManagerService = activityManagerService; 2612 } 2613 2614 @Override 2615 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2616 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2617 "meminfo", pw)) return; 2618 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, false, null); 2619 } 2620 } 2621 2622 static class GraphicsBinder extends Binder { 2623 ActivityManagerService mActivityManagerService; 2624 GraphicsBinder(ActivityManagerService activityManagerService) { 2625 mActivityManagerService = activityManagerService; 2626 } 2627 2628 @Override 2629 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2630 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2631 "gfxinfo", pw)) return; 2632 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 2633 } 2634 } 2635 2636 static class DbBinder extends Binder { 2637 ActivityManagerService mActivityManagerService; 2638 DbBinder(ActivityManagerService activityManagerService) { 2639 mActivityManagerService = activityManagerService; 2640 } 2641 2642 @Override 2643 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2644 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2645 "dbinfo", pw)) return; 2646 mActivityManagerService.dumpDbInfo(fd, pw, args); 2647 } 2648 } 2649 2650 static class CpuBinder extends Binder { 2651 ActivityManagerService mActivityManagerService; 2652 CpuBinder(ActivityManagerService activityManagerService) { 2653 mActivityManagerService = activityManagerService; 2654 } 2655 2656 @Override 2657 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2658 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 2659 "cpuinfo", pw)) return; 2660 synchronized (mActivityManagerService.mProcessCpuTracker) { 2661 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad()); 2662 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState( 2663 SystemClock.uptimeMillis())); 2664 } 2665 } 2666 } 2667 2668 public static final class Lifecycle extends SystemService { 2669 private final ActivityManagerService mService; 2670 2671 public Lifecycle(Context context) { 2672 super(context); 2673 mService = new ActivityManagerService(context); 2674 } 2675 2676 @Override 2677 public void onStart() { 2678 mService.start(); 2679 } 2680 2681 public ActivityManagerService getService() { 2682 return mService; 2683 } 2684 } 2685 2686 @VisibleForTesting 2687 public ActivityManagerService(Injector injector) { 2688 mInjector = injector; 2689 mContext = mInjector.getContext(); 2690 mUiContext = null; 2691 GL_ES_VERSION = 0; 2692 mActivityStarter = null; 2693 mAppErrors = null; 2694 mAppOpsService = mInjector.getAppOpsService(null, null); 2695 mBatteryStatsService = null; 2696 mCompatModePackages = null; 2697 mConstants = null; 2698 mGrantFile = null; 2699 mHandler = null; 2700 mHandlerThread = null; 2701 mIntentFirewall = null; 2702 mKeyguardController = null; 2703 mPermissionReviewRequired = false; 2704 mProcessCpuThread = null; 2705 mProcessStats = null; 2706 mProviderMap = null; 2707 mRecentTasks = null; 2708 mServices = null; 2709 mStackSupervisor = null; 2710 mSystemThread = null; 2711 mTaskChangeNotificationController = null; 2712 mUiHandler = injector.getUiHandler(null); 2713 mUserController = null; 2714 mVrController = null; 2715 } 2716 2717 // Note: This method is invoked on the main thread but may need to attach various 2718 // handlers to other threads. So take care to be explicit about the looper. 2719 public ActivityManagerService(Context systemContext) { 2720 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); 2721 mInjector = new Injector(); 2722 mContext = systemContext; 2723 2724 mFactoryTest = FactoryTest.getMode(); 2725 mSystemThread = ActivityThread.currentActivityThread(); 2726 mUiContext = mSystemThread.getSystemUiContext(); 2727 2728 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2729 2730 mPermissionReviewRequired = mContext.getResources().getBoolean( 2731 com.android.internal.R.bool.config_permissionReviewRequired); 2732 2733 mHandlerThread = new ServiceThread(TAG, 2734 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2735 mHandlerThread.start(); 2736 mHandler = new MainHandler(mHandlerThread.getLooper()); 2737 mUiHandler = mInjector.getUiHandler(this); 2738 2739 mConstants = new ActivityManagerConstants(this, mHandler); 2740 2741 /* static; one-time init here */ 2742 if (sKillHandler == null) { 2743 sKillThread = new ServiceThread(TAG + ":kill", 2744 THREAD_PRIORITY_BACKGROUND, true /* allowIo */); 2745 sKillThread.start(); 2746 sKillHandler = new KillHandler(sKillThread.getLooper()); 2747 } 2748 2749 mFgBroadcastQueue = new BroadcastQueue(this, mHandler, 2750 "foreground", BROADCAST_FG_TIMEOUT, false); 2751 mBgBroadcastQueue = new BroadcastQueue(this, mHandler, 2752 "background", BROADCAST_BG_TIMEOUT, true); 2753 mBroadcastQueues[0] = mFgBroadcastQueue; 2754 mBroadcastQueues[1] = mBgBroadcastQueue; 2755 2756 mServices = new ActiveServices(this); 2757 mProviderMap = new ProviderMap(this); 2758 mAppErrors = new AppErrors(mUiContext, this); 2759 2760 // TODO: Move creation of battery stats service outside of activity manager service. 2761 File dataDir = Environment.getDataDirectory(); 2762 File systemDir = new File(dataDir, "system"); 2763 systemDir.mkdirs(); 2764 mBatteryStatsService = new BatteryStatsService(systemDir, mHandler); 2765 mBatteryStatsService.getActiveStatistics().readLocked(); 2766 mBatteryStatsService.scheduleWriteToDisk(); 2767 mOnBattery = DEBUG_POWER ? true 2768 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2769 mBatteryStatsService.getActiveStatistics().setCallback(this); 2770 2771 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2772 2773 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler); 2774 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null, 2775 new IAppOpsCallback.Stub() { 2776 @Override public void opChanged(int op, int uid, String packageName) { 2777 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) { 2778 if (mAppOpsService.checkOperation(op, uid, packageName) 2779 != AppOpsManager.MODE_ALLOWED) { 2780 runInBackgroundDisabled(uid); 2781 } 2782 } 2783 } 2784 }); 2785 2786 mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml")); 2787 2788 mUserController = new UserController(this); 2789 2790 mVrController = new VrController(this); 2791 2792 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", 2793 ConfigurationInfo.GL_ES_VERSION_UNDEFINED); 2794 2795 if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) { 2796 mUseFifoUiScheduling = true; 2797 } 2798 2799 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations")); 2800 mTempConfig.setToDefaults(); 2801 mTempConfig.setLocales(LocaleList.getDefault()); 2802 mConfigurationSeq = mTempConfig.seq = 1; 2803 mStackSupervisor = createStackSupervisor(); 2804 mStackSupervisor.onConfigurationChanged(mTempConfig); 2805 mKeyguardController = mStackSupervisor.mKeyguardController; 2806 mCompatModePackages = new CompatModePackages(this, systemDir, mHandler); 2807 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2808 mTaskChangeNotificationController = 2809 new TaskChangeNotificationController(this, mStackSupervisor, mHandler); 2810 mActivityStarter = new ActivityStarter(this, mStackSupervisor); 2811 mRecentTasks = new RecentTasks(this, mStackSupervisor); 2812 2813 mProcessCpuThread = new Thread("CpuTracker") { 2814 @Override 2815 public void run() { 2816 synchronized (mProcessCpuTracker) { 2817 mProcessCpuInitLatch.countDown(); 2818 mProcessCpuTracker.init(); 2819 } 2820 while (true) { 2821 try { 2822 try { 2823 synchronized(this) { 2824 final long now = SystemClock.uptimeMillis(); 2825 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 2826 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 2827 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 2828 // + ", write delay=" + nextWriteDelay); 2829 if (nextWriteDelay < nextCpuDelay) { 2830 nextCpuDelay = nextWriteDelay; 2831 } 2832 if (nextCpuDelay > 0) { 2833 mProcessCpuMutexFree.set(true); 2834 this.wait(nextCpuDelay); 2835 } 2836 } 2837 } catch (InterruptedException e) { 2838 } 2839 updateCpuStatsNow(); 2840 } catch (Exception e) { 2841 Slog.e(TAG, "Unexpected exception collecting process stats", e); 2842 } 2843 } 2844 } 2845 }; 2846 2847 Watchdog.getInstance().addMonitor(this); 2848 Watchdog.getInstance().addThread(mHandler); 2849 } 2850 2851 protected ActivityStackSupervisor createStackSupervisor() { 2852 return new ActivityStackSupervisor(this, mHandler.getLooper()); 2853 } 2854 2855 public void setSystemServiceManager(SystemServiceManager mgr) { 2856 mSystemServiceManager = mgr; 2857 } 2858 2859 public void setInstaller(Installer installer) { 2860 mInstaller = installer; 2861 } 2862 2863 private void start() { 2864 removeAllProcessGroups(); 2865 mProcessCpuThread.start(); 2866 2867 mBatteryStatsService.publish(mContext); 2868 mAppOpsService.publish(mContext); 2869 Slog.d("AppOps", "AppOpsService published"); 2870 LocalServices.addService(ActivityManagerInternal.class, new LocalService()); 2871 // Wait for the synchronized block started in mProcessCpuThread, 2872 // so that any other acccess to mProcessCpuTracker from main thread 2873 // will be blocked during mProcessCpuTracker initialization. 2874 try { 2875 mProcessCpuInitLatch.await(); 2876 } catch (InterruptedException e) { 2877 Slog.wtf(TAG, "Interrupted wait during start", e); 2878 Thread.currentThread().interrupt(); 2879 throw new IllegalStateException("Interrupted wait during start"); 2880 } 2881 } 2882 2883 void onUserStoppedLocked(int userId) { 2884 mRecentTasks.unloadUserDataFromMemoryLocked(userId); 2885 } 2886 2887 public void initPowerManagement() { 2888 mStackSupervisor.initPowerManagement(); 2889 mBatteryStatsService.initPowerManagement(); 2890 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); 2891 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); 2892 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*"); 2893 mVoiceWakeLock.setReferenceCounted(false); 2894 } 2895 2896 private ArraySet<String> getBackgroundLaunchBroadcasts() { 2897 if (mBackgroundLaunchBroadcasts == null) { 2898 mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts(); 2899 } 2900 return mBackgroundLaunchBroadcasts; 2901 } 2902 2903 @Override 2904 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2905 throws RemoteException { 2906 if (code == SYSPROPS_TRANSACTION) { 2907 // We need to tell all apps about the system property change. 2908 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2909 synchronized(this) { 2910 final int NP = mProcessNames.getMap().size(); 2911 for (int ip=0; ip<NP; ip++) { 2912 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 2913 final int NA = apps.size(); 2914 for (int ia=0; ia<NA; ia++) { 2915 ProcessRecord app = apps.valueAt(ia); 2916 if (app.thread != null) { 2917 procs.add(app.thread.asBinder()); 2918 } 2919 } 2920 } 2921 } 2922 2923 int N = procs.size(); 2924 for (int i=0; i<N; i++) { 2925 Parcel data2 = Parcel.obtain(); 2926 try { 2927 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 2928 Binder.FLAG_ONEWAY); 2929 } catch (RemoteException e) { 2930 } 2931 data2.recycle(); 2932 } 2933 } 2934 try { 2935 return super.onTransact(code, data, reply, flags); 2936 } catch (RuntimeException e) { 2937 // The activity manager only throws security exceptions, so let's 2938 // log all others. 2939 if (!(e instanceof SecurityException)) { 2940 Slog.wtf(TAG, "Activity Manager Crash." 2941 + " UID:" + Binder.getCallingUid() 2942 + " PID:" + Binder.getCallingPid() 2943 + " TRANS:" + code, e); 2944 } 2945 throw e; 2946 } 2947 } 2948 2949 void updateCpuStats() { 2950 final long now = SystemClock.uptimeMillis(); 2951 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 2952 return; 2953 } 2954 if (mProcessCpuMutexFree.compareAndSet(true, false)) { 2955 synchronized (mProcessCpuThread) { 2956 mProcessCpuThread.notify(); 2957 } 2958 } 2959 } 2960 2961 void updateCpuStatsNow() { 2962 synchronized (mProcessCpuTracker) { 2963 mProcessCpuMutexFree.set(false); 2964 final long now = SystemClock.uptimeMillis(); 2965 boolean haveNewCpuStats = false; 2966 2967 if (MONITOR_CPU_USAGE && 2968 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 2969 mLastCpuTime.set(now); 2970 mProcessCpuTracker.update(); 2971 if (mProcessCpuTracker.hasGoodLastStats()) { 2972 haveNewCpuStats = true; 2973 //Slog.i(TAG, mProcessCpu.printCurrentState()); 2974 //Slog.i(TAG, "Total CPU usage: " 2975 // + mProcessCpu.getTotalCpuPercent() + "%"); 2976 2977 // Slog the cpu usage if the property is set. 2978 if ("true".equals(SystemProperties.get("events.cpu"))) { 2979 int user = mProcessCpuTracker.getLastUserTime(); 2980 int system = mProcessCpuTracker.getLastSystemTime(); 2981 int iowait = mProcessCpuTracker.getLastIoWaitTime(); 2982 int irq = mProcessCpuTracker.getLastIrqTime(); 2983 int softIrq = mProcessCpuTracker.getLastSoftIrqTime(); 2984 int idle = mProcessCpuTracker.getLastIdleTime(); 2985 2986 int total = user + system + iowait + irq + softIrq + idle; 2987 if (total == 0) total = 1; 2988 2989 EventLog.writeEvent(EventLogTags.CPU, 2990 ((user+system+iowait+irq+softIrq) * 100) / total, 2991 (user * 100) / total, 2992 (system * 100) / total, 2993 (iowait * 100) / total, 2994 (irq * 100) / total, 2995 (softIrq * 100) / total); 2996 } 2997 } 2998 } 2999 3000 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 3001 synchronized(bstats) { 3002 synchronized(mPidsSelfLocked) { 3003 if (haveNewCpuStats) { 3004 if (bstats.startAddingCpuLocked()) { 3005 int totalUTime = 0; 3006 int totalSTime = 0; 3007 final int N = mProcessCpuTracker.countStats(); 3008 for (int i=0; i<N; i++) { 3009 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 3010 if (!st.working) { 3011 continue; 3012 } 3013 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 3014 totalUTime += st.rel_utime; 3015 totalSTime += st.rel_stime; 3016 if (pr != null) { 3017 BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats; 3018 if (ps == null || !ps.isActive()) { 3019 pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked( 3020 pr.info.uid, pr.processName); 3021 } 3022 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime); 3023 pr.curCpuTime += st.rel_utime + st.rel_stime; 3024 } else { 3025 BatteryStatsImpl.Uid.Proc ps = st.batteryStats; 3026 if (ps == null || !ps.isActive()) { 3027 st.batteryStats = ps = bstats.getProcessStatsLocked( 3028 bstats.mapUid(st.uid), st.name); 3029 } 3030 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime); 3031 } 3032 } 3033 final int userTime = mProcessCpuTracker.getLastUserTime(); 3034 final int systemTime = mProcessCpuTracker.getLastSystemTime(); 3035 final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime(); 3036 final int irqTime = mProcessCpuTracker.getLastIrqTime(); 3037 final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime(); 3038 final int idleTime = mProcessCpuTracker.getLastIdleTime(); 3039 bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime, 3040 systemTime, iowaitTime, irqTime, softIrqTime, idleTime); 3041 } 3042 } 3043 } 3044 3045 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 3046 mLastWriteTime = now; 3047 mBatteryStatsService.scheduleWriteToDisk(); 3048 } 3049 } 3050 } 3051 } 3052 3053 @Override 3054 public void batteryNeedsCpuUpdate() { 3055 updateCpuStatsNow(); 3056 } 3057 3058 @Override 3059 public void batteryPowerChanged(boolean onBattery) { 3060 // When plugging in, update the CPU stats first before changing 3061 // the plug state. 3062 updateCpuStatsNow(); 3063 synchronized (this) { 3064 synchronized(mPidsSelfLocked) { 3065 mOnBattery = DEBUG_POWER ? true : onBattery; 3066 } 3067 } 3068 } 3069 3070 @Override 3071 public void batterySendBroadcast(Intent intent) { 3072 synchronized (this) { 3073 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 3074 AppOpsManager.OP_NONE, null, false, false, 3075 -1, SYSTEM_UID, UserHandle.USER_ALL); 3076 } 3077 } 3078 3079 /** 3080 * Initialize the application bind args. These are passed to each 3081 * process when the bindApplication() IPC is sent to the process. They're 3082 * lazily setup to make sure the services are running when they're asked for. 3083 */ 3084 private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) { 3085 // Isolated processes won't get this optimization, so that we don't 3086 // violate the rules about which services they have access to. 3087 if (isolated) { 3088 if (mIsolatedAppBindArgs == null) { 3089 mIsolatedAppBindArgs = new HashMap<>(); 3090 mIsolatedAppBindArgs.put("package", ServiceManager.getService("package")); 3091 } 3092 return mIsolatedAppBindArgs; 3093 } 3094 3095 if (mAppBindArgs == null) { 3096 mAppBindArgs = new HashMap<>(); 3097 3098 // Setup the application init args 3099 mAppBindArgs.put("package", ServiceManager.getService("package")); 3100 mAppBindArgs.put("window", ServiceManager.getService("window")); 3101 mAppBindArgs.put(Context.ALARM_SERVICE, 3102 ServiceManager.getService(Context.ALARM_SERVICE)); 3103 } 3104 return mAppBindArgs; 3105 } 3106 3107 /** 3108 * Update AMS states when an activity is resumed. This should only be called by 3109 * {@link ActivityStack#setResumedActivityLocked} when an activity is resumed. 3110 */ 3111 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) { 3112 final TaskRecord task = r.getTask(); 3113 if (task.isApplicationTask()) { 3114 if (mCurAppTimeTracker != r.appTimeTracker) { 3115 // We are switching app tracking. Complete the current one. 3116 if (mCurAppTimeTracker != null) { 3117 mCurAppTimeTracker.stop(); 3118 mHandler.obtainMessage( 3119 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget(); 3120 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker); 3121 mCurAppTimeTracker = null; 3122 } 3123 if (r.appTimeTracker != null) { 3124 mCurAppTimeTracker = r.appTimeTracker; 3125 startTimeTrackingFocusedActivityLocked(); 3126 } 3127 } else { 3128 startTimeTrackingFocusedActivityLocked(); 3129 } 3130 } else { 3131 r.appTimeTracker = null; 3132 } 3133 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null 3134 // TODO: Probably not, because we don't want to resume voice on switching 3135 // back to this activity 3136 if (task.voiceInteractor != null) { 3137 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid); 3138 } else { 3139 finishRunningVoiceLocked(); 3140 3141 if (mLastResumedActivity != null) { 3142 final IVoiceInteractionSession session; 3143 3144 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask(); 3145 if (lastResumedActivityTask != null 3146 && lastResumedActivityTask.voiceSession != null) { 3147 session = lastResumedActivityTask.voiceSession; 3148 } else { 3149 session = mLastResumedActivity.voiceSession; 3150 } 3151 3152 if (session != null) { 3153 // We had been in a voice interaction session, but now focused has 3154 // move to something different. Just finish the session, we can't 3155 // return to it and retain the proper state and synchronization with 3156 // the voice interaction service. 3157 finishVoiceTask(session); 3158 } 3159 } 3160 } 3161 3162 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) { 3163 mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG); 3164 mHandler.obtainMessage( 3165 FOREGROUND_PROFILE_CHANGED_MSG, r.userId, 0).sendToTarget(); 3166 } 3167 mLastResumedActivity = r; 3168 3169 mWindowManager.setFocusedApp(r.appToken, true); 3170 3171 applyUpdateLockStateLocked(r); 3172 applyUpdateVrModeLocked(r); 3173 3174 EventLogTags.writeAmSetResumedActivity( 3175 r == null ? -1 : r.userId, 3176 r == null ? "NULL" : r.shortComponentName, 3177 reason); 3178 } 3179 3180 @Override 3181 public void setFocusedStack(int stackId) { 3182 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()"); 3183 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId); 3184 final long callingId = Binder.clearCallingIdentity(); 3185 try { 3186 synchronized (this) { 3187 final ActivityStack stack = mStackSupervisor.getStack(stackId); 3188 if (stack == null) { 3189 return; 3190 } 3191 final ActivityRecord r = stack.topRunningActivityLocked(); 3192 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedStack")) { 3193 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 3194 } 3195 } 3196 } finally { 3197 Binder.restoreCallingIdentity(callingId); 3198 } 3199 } 3200 3201 @Override 3202 public void setFocusedTask(int taskId) { 3203 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()"); 3204 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId); 3205 final long callingId = Binder.clearCallingIdentity(); 3206 try { 3207 synchronized (this) { 3208 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 3209 if (task == null) { 3210 return; 3211 } 3212 final ActivityRecord r = task.topRunningActivityLocked(); 3213 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedTask")) { 3214 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 3215 } 3216 } 3217 } finally { 3218 Binder.restoreCallingIdentity(callingId); 3219 } 3220 } 3221 3222 /** Sets the task stack listener that gets callbacks when a task stack changes. */ 3223 @Override 3224 public void registerTaskStackListener(ITaskStackListener listener) throws RemoteException { 3225 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "registerTaskStackListener()"); 3226 mTaskChangeNotificationController.registerTaskStackListener(listener); 3227 } 3228 3229 /** 3230 * Unregister a task stack listener so that it stops receiving callbacks. 3231 */ 3232 @Override 3233 public void unregisterTaskStackListener(ITaskStackListener listener) throws RemoteException { 3234 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "unregisterTaskStackListener()"); 3235 mTaskChangeNotificationController.unregisterTaskStackListener(listener); 3236 } 3237 3238 @Override 3239 public void notifyActivityDrawn(IBinder token) { 3240 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token); 3241 synchronized (this) { 3242 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token); 3243 if (r != null) { 3244 r.getStack().notifyActivityDrawnLocked(r); 3245 } 3246 } 3247 } 3248 3249 final void applyUpdateLockStateLocked(ActivityRecord r) { 3250 // Modifications to the UpdateLock state are done on our handler, outside 3251 // the activity manager's locks. The new state is determined based on the 3252 // state *now* of the relevant activity record. The object is passed to 3253 // the handler solely for logging detail, not to be consulted/modified. 3254 final boolean nextState = r != null && r.immersive; 3255 mHandler.sendMessage( 3256 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r)); 3257 } 3258 3259 final void applyUpdateVrModeLocked(ActivityRecord r) { 3260 mHandler.sendMessage( 3261 mHandler.obtainMessage(VR_MODE_CHANGE_MSG, 0, 0, r)); 3262 } 3263 3264 private void sendNotifyVrManagerOfSleepState(boolean isSleeping) { 3265 mHandler.sendMessage( 3266 mHandler.obtainMessage(NOTIFY_VR_SLEEPING_MSG, isSleeping ? 1 : 0, 0)); 3267 } 3268 3269 private void notifyVrManagerOfSleepState(boolean isSleeping) { 3270 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); 3271 if (vrService == null) { 3272 return; 3273 } 3274 vrService.onSleepStateChanged(isSleeping); 3275 } 3276 3277 final void showAskCompatModeDialogLocked(ActivityRecord r) { 3278 Message msg = Message.obtain(); 3279 msg.what = SHOW_COMPAT_MODE_DIALOG_UI_MSG; 3280 msg.obj = r.getTask().askedCompatMode ? null : r; 3281 mUiHandler.sendMessage(msg); 3282 } 3283 3284 final void showUnsupportedZoomDialogIfNeededLocked(ActivityRecord r) { 3285 final Configuration globalConfig = getGlobalConfiguration(); 3286 if (globalConfig.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE 3287 && r.appInfo.requiresSmallestWidthDp > globalConfig.smallestScreenWidthDp) { 3288 final Message msg = Message.obtain(); 3289 msg.what = SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG; 3290 msg.obj = r; 3291 mUiHandler.sendMessage(msg); 3292 } 3293 } 3294 3295 private int updateLruProcessInternalLocked(ProcessRecord app, long now, int index, 3296 String what, Object obj, ProcessRecord srcApp) { 3297 app.lastActivityTime = now; 3298 3299 if (app.activities.size() > 0) { 3300 // Don't want to touch dependent processes that are hosting activities. 3301 return index; 3302 } 3303 3304 int lrui = mLruProcesses.lastIndexOf(app); 3305 if (lrui < 0) { 3306 Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: " 3307 + what + " " + obj + " from " + srcApp); 3308 return index; 3309 } 3310 3311 if (lrui >= index) { 3312 // Don't want to cause this to move dependent processes *back* in the 3313 // list as if they were less frequently used. 3314 return index; 3315 } 3316 3317 if (lrui >= mLruProcessActivityStart) { 3318 // Don't want to touch dependent processes that are hosting activities. 3319 return index; 3320 } 3321 3322 mLruProcesses.remove(lrui); 3323 if (index > 0) { 3324 index--; 3325 } 3326 if (DEBUG_LRU) Slog.d(TAG_LRU, "Moving dep from " + lrui + " to " + index 3327 + " in LRU list: " + app); 3328 mLruProcesses.add(index, app); 3329 return index; 3330 } 3331 3332 static void killProcessGroup(int uid, int pid) { 3333 if (sKillHandler != null) { 3334 sKillHandler.sendMessage( 3335 sKillHandler.obtainMessage(KillHandler.KILL_PROCESS_GROUP_MSG, uid, pid)); 3336 } else { 3337 Slog.w(TAG, "Asked to kill process group before system bringup!"); 3338 Process.killProcessGroup(uid, pid); 3339 } 3340 } 3341 3342 final void removeLruProcessLocked(ProcessRecord app) { 3343 int lrui = mLruProcesses.lastIndexOf(app); 3344 if (lrui >= 0) { 3345 if (!app.killed) { 3346 Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app); 3347 killProcessQuiet(app.pid); 3348 killProcessGroup(app.uid, app.pid); 3349 } 3350 if (lrui <= mLruProcessActivityStart) { 3351 mLruProcessActivityStart--; 3352 } 3353 if (lrui <= mLruProcessServiceStart) { 3354 mLruProcessServiceStart--; 3355 } 3356 mLruProcesses.remove(lrui); 3357 } 3358 } 3359 3360 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 3361 ProcessRecord client) { 3362 final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities 3363 || app.treatLikeActivity; 3364 final boolean hasService = false; // not impl yet. app.services.size() > 0; 3365 if (!activityChange && hasActivity) { 3366 // The process has activities, so we are only allowing activity-based adjustments 3367 // to move it. It should be kept in the front of the list with other 3368 // processes that have activities, and we don't want those to change their 3369 // order except due to activity operations. 3370 return; 3371 } 3372 3373 mLruSeq++; 3374 final long now = SystemClock.uptimeMillis(); 3375 app.lastActivityTime = now; 3376 3377 // First a quick reject: if the app is already at the position we will 3378 // put it, then there is nothing to do. 3379 if (hasActivity) { 3380 final int N = mLruProcesses.size(); 3381 if (N > 0 && mLruProcesses.get(N-1) == app) { 3382 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top activity: " + app); 3383 return; 3384 } 3385 } else { 3386 if (mLruProcessServiceStart > 0 3387 && mLruProcesses.get(mLruProcessServiceStart-1) == app) { 3388 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top other: " + app); 3389 return; 3390 } 3391 } 3392 3393 int lrui = mLruProcesses.lastIndexOf(app); 3394 3395 if (app.persistent && lrui >= 0) { 3396 // We don't care about the position of persistent processes, as long as 3397 // they are in the list. 3398 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, persistent: " + app); 3399 return; 3400 } 3401 3402 /* In progress: compute new position first, so we can avoid doing work 3403 if the process is not actually going to move. Not yet working. 3404 int addIndex; 3405 int nextIndex; 3406 boolean inActivity = false, inService = false; 3407 if (hasActivity) { 3408 // Process has activities, put it at the very tipsy-top. 3409 addIndex = mLruProcesses.size(); 3410 nextIndex = mLruProcessServiceStart; 3411 inActivity = true; 3412 } else if (hasService) { 3413 // Process has services, put it at the top of the service list. 3414 addIndex = mLruProcessActivityStart; 3415 nextIndex = mLruProcessServiceStart; 3416 inActivity = true; 3417 inService = true; 3418 } else { 3419 // Process not otherwise of interest, it goes to the top of the non-service area. 3420 addIndex = mLruProcessServiceStart; 3421 if (client != null) { 3422 int clientIndex = mLruProcesses.lastIndexOf(client); 3423 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating " 3424 + app); 3425 if (clientIndex >= 0 && addIndex > clientIndex) { 3426 addIndex = clientIndex; 3427 } 3428 } 3429 nextIndex = addIndex > 0 ? addIndex-1 : addIndex; 3430 } 3431 3432 Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act=" 3433 + mLruProcessActivityStart + "): " + app); 3434 */ 3435 3436 if (lrui >= 0) { 3437 if (lrui < mLruProcessActivityStart) { 3438 mLruProcessActivityStart--; 3439 } 3440 if (lrui < mLruProcessServiceStart) { 3441 mLruProcessServiceStart--; 3442 } 3443 /* 3444 if (addIndex > lrui) { 3445 addIndex--; 3446 } 3447 if (nextIndex > lrui) { 3448 nextIndex--; 3449 } 3450 */ 3451 mLruProcesses.remove(lrui); 3452 } 3453 3454 /* 3455 mLruProcesses.add(addIndex, app); 3456 if (inActivity) { 3457 mLruProcessActivityStart++; 3458 } 3459 if (inService) { 3460 mLruProcessActivityStart++; 3461 } 3462 */ 3463 3464 int nextIndex; 3465 if (hasActivity) { 3466 final int N = mLruProcesses.size(); 3467 if (app.activities.size() == 0 && mLruProcessActivityStart < (N - 1)) { 3468 // Process doesn't have activities, but has clients with 3469 // activities... move it up, but one below the top (the top 3470 // should always have a real activity). 3471 if (DEBUG_LRU) Slog.d(TAG_LRU, 3472 "Adding to second-top of LRU activity list: " + app); 3473 mLruProcesses.add(N - 1, app); 3474 // To keep it from spamming the LRU list (by making a bunch of clients), 3475 // we will push down any other entries owned by the app. 3476 final int uid = app.info.uid; 3477 for (int i = N - 2; i > mLruProcessActivityStart; i--) { 3478 ProcessRecord subProc = mLruProcesses.get(i); 3479 if (subProc.info.uid == uid) { 3480 // We want to push this one down the list. If the process after 3481 // it is for the same uid, however, don't do so, because we don't 3482 // want them internally to be re-ordered. 3483 if (mLruProcesses.get(i - 1).info.uid != uid) { 3484 if (DEBUG_LRU) Slog.d(TAG_LRU, 3485 "Pushing uid " + uid + " swapping at " + i + ": " 3486 + mLruProcesses.get(i) + " : " + mLruProcesses.get(i - 1)); 3487 ProcessRecord tmp = mLruProcesses.get(i); 3488 mLruProcesses.set(i, mLruProcesses.get(i - 1)); 3489 mLruProcesses.set(i - 1, tmp); 3490 i--; 3491 } 3492 } else { 3493 // A gap, we can stop here. 3494 break; 3495 } 3496 } 3497 } else { 3498 // Process has activities, put it at the very tipsy-top. 3499 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU activity list: " + app); 3500 mLruProcesses.add(app); 3501 } 3502 nextIndex = mLruProcessServiceStart; 3503 } else if (hasService) { 3504 // Process has services, put it at the top of the service list. 3505 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU service list: " + app); 3506 mLruProcesses.add(mLruProcessActivityStart, app); 3507 nextIndex = mLruProcessServiceStart; 3508 mLruProcessActivityStart++; 3509 } else { 3510 // Process not otherwise of interest, it goes to the top of the non-service area. 3511 int index = mLruProcessServiceStart; 3512 if (client != null) { 3513 // If there is a client, don't allow the process to be moved up higher 3514 // in the list than that client. 3515 int clientIndex = mLruProcesses.lastIndexOf(client); 3516 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG_LRU, "Unknown client " + client 3517 + " when updating " + app); 3518 if (clientIndex <= lrui) { 3519 // Don't allow the client index restriction to push it down farther in the 3520 // list than it already is. 3521 clientIndex = lrui; 3522 } 3523 if (clientIndex >= 0 && index > clientIndex) { 3524 index = clientIndex; 3525 } 3526 } 3527 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding at " + index + " of LRU list: " + app); 3528 mLruProcesses.add(index, app); 3529 nextIndex = index-1; 3530 mLruProcessActivityStart++; 3531 mLruProcessServiceStart++; 3532 } 3533 3534 // If the app is currently using a content provider or service, 3535 // bump those processes as well. 3536 for (int j=app.connections.size()-1; j>=0; j--) { 3537 ConnectionRecord cr = app.connections.valueAt(j); 3538 if (cr.binding != null && !cr.serviceDead && cr.binding.service != null 3539 && cr.binding.service.app != null 3540 && cr.binding.service.app.lruSeq != mLruSeq 3541 && !cr.binding.service.app.persistent) { 3542 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex, 3543 "service connection", cr, app); 3544 } 3545 } 3546 for (int j=app.conProviders.size()-1; j>=0; j--) { 3547 ContentProviderRecord cpr = app.conProviders.get(j).provider; 3548 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) { 3549 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex, 3550 "provider reference", cpr, app); 3551 } 3552 } 3553 } 3554 3555 final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) { 3556 if (uid == SYSTEM_UID) { 3557 // The system gets to run in any process. If there are multiple 3558 // processes with the same uid, just pick the first (this 3559 // should never happen). 3560 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName); 3561 if (procs == null) return null; 3562 final int procCount = procs.size(); 3563 for (int i = 0; i < procCount; i++) { 3564 final int procUid = procs.keyAt(i); 3565 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) { 3566 // Don't use an app process or different user process for system component. 3567 continue; 3568 } 3569 return procs.valueAt(i); 3570 } 3571 } 3572 ProcessRecord proc = mProcessNames.get(processName, uid); 3573 if (false && proc != null && !keepIfLarge 3574 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY 3575 && proc.lastCachedPss >= 4000) { 3576 // Turn this condition on to cause killing to happen regularly, for testing. 3577 if (proc.baseProcessTracker != null) { 3578 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 3579 } 3580 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 3581 } else if (proc != null && !keepIfLarge 3582 && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 3583 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 3584 if (DEBUG_PSS) Slog.d(TAG_PSS, "May not keep " + proc + ": pss=" + proc.lastCachedPss); 3585 if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) { 3586 if (proc.baseProcessTracker != null) { 3587 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 3588 } 3589 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 3590 } 3591 } 3592 return proc; 3593 } 3594 3595 void notifyPackageUse(String packageName, int reason) { 3596 IPackageManager pm = AppGlobals.getPackageManager(); 3597 try { 3598 pm.notifyPackageUse(packageName, reason); 3599 } catch (RemoteException e) { 3600 } 3601 } 3602 3603 boolean isNextTransitionForward() { 3604 int transit = mWindowManager.getPendingAppTransition(); 3605 return transit == TRANSIT_ACTIVITY_OPEN 3606 || transit == TRANSIT_TASK_OPEN 3607 || transit == TRANSIT_TASK_TO_FRONT; 3608 } 3609 3610 int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 3611 String processName, String abiOverride, int uid, Runnable crashHandler) { 3612 synchronized(this) { 3613 ApplicationInfo info = new ApplicationInfo(); 3614 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 3615 // For isolated processes, the former contains the parent's uid and the latter the 3616 // actual uid of the isolated process. 3617 // In the special case introduced by this method (which is, starting an isolated 3618 // process directly from the SystemServer without an actual parent app process) the 3619 // closest thing to a parent's uid is SYSTEM_UID. 3620 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 3621 // the |isolated| logic in the ProcessRecord constructor. 3622 info.uid = SYSTEM_UID; 3623 info.processName = processName; 3624 info.className = entryPoint; 3625 info.packageName = "android"; 3626 info.seInfoUser = SELinuxUtil.COMPLETE_STR; 3627 ProcessRecord proc = startProcessLocked(processName, info /* info */, 3628 false /* knownToBeDead */, 0 /* intentFlags */, "" /* hostingType */, 3629 null /* hostingName */, true /* allowWhileBooting */, true /* isolated */, 3630 uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs, 3631 crashHandler); 3632 return proc != null ? proc.pid : 0; 3633 } 3634 } 3635 3636 final ProcessRecord startProcessLocked(String processName, 3637 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 3638 String hostingType, ComponentName hostingName, boolean allowWhileBooting, 3639 boolean isolated, boolean keepIfLarge) { 3640 return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType, 3641 hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge, 3642 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */, 3643 null /* crashHandler */); 3644 } 3645 3646 final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, 3647 boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, 3648 boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge, 3649 String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) { 3650 long startTime = SystemClock.elapsedRealtime(); 3651 ProcessRecord app; 3652 if (!isolated) { 3653 app = getProcessRecordLocked(processName, info.uid, keepIfLarge); 3654 checkTime(startTime, "startProcess: after getProcessRecord"); 3655 3656 if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) { 3657 // If we are in the background, then check to see if this process 3658 // is bad. If so, we will just silently fail. 3659 if (mAppErrors.isBadProcessLocked(info)) { 3660 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 3661 + "/" + info.processName); 3662 return null; 3663 } 3664 } else { 3665 // When the user is explicitly starting a process, then clear its 3666 // crash count so that we won't make it bad until they see at 3667 // least one crash dialog again, and make the process good again 3668 // if it had been bad. 3669 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 3670 + "/" + info.processName); 3671 mAppErrors.resetProcessCrashTimeLocked(info); 3672 if (mAppErrors.isBadProcessLocked(info)) { 3673 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, 3674 UserHandle.getUserId(info.uid), info.uid, 3675 info.processName); 3676 mAppErrors.clearBadProcessLocked(info); 3677 if (app != null) { 3678 app.bad = false; 3679 } 3680 } 3681 } 3682 } else { 3683 // If this is an isolated process, it can't re-use an existing process. 3684 app = null; 3685 } 3686 3687 // We don't have to do anything more if: 3688 // (1) There is an existing application record; and 3689 // (2) The caller doesn't think it is dead, OR there is no thread 3690 // object attached to it so we know it couldn't have crashed; and 3691 // (3) There is a pid assigned to it, so it is either starting or 3692 // already running. 3693 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "startProcess: name=" + processName 3694 + " app=" + app + " knownToBeDead=" + knownToBeDead 3695 + " thread=" + (app != null ? app.thread : null) 3696 + " pid=" + (app != null ? app.pid : -1)); 3697 if (app != null && app.pid > 0) { 3698 if ((!knownToBeDead && !app.killed) || app.thread == null) { 3699 // We already have the app running, or are waiting for it to 3700 // come up (we have a pid but not yet its thread), so keep it. 3701 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App already running: " + app); 3702 // If this is a new package in the process, add the package to the list 3703 app.addPackage(info.packageName, info.versionCode, mProcessStats); 3704 checkTime(startTime, "startProcess: done, added package to proc"); 3705 return app; 3706 } 3707 3708 // An application record is attached to a previous process, 3709 // clean it up now. 3710 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_PROCESSES, "App died: " + app); 3711 checkTime(startTime, "startProcess: bad proc running, killing"); 3712 killProcessGroup(app.uid, app.pid); 3713 handleAppDiedLocked(app, true, true); 3714 checkTime(startTime, "startProcess: done killing old proc"); 3715 } 3716 3717 String hostingNameStr = hostingName != null 3718 ? hostingName.flattenToShortString() : null; 3719 3720 if (app == null) { 3721 checkTime(startTime, "startProcess: creating new process record"); 3722 app = newProcessRecordLocked(info, processName, isolated, isolatedUid); 3723 if (app == null) { 3724 Slog.w(TAG, "Failed making new process record for " 3725 + processName + "/" + info.uid + " isolated=" + isolated); 3726 return null; 3727 } 3728 app.crashHandler = crashHandler; 3729 checkTime(startTime, "startProcess: done creating new process record"); 3730 } else { 3731 // If this is a new package in the process, add the package to the list 3732 app.addPackage(info.packageName, info.versionCode, mProcessStats); 3733 checkTime(startTime, "startProcess: added package to existing proc"); 3734 } 3735 3736 // If the system is not ready yet, then hold off on starting this 3737 // process until it is. 3738 if (!mProcessesReady 3739 && !isAllowedWhileBooting(info) 3740 && !allowWhileBooting) { 3741 if (!mProcessesOnHold.contains(app)) { 3742 mProcessesOnHold.add(app); 3743 } 3744 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, 3745 "System not ready, putting on hold: " + app); 3746 checkTime(startTime, "startProcess: returning with proc on hold"); 3747 return app; 3748 } 3749 3750 checkTime(startTime, "startProcess: stepping in to startProcess"); 3751 startProcessLocked( 3752 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs); 3753 checkTime(startTime, "startProcess: done starting proc!"); 3754 return (app.pid != 0) ? app : null; 3755 } 3756 3757 boolean isAllowedWhileBooting(ApplicationInfo ai) { 3758 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 3759 } 3760 3761 private final void startProcessLocked(ProcessRecord app, 3762 String hostingType, String hostingNameStr) { 3763 startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */, 3764 null /* entryPoint */, null /* entryPointArgs */); 3765 } 3766 3767 private final void startProcessLocked(ProcessRecord app, String hostingType, 3768 String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) { 3769 long startTime = SystemClock.elapsedRealtime(); 3770 if (app.pid > 0 && app.pid != MY_PID) { 3771 checkTime(startTime, "startProcess: removing from pids map"); 3772 synchronized (mPidsSelfLocked) { 3773 mPidsSelfLocked.remove(app.pid); 3774 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 3775 } 3776 checkTime(startTime, "startProcess: done removing from pids map"); 3777 app.setPid(0); 3778 } 3779 3780 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, 3781 "startProcessLocked removing on hold: " + app); 3782 mProcessesOnHold.remove(app); 3783 3784 checkTime(startTime, "startProcess: starting to update cpu stats"); 3785 updateCpuStats(); 3786 checkTime(startTime, "startProcess: done updating cpu stats"); 3787 3788 try { 3789 try { 3790 final int userId = UserHandle.getUserId(app.uid); 3791 AppGlobals.getPackageManager().checkPackageStartable(app.info.packageName, userId); 3792 } catch (RemoteException e) { 3793 throw e.rethrowAsRuntimeException(); 3794 } 3795 3796 int uid = app.uid; 3797 int[] gids = null; 3798 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE; 3799 if (!app.isolated) { 3800 int[] permGids = null; 3801 try { 3802 checkTime(startTime, "startProcess: getting gids from package manager"); 3803 final IPackageManager pm = AppGlobals.getPackageManager(); 3804 permGids = pm.getPackageGids(app.info.packageName, 3805 MATCH_DEBUG_TRIAGED_MISSING, app.userId); 3806 StorageManagerInternal storageManagerInternal = LocalServices.getService( 3807 StorageManagerInternal.class); 3808 mountExternal = storageManagerInternal.getExternalStorageMountMode(uid, 3809 app.info.packageName); 3810 } catch (RemoteException e) { 3811 throw e.rethrowAsRuntimeException(); 3812 } 3813 3814 /* 3815 * Add shared application and profile GIDs so applications can share some 3816 * resources like shared libraries and access user-wide resources 3817 */ 3818 if (ArrayUtils.isEmpty(permGids)) { 3819 gids = new int[3]; 3820 } else { 3821 gids = new int[permGids.length + 3]; 3822 System.arraycopy(permGids, 0, gids, 3, permGids.length); 3823 } 3824 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid)); 3825 gids[1] = UserHandle.getCacheAppGid(UserHandle.getAppId(uid)); 3826 gids[2] = UserHandle.getUserGid(UserHandle.getUserId(uid)); 3827 } 3828 checkTime(startTime, "startProcess: building args"); 3829 if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) { 3830 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 3831 && mTopComponent != null 3832 && app.processName.equals(mTopComponent.getPackageName())) { 3833 uid = 0; 3834 } 3835 if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL 3836 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) { 3837 uid = 0; 3838 } 3839 } 3840 int debugFlags = 0; 3841 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 3842 debugFlags |= Zygote.DEBUG_ENABLE_JDWP; 3843 debugFlags |= Zygote.DEBUG_JAVA_DEBUGGABLE; 3844 // Also turn on CheckJNI for debuggable apps. It's quite 3845 // awkward to turn on otherwise. 3846 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 3847 } 3848 // Run the app in safe mode if its manifest requests so or the 3849 // system is booted in safe mode. 3850 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || 3851 mSafeMode == true) { 3852 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 3853 } 3854 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 3855 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 3856 } 3857 String genDebugInfoProperty = SystemProperties.get("debug.generate-debug-info"); 3858 if ("true".equals(genDebugInfoProperty)) { 3859 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; 3860 } 3861 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 3862 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 3863 } 3864 if ("1".equals(SystemProperties.get("debug.assert"))) { 3865 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; 3866 } 3867 if (mNativeDebuggingApp != null && mNativeDebuggingApp.equals(app.processName)) { 3868 // Enable all debug flags required by the native debugger. 3869 debugFlags |= Zygote.DEBUG_ALWAYS_JIT; // Don't interpret anything 3870 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; // Generate debug info 3871 debugFlags |= Zygote.DEBUG_NATIVE_DEBUGGABLE; // Disbale optimizations 3872 mNativeDebuggingApp = null; 3873 } 3874 3875 String invokeWith = null; 3876 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 3877 // Debuggable apps may include a wrapper script with their library directory. 3878 String wrapperFileName = app.info.nativeLibraryDir + "/wrap.sh"; 3879 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 3880 try { 3881 if (new File(wrapperFileName).exists()) { 3882 invokeWith = "/system/bin/logwrapper " + wrapperFileName; 3883 } 3884 } finally { 3885 StrictMode.setThreadPolicy(oldPolicy); 3886 } 3887 } 3888 3889 String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi; 3890 if (requiredAbi == null) { 3891 requiredAbi = Build.SUPPORTED_ABIS[0]; 3892 } 3893 3894 String instructionSet = null; 3895 if (app.info.primaryCpuAbi != null) { 3896 instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi); 3897 } 3898 3899 app.gids = gids; 3900 app.requiredAbi = requiredAbi; 3901 app.instructionSet = instructionSet; 3902 3903 // the per-user SELinux context must be set 3904 if (TextUtils.isEmpty(app.info.seInfoUser)) { 3905 Slog.wtf(TAG, "SELinux tag not defined", 3906 new IllegalStateException("SELinux tag not defined for " 3907 + app.info.packageName + " (uid " + app.uid + ")")); 3908 } 3909 final String seInfo = app.info.seInfo 3910 + (TextUtils.isEmpty(app.info.seInfoUser) ? "" : app.info.seInfoUser); 3911 // Start the process. It will either succeed and return a result containing 3912 // the PID of the new process, or else throw a RuntimeException. 3913 boolean isActivityProcess = (entryPoint == null); 3914 if (entryPoint == null) entryPoint = "android.app.ActivityThread"; 3915 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " + 3916 app.processName); 3917 checkTime(startTime, "startProcess: asking zygote to start proc"); 3918 ProcessStartResult startResult; 3919 if (hostingType.equals("webview_service")) { 3920 startResult = startWebView(entryPoint, 3921 app.processName, uid, uid, gids, debugFlags, mountExternal, 3922 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, 3923 app.info.dataDir, null, entryPointArgs); 3924 } else { 3925 startResult = Process.start(entryPoint, 3926 app.processName, uid, uid, gids, debugFlags, mountExternal, 3927 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, 3928 app.info.dataDir, invokeWith, entryPointArgs); 3929 } 3930 checkTime(startTime, "startProcess: returned from zygote!"); 3931 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 3932 3933 mBatteryStatsService.noteProcessStart(app.processName, app.info.uid); 3934 checkTime(startTime, "startProcess: done updating battery stats"); 3935 3936 EventLog.writeEvent(EventLogTags.AM_PROC_START, 3937 UserHandle.getUserId(uid), startResult.pid, uid, 3938 app.processName, hostingType, 3939 hostingNameStr != null ? hostingNameStr : ""); 3940 3941 try { 3942 AppGlobals.getPackageManager().logAppProcessStartIfNeeded(app.processName, app.uid, 3943 seInfo, app.info.sourceDir, startResult.pid); 3944 } catch (RemoteException ex) { 3945 // Ignore 3946 } 3947 3948 if (app.persistent) { 3949 Watchdog.getInstance().processStarted(app.processName, startResult.pid); 3950 } 3951 3952 checkTime(startTime, "startProcess: building log message"); 3953 StringBuilder buf = mStringBuilder; 3954 buf.setLength(0); 3955 buf.append("Start proc "); 3956 buf.append(startResult.pid); 3957 buf.append(':'); 3958 buf.append(app.processName); 3959 buf.append('/'); 3960 UserHandle.formatUid(buf, uid); 3961 if (!isActivityProcess) { 3962 buf.append(" ["); 3963 buf.append(entryPoint); 3964 buf.append("]"); 3965 } 3966 buf.append(" for "); 3967 buf.append(hostingType); 3968 if (hostingNameStr != null) { 3969 buf.append(" "); 3970 buf.append(hostingNameStr); 3971 } 3972 Slog.i(TAG, buf.toString()); 3973 app.setPid(startResult.pid); 3974 app.usingWrapper = startResult.usingWrapper; 3975 app.removed = false; 3976 app.killed = false; 3977 app.killedByAm = false; 3978 checkTime(startTime, "startProcess: starting to update pids map"); 3979 ProcessRecord oldApp; 3980 synchronized (mPidsSelfLocked) { 3981 oldApp = mPidsSelfLocked.get(startResult.pid); 3982 } 3983 // If there is already an app occupying that pid that hasn't been cleaned up 3984 if (oldApp != null && !app.isolated) { 3985 // Clean up anything relating to this pid first 3986 Slog.w(TAG, "Reusing pid " + startResult.pid 3987 + " while app is still mapped to it"); 3988 cleanUpApplicationRecordLocked(oldApp, false, false, -1, 3989 true /*replacingPid*/); 3990 } 3991 synchronized (mPidsSelfLocked) { 3992 this.mPidsSelfLocked.put(startResult.pid, app); 3993 if (isActivityProcess) { 3994 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 3995 msg.obj = app; 3996 mHandler.sendMessageDelayed(msg, startResult.usingWrapper 3997 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 3998 } 3999 } 4000 checkTime(startTime, "startProcess: done updating pids map"); 4001 } catch (RuntimeException e) { 4002 Slog.e(TAG, "Failure starting process " + app.processName, e); 4003 4004 // Something went very wrong while trying to start this process; one 4005 // common case is when the package is frozen due to an active 4006 // upgrade. To recover, clean up any active bookkeeping related to 4007 // starting this process. (We already invoked this method once when 4008 // the package was initially frozen through KILL_APPLICATION_MSG, so 4009 // it doesn't hurt to use it again.) 4010 forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false, 4011 false, true, false, false, UserHandle.getUserId(app.userId), "start failure"); 4012 } 4013 } 4014 4015 void updateUsageStats(ActivityRecord component, boolean resumed) { 4016 if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, 4017 "updateUsageStats: comp=" + component + "res=" + resumed); 4018 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 4019 if (resumed) { 4020 if (mUsageStatsService != null) { 4021 mUsageStatsService.reportEvent(component.realActivity, component.userId, 4022 UsageEvents.Event.MOVE_TO_FOREGROUND); 4023 } 4024 synchronized (stats) { 4025 stats.noteActivityResumedLocked(component.app.uid); 4026 } 4027 } else { 4028 if (mUsageStatsService != null) { 4029 mUsageStatsService.reportEvent(component.realActivity, component.userId, 4030 UsageEvents.Event.MOVE_TO_BACKGROUND); 4031 } 4032 synchronized (stats) { 4033 stats.noteActivityPausedLocked(component.app.uid); 4034 } 4035 } 4036 } 4037 4038 Intent getHomeIntent() { 4039 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null); 4040 intent.setComponent(mTopComponent); 4041 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING); 4042 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 4043 intent.addCategory(Intent.CATEGORY_HOME); 4044 } 4045 return intent; 4046 } 4047 4048 boolean startHomeActivityLocked(int userId, String reason) { 4049 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 4050 && mTopAction == null) { 4051 // We are running in factory test mode, but unable to find 4052 // the factory test app, so just sit around displaying the 4053 // error message and don't try to start anything. 4054 return false; 4055 } 4056 Intent intent = getHomeIntent(); 4057 ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); 4058 if (aInfo != null) { 4059 intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name)); 4060 // Don't do this if the home app is currently being 4061 // instrumented. 4062 aInfo = new ActivityInfo(aInfo); 4063 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId); 4064 ProcessRecord app = getProcessRecordLocked(aInfo.processName, 4065 aInfo.applicationInfo.uid, true); 4066 if (app == null || app.instr == null) { 4067 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 4068 final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid); 4069 // For ANR debugging to verify if the user activity is the one that actually 4070 // launched. 4071 final String myReason = reason + ":" + userId + ":" + resolvedUserId; 4072 mActivityStarter.startHomeActivityLocked(intent, aInfo, myReason); 4073 } 4074 } else { 4075 Slog.wtf(TAG, "No home screen found for " + intent, new Throwable()); 4076 } 4077 4078 return true; 4079 } 4080 4081 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) { 4082 ActivityInfo ai = null; 4083 ComponentName comp = intent.getComponent(); 4084 try { 4085 if (comp != null) { 4086 // Factory test. 4087 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId); 4088 } else { 4089 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent( 4090 intent, 4091 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 4092 flags, userId); 4093 4094 if (info != null) { 4095 ai = info.activityInfo; 4096 } 4097 } 4098 } catch (RemoteException e) { 4099 // ignore 4100 } 4101 4102 return ai; 4103 } 4104 4105 /** 4106 * Starts the "new version setup screen" if appropriate. 4107 */ 4108 void startSetupActivityLocked() { 4109 // Only do this once per boot. 4110 if (mCheckedForSetup) { 4111 return; 4112 } 4113 4114 // We will show this screen if the current one is a different 4115 // version than the last one shown, and we are not running in 4116 // low-level factory test mode. 4117 final ContentResolver resolver = mContext.getContentResolver(); 4118 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL && 4119 Settings.Global.getInt(resolver, 4120 Settings.Global.DEVICE_PROVISIONED, 0) != 0) { 4121 mCheckedForSetup = true; 4122 4123 // See if we should be showing the platform update setup UI. 4124 final Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP); 4125 final List<ResolveInfo> ris = mContext.getPackageManager().queryIntentActivities(intent, 4126 PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_META_DATA); 4127 if (!ris.isEmpty()) { 4128 final ResolveInfo ri = ris.get(0); 4129 String vers = ri.activityInfo.metaData != null 4130 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION) 4131 : null; 4132 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) { 4133 vers = ri.activityInfo.applicationInfo.metaData.getString( 4134 Intent.METADATA_SETUP_VERSION); 4135 } 4136 String lastVers = Settings.Secure.getString( 4137 resolver, Settings.Secure.LAST_SETUP_SHOWN); 4138 if (vers != null && !vers.equals(lastVers)) { 4139 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 4140 intent.setComponent(new ComponentName( 4141 ri.activityInfo.packageName, ri.activityInfo.name)); 4142 mActivityStarter.startActivityLocked(null, intent, null /*ephemeralIntent*/, 4143 null, ri.activityInfo, null /*rInfo*/, null, null, null, null, 0, 0, 0, 4144 null, 0, 0, 0, null, false, false, null, null, null, 4145 "startSetupActivity"); 4146 } 4147 } 4148 } 4149 } 4150 4151 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) { 4152 return mCompatModePackages.compatibilityInfoForPackageLocked(ai); 4153 } 4154 4155 void enforceNotIsolatedCaller(String caller) { 4156 if (UserHandle.isIsolated(Binder.getCallingUid())) { 4157 throw new SecurityException("Isolated process not allowed to call " + caller); 4158 } 4159 } 4160 4161 void enforceShellRestriction(String restriction, int userHandle) { 4162 if (Binder.getCallingUid() == SHELL_UID) { 4163 if (userHandle < 0 || mUserController.hasUserRestriction(restriction, userHandle)) { 4164 throw new SecurityException("Shell does not have permission to access user " 4165 + userHandle); 4166 } 4167 } 4168 } 4169 4170 @Override 4171 public int getFrontActivityScreenCompatMode() { 4172 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode"); 4173 synchronized (this) { 4174 return mCompatModePackages.getFrontActivityScreenCompatModeLocked(); 4175 } 4176 } 4177 4178 @Override 4179 public void setFrontActivityScreenCompatMode(int mode) { 4180 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 4181 "setFrontActivityScreenCompatMode"); 4182 synchronized (this) { 4183 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode); 4184 } 4185 } 4186 4187 @Override 4188 public int getPackageScreenCompatMode(String packageName) { 4189 enforceNotIsolatedCaller("getPackageScreenCompatMode"); 4190 synchronized (this) { 4191 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName); 4192 } 4193 } 4194 4195 @Override 4196 public void setPackageScreenCompatMode(String packageName, int mode) { 4197 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 4198 "setPackageScreenCompatMode"); 4199 synchronized (this) { 4200 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode); 4201 } 4202 } 4203 4204 @Override 4205 public boolean getPackageAskScreenCompat(String packageName) { 4206 enforceNotIsolatedCaller("getPackageAskScreenCompat"); 4207 synchronized (this) { 4208 return mCompatModePackages.getPackageAskCompatModeLocked(packageName); 4209 } 4210 } 4211 4212 @Override 4213 public void setPackageAskScreenCompat(String packageName, boolean ask) { 4214 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 4215 "setPackageAskScreenCompat"); 4216 synchronized (this) { 4217 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask); 4218 } 4219 } 4220 4221 private boolean hasUsageStatsPermission(String callingPackage) { 4222 final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_GET_USAGE_STATS, 4223 Binder.getCallingUid(), callingPackage); 4224 if (mode == AppOpsManager.MODE_DEFAULT) { 4225 return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS) 4226 == PackageManager.PERMISSION_GRANTED; 4227 } 4228 return mode == AppOpsManager.MODE_ALLOWED; 4229 } 4230 4231 @Override 4232 public int getPackageProcessState(String packageName, String callingPackage) { 4233 if (!hasUsageStatsPermission(callingPackage)) { 4234 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 4235 "getPackageProcessState"); 4236 } 4237 4238 int procState = ActivityManager.PROCESS_STATE_NONEXISTENT; 4239 synchronized (this) { 4240 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4241 final ProcessRecord proc = mLruProcesses.get(i); 4242 if (procState > proc.setProcState) { 4243 if (proc.pkgList.containsKey(packageName) || 4244 (proc.pkgDeps != null && proc.pkgDeps.contains(packageName))) { 4245 procState = proc.setProcState; 4246 } 4247 } 4248 } 4249 } 4250 return procState; 4251 } 4252 4253 @Override 4254 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) 4255 throws RemoteException { 4256 synchronized (this) { 4257 final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel"); 4258 if (app == null) { 4259 throw new IllegalArgumentException("Unknown process: " + process); 4260 } 4261 if (app.thread == null) { 4262 throw new IllegalArgumentException("Process has no app thread"); 4263 } 4264 if (app.trimMemoryLevel >= level) { 4265 throw new IllegalArgumentException( 4266 "Unable to set a higher trim level than current level"); 4267 } 4268 if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || 4269 app.curProcState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND)) { 4270 throw new IllegalArgumentException("Unable to set a background trim level " 4271 + "on a foreground process"); 4272 } 4273 app.thread.scheduleTrimMemory(level); 4274 app.trimMemoryLevel = level; 4275 return true; 4276 } 4277 } 4278 4279 private void dispatchProcessesChanged() { 4280 int N; 4281 synchronized (this) { 4282 N = mPendingProcessChanges.size(); 4283 if (mActiveProcessChanges.length < N) { 4284 mActiveProcessChanges = new ProcessChangeItem[N]; 4285 } 4286 mPendingProcessChanges.toArray(mActiveProcessChanges); 4287 mPendingProcessChanges.clear(); 4288 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 4289 "*** Delivering " + N + " process changes"); 4290 } 4291 4292 int i = mProcessObservers.beginBroadcast(); 4293 while (i > 0) { 4294 i--; 4295 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 4296 if (observer != null) { 4297 try { 4298 for (int j=0; j<N; j++) { 4299 ProcessChangeItem item = mActiveProcessChanges[j]; 4300 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) { 4301 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 4302 "ACTIVITIES CHANGED pid=" + item.pid + " uid=" 4303 + item.uid + ": " + item.foregroundActivities); 4304 observer.onForegroundActivitiesChanged(item.pid, item.uid, 4305 item.foregroundActivities); 4306 } 4307 } 4308 } catch (RemoteException e) { 4309 } 4310 } 4311 } 4312 mProcessObservers.finishBroadcast(); 4313 4314 synchronized (this) { 4315 for (int j=0; j<N; j++) { 4316 mAvailProcessChanges.add(mActiveProcessChanges[j]); 4317 } 4318 } 4319 } 4320 4321 private void dispatchProcessDied(int pid, int uid) { 4322 int i = mProcessObservers.beginBroadcast(); 4323 while (i > 0) { 4324 i--; 4325 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 4326 if (observer != null) { 4327 try { 4328 observer.onProcessDied(pid, uid); 4329 } catch (RemoteException e) { 4330 } 4331 } 4332 } 4333 mProcessObservers.finishBroadcast(); 4334 } 4335 4336 @VisibleForTesting 4337 void dispatchUidsChanged() { 4338 int N; 4339 synchronized (this) { 4340 N = mPendingUidChanges.size(); 4341 if (mActiveUidChanges.length < N) { 4342 mActiveUidChanges = new UidRecord.ChangeItem[N]; 4343 } 4344 for (int i=0; i<N; i++) { 4345 final UidRecord.ChangeItem change = mPendingUidChanges.get(i); 4346 mActiveUidChanges[i] = change; 4347 if (change.uidRecord != null) { 4348 change.uidRecord.pendingChange = null; 4349 change.uidRecord = null; 4350 } 4351 } 4352 mPendingUidChanges.clear(); 4353 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 4354 "*** Delivering " + N + " uid changes"); 4355 } 4356 4357 int i = mUidObservers.beginBroadcast(); 4358 while (i > 0) { 4359 i--; 4360 dispatchUidsChangedForObserver(mUidObservers.getBroadcastItem(i), 4361 (UidObserverRegistration) mUidObservers.getBroadcastCookie(i), N); 4362 } 4363 mUidObservers.finishBroadcast(); 4364 4365 if (VALIDATE_UID_STATES && mUidObservers.getRegisteredCallbackCount() > 0) { 4366 for (int j = 0; j < N; ++j) { 4367 final UidRecord.ChangeItem item = mActiveUidChanges[j]; 4368 if (item.change == UidRecord.CHANGE_GONE 4369 || item.change == UidRecord.CHANGE_GONE_IDLE) { 4370 mValidateUids.remove(item.uid); 4371 } else { 4372 UidRecord validateUid = mValidateUids.get(item.uid); 4373 if (validateUid == null) { 4374 validateUid = new UidRecord(item.uid); 4375 mValidateUids.put(item.uid, validateUid); 4376 } 4377 if (item.change == UidRecord.CHANGE_IDLE) { 4378 validateUid.idle = true; 4379 } else if (item.change == UidRecord.CHANGE_ACTIVE) { 4380 validateUid.idle = false; 4381 } 4382 validateUid.curProcState = validateUid.setProcState = item.processState; 4383 validateUid.lastDispatchedProcStateSeq = item.procStateSeq; 4384 } 4385 } 4386 } 4387 4388 synchronized (this) { 4389 for (int j = 0; j < N; j++) { 4390 mAvailUidChanges.add(mActiveUidChanges[j]); 4391 } 4392 } 4393 } 4394 4395 private void dispatchUidsChangedForObserver(IUidObserver observer, 4396 UidObserverRegistration reg, int changesSize) { 4397 if (observer == null) { 4398 return; 4399 } 4400 try { 4401 for (int j = 0; j < changesSize; j++) { 4402 UidRecord.ChangeItem item = mActiveUidChanges[j]; 4403 final int change = item.change; 4404 if (change == UidRecord.CHANGE_IDLE 4405 || change == UidRecord.CHANGE_GONE_IDLE) { 4406 if ((reg.which & ActivityManager.UID_OBSERVER_IDLE) != 0) { 4407 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 4408 "UID idle uid=" + item.uid); 4409 observer.onUidIdle(item.uid, item.ephemeral); 4410 } 4411 } else if (change == UidRecord.CHANGE_ACTIVE) { 4412 if ((reg.which & ActivityManager.UID_OBSERVER_ACTIVE) != 0) { 4413 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 4414 "UID active uid=" + item.uid); 4415 observer.onUidActive(item.uid); 4416 } 4417 } 4418 if (change == UidRecord.CHANGE_GONE 4419 || change == UidRecord.CHANGE_GONE_IDLE) { 4420 if ((reg.which & ActivityManager.UID_OBSERVER_GONE) != 0) { 4421 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 4422 "UID gone uid=" + item.uid); 4423 observer.onUidGone(item.uid, item.ephemeral); 4424 } 4425 if (reg.lastProcStates != null) { 4426 reg.lastProcStates.delete(item.uid); 4427 } 4428 } else { 4429 if ((reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) != 0) { 4430 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 4431 "UID CHANGED uid=" + item.uid 4432 + ": " + item.processState); 4433 boolean doReport = true; 4434 if (reg.cutpoint >= ActivityManager.MIN_PROCESS_STATE) { 4435 final int lastState = reg.lastProcStates.get(item.uid, 4436 ActivityManager.PROCESS_STATE_UNKNOWN); 4437 if (lastState != ActivityManager.PROCESS_STATE_UNKNOWN) { 4438 final boolean lastAboveCut = lastState <= reg.cutpoint; 4439 final boolean newAboveCut = item.processState <= reg.cutpoint; 4440 doReport = lastAboveCut != newAboveCut; 4441 } else { 4442 doReport = item.processState 4443 != ActivityManager.PROCESS_STATE_NONEXISTENT; 4444 } 4445 } 4446 if (doReport) { 4447 if (reg.lastProcStates != null) { 4448 reg.lastProcStates.put(item.uid, item.processState); 4449 } 4450 observer.onUidStateChanged(item.uid, item.processState, 4451 item.procStateSeq); 4452 } 4453 } 4454 } 4455 } 4456 } catch (RemoteException e) { 4457 } 4458 } 4459 4460 @Override 4461 public final int startActivity(IApplicationThread caller, String callingPackage, 4462 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 4463 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { 4464 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, 4465 resultWho, requestCode, startFlags, profilerInfo, bOptions, 4466 UserHandle.getCallingUserId()); 4467 } 4468 4469 final int startActivity(Intent intent, ActivityStackSupervisor.ActivityContainer container) { 4470 enforceNotIsolatedCaller("ActivityContainer.startActivity"); 4471 final int userId = mUserController.handleIncomingUser(Binder.getCallingPid(), 4472 Binder.getCallingUid(), mStackSupervisor.mCurrentUser, false, 4473 ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null); 4474 4475 // TODO: Switch to user app stacks here. 4476 String mimeType = intent.getType(); 4477 final Uri data = intent.getData(); 4478 if (mimeType == null && data != null && "content".equals(data.getScheme())) { 4479 mimeType = getProviderMimeType(data, userId); 4480 } 4481 container.checkEmbeddedAllowedInner(userId, intent, mimeType); 4482 4483 intent.addFlags(FORCE_NEW_TASK_FLAGS); 4484 return mActivityStarter.startActivityMayWait(null, -1, null, intent, mimeType, null, null, 4485 null, null, 0, 0, null, null, null, null, false, userId, container, null, 4486 "startActivity"); 4487 } 4488 4489 @Override 4490 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 4491 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 4492 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 4493 enforceNotIsolatedCaller("startActivity"); 4494 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 4495 userId, false, ALLOW_FULL_ONLY, "startActivity", null); 4496 // TODO: Switch to user app stacks here. 4497 return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, 4498 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 4499 profilerInfo, null, null, bOptions, false, userId, null, null, 4500 "startActivityAsUser"); 4501 } 4502 4503 @Override 4504 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage, 4505 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 4506 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity, 4507 int userId) { 4508 4509 // This is very dangerous -- it allows you to perform a start activity (including 4510 // permission grants) as any app that may launch one of your own activities. So 4511 // we will only allow this to be done from activities that are part of the core framework, 4512 // and then only when they are running as the system. 4513 final ActivityRecord sourceRecord; 4514 final int targetUid; 4515 final String targetPackage; 4516 synchronized (this) { 4517 if (resultTo == null) { 4518 throw new SecurityException("Must be called from an activity"); 4519 } 4520 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo); 4521 if (sourceRecord == null) { 4522 throw new SecurityException("Called with bad activity token: " + resultTo); 4523 } 4524 if (!sourceRecord.info.packageName.equals("android")) { 4525 throw new SecurityException( 4526 "Must be called from an activity that is declared in the android package"); 4527 } 4528 if (sourceRecord.app == null) { 4529 throw new SecurityException("Called without a process attached to activity"); 4530 } 4531 if (UserHandle.getAppId(sourceRecord.app.uid) != SYSTEM_UID) { 4532 // This is still okay, as long as this activity is running under the 4533 // uid of the original calling activity. 4534 if (sourceRecord.app.uid != sourceRecord.launchedFromUid) { 4535 throw new SecurityException( 4536 "Calling activity in uid " + sourceRecord.app.uid 4537 + " must be system uid or original calling uid " 4538 + sourceRecord.launchedFromUid); 4539 } 4540 } 4541 if (ignoreTargetSecurity) { 4542 if (intent.getComponent() == null) { 4543 throw new SecurityException( 4544 "Component must be specified with ignoreTargetSecurity"); 4545 } 4546 if (intent.getSelector() != null) { 4547 throw new SecurityException( 4548 "Selector not allowed with ignoreTargetSecurity"); 4549 } 4550 } 4551 targetUid = sourceRecord.launchedFromUid; 4552 targetPackage = sourceRecord.launchedFromPackage; 4553 } 4554 4555 if (userId == UserHandle.USER_NULL) { 4556 userId = UserHandle.getUserId(sourceRecord.app.uid); 4557 } 4558 4559 // TODO: Switch to user app stacks here. 4560 try { 4561 int ret = mActivityStarter.startActivityMayWait(null, targetUid, targetPackage, intent, 4562 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null, 4563 null, null, bOptions, ignoreTargetSecurity, userId, null, null, 4564 "startActivityAsCaller"); 4565 return ret; 4566 } catch (SecurityException e) { 4567 // XXX need to figure out how to propagate to original app. 4568 // A SecurityException here is generally actually a fault of the original 4569 // calling activity (such as a fairly granting permissions), so propagate it 4570 // back to them. 4571 /* 4572 StringBuilder msg = new StringBuilder(); 4573 msg.append("While launching"); 4574 msg.append(intent.toString()); 4575 msg.append(": "); 4576 msg.append(e.getMessage()); 4577 */ 4578 throw e; 4579 } 4580 } 4581 4582 @Override 4583 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 4584 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 4585 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 4586 enforceNotIsolatedCaller("startActivityAndWait"); 4587 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 4588 userId, false, ALLOW_FULL_ONLY, "startActivityAndWait", null); 4589 WaitResult res = new WaitResult(); 4590 // TODO: Switch to user app stacks here. 4591 mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 4592 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null, 4593 bOptions, false, userId, null, null, "startActivityAndWait"); 4594 return res; 4595 } 4596 4597 @Override 4598 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage, 4599 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 4600 int startFlags, Configuration config, Bundle bOptions, int userId) { 4601 enforceNotIsolatedCaller("startActivityWithConfig"); 4602 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 4603 userId, false, ALLOW_FULL_ONLY, "startActivityWithConfig", null); 4604 // TODO: Switch to user app stacks here. 4605 int ret = mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, 4606 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 4607 null, null, config, bOptions, false, userId, null, null, "startActivityWithConfig"); 4608 return ret; 4609 } 4610 4611 @Override 4612 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target, 4613 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo, 4614 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) 4615 throws TransactionTooLargeException { 4616 enforceNotIsolatedCaller("startActivityIntentSender"); 4617 // Refuse possible leaked file descriptors 4618 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) { 4619 throw new IllegalArgumentException("File descriptors passed in Intent"); 4620 } 4621 4622 if (!(target instanceof PendingIntentRecord)) { 4623 throw new IllegalArgumentException("Bad PendingIntent object"); 4624 } 4625 4626 PendingIntentRecord pir = (PendingIntentRecord)target; 4627 4628 synchronized (this) { 4629 // If this is coming from the currently resumed activity, it is 4630 // effectively saying that app switches are allowed at this point. 4631 final ActivityStack stack = getFocusedStack(); 4632 if (stack.mResumedActivity != null && 4633 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) { 4634 mAppSwitchesAllowedTime = 0; 4635 } 4636 } 4637 int ret = pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null, 4638 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions, null); 4639 return ret; 4640 } 4641 4642 @Override 4643 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid, 4644 Intent intent, String resolvedType, IVoiceInteractionSession session, 4645 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo, 4646 Bundle bOptions, int userId) { 4647 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION) 4648 != PackageManager.PERMISSION_GRANTED) { 4649 String msg = "Permission Denial: startVoiceActivity() from pid=" 4650 + Binder.getCallingPid() 4651 + ", uid=" + Binder.getCallingUid() 4652 + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION; 4653 Slog.w(TAG, msg); 4654 throw new SecurityException(msg); 4655 } 4656 if (session == null || interactor == null) { 4657 throw new NullPointerException("null session or interactor"); 4658 } 4659 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false, 4660 ALLOW_FULL_ONLY, "startVoiceActivity", null); 4661 // TODO: Switch to user app stacks here. 4662 return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent, 4663 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null, 4664 null, bOptions, false, userId, null, null, "startVoiceActivity"); 4665 } 4666 4667 @Override 4668 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid, 4669 Intent intent, String resolvedType, Bundle bOptions, int userId) { 4670 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION) 4671 != PackageManager.PERMISSION_GRANTED) { 4672 final String msg = "Permission Denial: startAssistantActivity() from pid=" 4673 + Binder.getCallingPid() 4674 + ", uid=" + Binder.getCallingUid() 4675 + " requires " + Manifest.permission.BIND_VOICE_INTERACTION; 4676 Slog.w(TAG, msg); 4677 throw new SecurityException(msg); 4678 } 4679 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false, 4680 ALLOW_FULL_ONLY, "startAssistantActivity", null); 4681 return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent, 4682 resolvedType, null, null, null, null, 0, 0, null, null, null, bOptions, false, 4683 userId, null, null, "startAssistantActivity"); 4684 } 4685 4686 @Override 4687 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) 4688 throws RemoteException { 4689 Slog.i(TAG, "Activity tried to startVoiceInteraction"); 4690 synchronized (this) { 4691 ActivityRecord activity = getFocusedStack().topActivity(); 4692 if (ActivityRecord.forTokenLocked(callingActivity) != activity) { 4693 throw new SecurityException("Only focused activity can call startVoiceInteraction"); 4694 } 4695 if (mRunningVoice != null || activity.getTask().voiceSession != null 4696 || activity.voiceSession != null) { 4697 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction"); 4698 return; 4699 } 4700 if (activity.pendingVoiceInteractionStart) { 4701 Slog.w(TAG, "Pending start of voice interaction already."); 4702 return; 4703 } 4704 activity.pendingVoiceInteractionStart = true; 4705 } 4706 LocalServices.getService(VoiceInteractionManagerInternal.class) 4707 .startLocalVoiceInteraction(callingActivity, options); 4708 } 4709 4710 @Override 4711 public void stopLocalVoiceInteraction(IBinder callingActivity) throws RemoteException { 4712 LocalServices.getService(VoiceInteractionManagerInternal.class) 4713 .stopLocalVoiceInteraction(callingActivity); 4714 } 4715 4716 @Override 4717 public boolean supportsLocalVoiceInteraction() throws RemoteException { 4718 return LocalServices.getService(VoiceInteractionManagerInternal.class) 4719 .supportsLocalVoiceInteraction(); 4720 } 4721 4722 void onLocalVoiceInteractionStartedLocked(IBinder activity, 4723 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) { 4724 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity); 4725 if (activityToCallback == null) return; 4726 activityToCallback.setVoiceSessionLocked(voiceSession); 4727 4728 // Inform the activity 4729 try { 4730 activityToCallback.app.thread.scheduleLocalVoiceInteractionStarted(activity, 4731 voiceInteractor); 4732 long token = Binder.clearCallingIdentity(); 4733 try { 4734 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid); 4735 } finally { 4736 Binder.restoreCallingIdentity(token); 4737 } 4738 // TODO: VI Should we cache the activity so that it's easier to find later 4739 // rather than scan through all the stacks and activities? 4740 } catch (RemoteException re) { 4741 activityToCallback.clearVoiceSessionLocked(); 4742 // TODO: VI Should this terminate the voice session? 4743 } 4744 } 4745 4746 @Override 4747 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) { 4748 synchronized (this) { 4749 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) { 4750 if (keepAwake) { 4751 mVoiceWakeLock.acquire(); 4752 } else { 4753 mVoiceWakeLock.release(); 4754 } 4755 } 4756 } 4757 } 4758 4759 @Override 4760 public boolean startNextMatchingActivity(IBinder callingActivity, 4761 Intent intent, Bundle bOptions) { 4762 // Refuse possible leaked file descriptors 4763 if (intent != null && intent.hasFileDescriptors() == true) { 4764 throw new IllegalArgumentException("File descriptors passed in Intent"); 4765 } 4766 ActivityOptions options = ActivityOptions.fromBundle(bOptions); 4767 4768 synchronized (this) { 4769 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity); 4770 if (r == null) { 4771 ActivityOptions.abort(options); 4772 return false; 4773 } 4774 if (r.app == null || r.app.thread == null) { 4775 // The caller is not running... d'oh! 4776 ActivityOptions.abort(options); 4777 return false; 4778 } 4779 intent = new Intent(intent); 4780 // The caller is not allowed to change the data. 4781 intent.setDataAndType(r.intent.getData(), r.intent.getType()); 4782 // And we are resetting to find the next component... 4783 intent.setComponent(null); 4784 4785 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4786 4787 ActivityInfo aInfo = null; 4788 try { 4789 List<ResolveInfo> resolves = 4790 AppGlobals.getPackageManager().queryIntentActivities( 4791 intent, r.resolvedType, 4792 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS, 4793 UserHandle.getCallingUserId()).getList(); 4794 4795 // Look for the original activity in the list... 4796 final int N = resolves != null ? resolves.size() : 0; 4797 for (int i=0; i<N; i++) { 4798 ResolveInfo rInfo = resolves.get(i); 4799 if (rInfo.activityInfo.packageName.equals(r.packageName) 4800 && rInfo.activityInfo.name.equals(r.info.name)) { 4801 // We found the current one... the next matching is 4802 // after it. 4803 i++; 4804 if (i<N) { 4805 aInfo = resolves.get(i).activityInfo; 4806 } 4807 if (debug) { 4808 Slog.v(TAG, "Next matching activity: found current " + r.packageName 4809 + "/" + r.info.name); 4810 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null) 4811 ? "null" : aInfo.packageName + "/" + aInfo.name)); 4812 } 4813 break; 4814 } 4815 } 4816 } catch (RemoteException e) { 4817 } 4818 4819 if (aInfo == null) { 4820 // Nobody who is next! 4821 ActivityOptions.abort(options); 4822 if (debug) Slog.d(TAG, "Next matching activity: nothing found"); 4823 return false; 4824 } 4825 4826 intent.setComponent(new ComponentName( 4827 aInfo.applicationInfo.packageName, aInfo.name)); 4828 intent.setFlags(intent.getFlags()&~( 4829 Intent.FLAG_ACTIVITY_FORWARD_RESULT| 4830 Intent.FLAG_ACTIVITY_CLEAR_TOP| 4831 Intent.FLAG_ACTIVITY_MULTIPLE_TASK| 4832 Intent.FLAG_ACTIVITY_NEW_TASK)); 4833 4834 // Okay now we need to start the new activity, replacing the 4835 // currently running activity. This is a little tricky because 4836 // we want to start the new one as if the current one is finished, 4837 // but not finish the current one first so that there is no flicker. 4838 // And thus... 4839 final boolean wasFinishing = r.finishing; 4840 r.finishing = true; 4841 4842 // Propagate reply information over to the new activity. 4843 final ActivityRecord resultTo = r.resultTo; 4844 final String resultWho = r.resultWho; 4845 final int requestCode = r.requestCode; 4846 r.resultTo = null; 4847 if (resultTo != null) { 4848 resultTo.removeResultsLocked(r, resultWho, requestCode); 4849 } 4850 4851 final long origId = Binder.clearCallingIdentity(); 4852 int res = mActivityStarter.startActivityLocked(r.app.thread, intent, 4853 null /*ephemeralIntent*/, r.resolvedType, aInfo, null /*rInfo*/, null, 4854 null, resultTo != null ? resultTo.appToken : null, resultWho, requestCode, -1, 4855 r.launchedFromUid, r.launchedFromPackage, -1, r.launchedFromUid, 0, options, 4856 false, false, null, null, null, "startNextMatchingActivity"); 4857 Binder.restoreCallingIdentity(origId); 4858 4859 r.finishing = wasFinishing; 4860 if (res != ActivityManager.START_SUCCESS) { 4861 return false; 4862 } 4863 return true; 4864 } 4865 } 4866 4867 @Override 4868 public final int startActivityFromRecents(int taskId, Bundle bOptions) { 4869 if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) { 4870 String msg = "Permission Denial: startActivityFromRecents called without " + 4871 START_TASKS_FROM_RECENTS; 4872 Slog.w(TAG, msg); 4873 throw new SecurityException(msg); 4874 } 4875 final long origId = Binder.clearCallingIdentity(); 4876 try { 4877 synchronized (this) { 4878 return mStackSupervisor.startActivityFromRecentsInner(taskId, bOptions); 4879 } 4880 } finally { 4881 Binder.restoreCallingIdentity(origId); 4882 } 4883 } 4884 4885 final int startActivityInPackage(int uid, String callingPackage, 4886 Intent intent, String resolvedType, IBinder resultTo, 4887 String resultWho, int requestCode, int startFlags, Bundle bOptions, int userId, 4888 IActivityContainer container, TaskRecord inTask, String reason) { 4889 4890 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 4891 userId, false, ALLOW_FULL_ONLY, "startActivityInPackage", null); 4892 4893 // TODO: Switch to user app stacks here. 4894 int ret = mActivityStarter.startActivityMayWait(null, uid, callingPackage, intent, 4895 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 4896 null, null, null, bOptions, false, userId, container, inTask, reason); 4897 return ret; 4898 } 4899 4900 @Override 4901 public final int startActivities(IApplicationThread caller, String callingPackage, 4902 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions, 4903 int userId) { 4904 final String reason = "startActivities"; 4905 enforceNotIsolatedCaller(reason); 4906 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 4907 userId, false, ALLOW_FULL_ONLY, reason, null); 4908 // TODO: Switch to user app stacks here. 4909 int ret = mActivityStarter.startActivities(caller, -1, callingPackage, intents, 4910 resolvedTypes, resultTo, bOptions, userId, reason); 4911 return ret; 4912 } 4913 4914 final int startActivitiesInPackage(int uid, String callingPackage, 4915 Intent[] intents, String[] resolvedTypes, IBinder resultTo, 4916 Bundle bOptions, int userId) { 4917 4918 final String reason = "startActivityInPackage"; 4919 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 4920 userId, false, ALLOW_FULL_ONLY, reason, null); 4921 // TODO: Switch to user app stacks here. 4922 int ret = mActivityStarter.startActivities(null, uid, callingPackage, intents, resolvedTypes, 4923 resultTo, bOptions, userId, reason); 4924 return ret; 4925 } 4926 4927 @Override 4928 public void reportActivityFullyDrawn(IBinder token) { 4929 synchronized (this) { 4930 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4931 if (r == null) { 4932 return; 4933 } 4934 r.reportFullyDrawnLocked(); 4935 } 4936 } 4937 4938 @Override 4939 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 4940 synchronized (this) { 4941 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4942 if (r == null) { 4943 return; 4944 } 4945 final long origId = Binder.clearCallingIdentity(); 4946 try { 4947 r.setRequestedOrientation(requestedOrientation); 4948 } finally { 4949 Binder.restoreCallingIdentity(origId); 4950 } 4951 } 4952 } 4953 4954 @Override 4955 public int getRequestedOrientation(IBinder token) { 4956 synchronized (this) { 4957 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4958 if (r == null) { 4959 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 4960 } 4961 return r.getRequestedOrientation(); 4962 } 4963 } 4964 4965 @Override 4966 public final void requestActivityRelaunch(IBinder token) { 4967 synchronized(this) { 4968 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4969 if (r == null) { 4970 return; 4971 } 4972 final long origId = Binder.clearCallingIdentity(); 4973 try { 4974 r.forceNewConfig = true; 4975 r.ensureActivityConfigurationLocked(0 /* globalChanges */, 4976 true /* preserveWindow */); 4977 } finally { 4978 Binder.restoreCallingIdentity(origId); 4979 } 4980 } 4981 } 4982 4983 /** 4984 * This is the internal entry point for handling Activity.finish(). 4985 * 4986 * @param token The Binder token referencing the Activity we want to finish. 4987 * @param resultCode Result code, if any, from this Activity. 4988 * @param resultData Result data (Intent), if any, from this Activity. 4989 * @param finishTask Whether to finish the task associated with this Activity. 4990 * 4991 * @return Returns true if the activity successfully finished, or false if it is still running. 4992 */ 4993 @Override 4994 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 4995 int finishTask) { 4996 // Refuse possible leaked file descriptors 4997 if (resultData != null && resultData.hasFileDescriptors() == true) { 4998 throw new IllegalArgumentException("File descriptors passed in Intent"); 4999 } 5000 5001 synchronized(this) { 5002 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5003 if (r == null) { 5004 return true; 5005 } 5006 // Keep track of the root activity of the task before we finish it 5007 TaskRecord tr = r.getTask(); 5008 ActivityRecord rootR = tr.getRootActivity(); 5009 if (rootR == null) { 5010 Slog.w(TAG, "Finishing task with all activities already finished"); 5011 } 5012 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can 5013 // finish. 5014 if (tr.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV && rootR == r && 5015 mStackSupervisor.isLastLockedTask(tr)) { 5016 Slog.i(TAG, "Not finishing task in lock task mode"); 5017 mStackSupervisor.showLockTaskToast(); 5018 return false; 5019 } 5020 if (mController != null) { 5021 // Find the first activity that is not finishing. 5022 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0); 5023 if (next != null) { 5024 // ask watcher if this is allowed 5025 boolean resumeOK = true; 5026 try { 5027 resumeOK = mController.activityResuming(next.packageName); 5028 } catch (RemoteException e) { 5029 mController = null; 5030 Watchdog.getInstance().setActivityController(null); 5031 } 5032 5033 if (!resumeOK) { 5034 Slog.i(TAG, "Not finishing activity because controller resumed"); 5035 return false; 5036 } 5037 } 5038 } 5039 final long origId = Binder.clearCallingIdentity(); 5040 try { 5041 boolean res; 5042 final boolean finishWithRootActivity = 5043 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY; 5044 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY 5045 || (finishWithRootActivity && r == rootR)) { 5046 // If requested, remove the task that is associated to this activity only if it 5047 // was the root activity in the task. The result code and data is ignored 5048 // because we don't support returning them across task boundaries. Also, to 5049 // keep backwards compatibility we remove the task from recents when finishing 5050 // task with root activity. 5051 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false, finishWithRootActivity); 5052 if (!res) { 5053 Slog.i(TAG, "Removing task failed to finish activity"); 5054 } 5055 } else { 5056 res = tr.getStack().requestFinishActivityLocked(token, resultCode, 5057 resultData, "app-request", true); 5058 if (!res) { 5059 Slog.i(TAG, "Failed to finish by app-request"); 5060 } 5061 } 5062 return res; 5063 } finally { 5064 Binder.restoreCallingIdentity(origId); 5065 } 5066 } 5067 } 5068 5069 @Override 5070 public final void finishHeavyWeightApp() { 5071 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 5072 != PackageManager.PERMISSION_GRANTED) { 5073 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 5074 + Binder.getCallingPid() 5075 + ", uid=" + Binder.getCallingUid() 5076 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 5077 Slog.w(TAG, msg); 5078 throw new SecurityException(msg); 5079 } 5080 5081 synchronized(this) { 5082 if (mHeavyWeightProcess == null) { 5083 return; 5084 } 5085 5086 ArrayList<ActivityRecord> activities = new ArrayList<>(mHeavyWeightProcess.activities); 5087 for (int i = 0; i < activities.size(); i++) { 5088 ActivityRecord r = activities.get(i); 5089 if (!r.finishing && r.isInStackLocked()) { 5090 r.getStack().finishActivityLocked(r, Activity.RESULT_CANCELED, 5091 null, "finish-heavy", true); 5092 } 5093 } 5094 5095 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 5096 mHeavyWeightProcess.userId, 0)); 5097 mHeavyWeightProcess = null; 5098 } 5099 } 5100 5101 @Override 5102 public void crashApplication(int uid, int initialPid, String packageName, int userId, 5103 String message) { 5104 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 5105 != PackageManager.PERMISSION_GRANTED) { 5106 String msg = "Permission Denial: crashApplication() from pid=" 5107 + Binder.getCallingPid() 5108 + ", uid=" + Binder.getCallingUid() 5109 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 5110 Slog.w(TAG, msg); 5111 throw new SecurityException(msg); 5112 } 5113 5114 synchronized(this) { 5115 mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId, message); 5116 } 5117 } 5118 5119 @Override 5120 public final void finishSubActivity(IBinder token, String resultWho, 5121 int requestCode) { 5122 synchronized(this) { 5123 final long origId = Binder.clearCallingIdentity(); 5124 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5125 if (r != null) { 5126 r.getStack().finishSubActivityLocked(r, resultWho, requestCode); 5127 } 5128 Binder.restoreCallingIdentity(origId); 5129 } 5130 } 5131 5132 @Override 5133 public boolean finishActivityAffinity(IBinder token) { 5134 synchronized(this) { 5135 final long origId = Binder.clearCallingIdentity(); 5136 try { 5137 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5138 if (r == null) { 5139 return false; 5140 } 5141 5142 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps 5143 // can finish. 5144 final TaskRecord task = r.getTask(); 5145 if (task.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV && 5146 mStackSupervisor.isLastLockedTask(task) && task.getRootActivity() == r) { 5147 mStackSupervisor.showLockTaskToast(); 5148 return false; 5149 } 5150 return task.getStack().finishActivityAffinityLocked(r); 5151 } finally { 5152 Binder.restoreCallingIdentity(origId); 5153 } 5154 } 5155 } 5156 5157 @Override 5158 public void finishVoiceTask(IVoiceInteractionSession session) { 5159 synchronized (this) { 5160 final long origId = Binder.clearCallingIdentity(); 5161 try { 5162 // TODO: VI Consider treating local voice interactions and voice tasks 5163 // differently here 5164 mStackSupervisor.finishVoiceTask(session); 5165 } finally { 5166 Binder.restoreCallingIdentity(origId); 5167 } 5168 } 5169 5170 } 5171 5172 @Override 5173 public boolean releaseActivityInstance(IBinder token) { 5174 synchronized(this) { 5175 final long origId = Binder.clearCallingIdentity(); 5176 try { 5177 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5178 if (r == null) { 5179 return false; 5180 } 5181 return r.getStack().safelyDestroyActivityLocked(r, "app-req"); 5182 } finally { 5183 Binder.restoreCallingIdentity(origId); 5184 } 5185 } 5186 } 5187 5188 @Override 5189 public void releaseSomeActivities(IApplicationThread appInt) { 5190 synchronized(this) { 5191 final long origId = Binder.clearCallingIdentity(); 5192 try { 5193 ProcessRecord app = getRecordForAppLocked(appInt); 5194 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem"); 5195 } finally { 5196 Binder.restoreCallingIdentity(origId); 5197 } 5198 } 5199 } 5200 5201 @Override 5202 public boolean willActivityBeVisible(IBinder token) { 5203 synchronized(this) { 5204 ActivityStack stack = ActivityRecord.getStackLocked(token); 5205 if (stack != null) { 5206 return stack.willActivityBeVisibleLocked(token); 5207 } 5208 return false; 5209 } 5210 } 5211 5212 @Override 5213 public void overridePendingTransition(IBinder token, String packageName, 5214 int enterAnim, int exitAnim) { 5215 synchronized(this) { 5216 ActivityRecord self = ActivityRecord.isInStackLocked(token); 5217 if (self == null) { 5218 return; 5219 } 5220 5221 final long origId = Binder.clearCallingIdentity(); 5222 5223 if (self.state == ActivityState.RESUMED 5224 || self.state == ActivityState.PAUSING) { 5225 mWindowManager.overridePendingAppTransition(packageName, 5226 enterAnim, exitAnim, null); 5227 } 5228 5229 Binder.restoreCallingIdentity(origId); 5230 } 5231 } 5232 5233 /** 5234 * Main function for removing an existing process from the activity manager 5235 * as a result of that process going away. Clears out all connections 5236 * to the process. 5237 */ 5238 private final void handleAppDiedLocked(ProcessRecord app, 5239 boolean restarting, boolean allowRestart) { 5240 int pid = app.pid; 5241 boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1, 5242 false /*replacingPid*/); 5243 if (!kept && !restarting) { 5244 removeLruProcessLocked(app); 5245 if (pid > 0) { 5246 ProcessList.remove(pid); 5247 } 5248 } 5249 5250 if (mProfileProc == app) { 5251 clearProfilerLocked(); 5252 } 5253 5254 // Remove this application's activities from active lists. 5255 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app); 5256 5257 app.activities.clear(); 5258 5259 if (app.instr != null) { 5260 Slog.w(TAG, "Crash of app " + app.processName 5261 + " running instrumentation " + app.instr.mClass); 5262 Bundle info = new Bundle(); 5263 info.putString("shortMsg", "Process crashed."); 5264 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 5265 } 5266 5267 mWindowManager.deferSurfaceLayout(); 5268 try { 5269 if (!restarting && hasVisibleActivities 5270 && !mStackSupervisor.resumeFocusedStackTopActivityLocked()) { 5271 // If there was nothing to resume, and we are not already restarting this process, but 5272 // there is a visible activity that is hosted by the process... then make sure all 5273 // visible activities are running, taking care of restarting this process. 5274 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 5275 } 5276 } finally { 5277 mWindowManager.continueSurfaceLayout(); 5278 } 5279 } 5280 5281 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) { 5282 final IBinder threadBinder = thread.asBinder(); 5283 // Find the application record. 5284 for (int i=mLruProcesses.size()-1; i>=0; i--) { 5285 final ProcessRecord rec = mLruProcesses.get(i); 5286 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 5287 return i; 5288 } 5289 } 5290 return -1; 5291 } 5292 5293 final ProcessRecord getRecordForAppLocked( 5294 IApplicationThread thread) { 5295 if (thread == null) { 5296 return null; 5297 } 5298 5299 int appIndex = getLRURecordIndexForAppLocked(thread); 5300 if (appIndex >= 0) { 5301 return mLruProcesses.get(appIndex); 5302 } 5303 5304 // Validation: if it isn't in the LRU list, it shouldn't exist, but let's 5305 // double-check that. 5306 final IBinder threadBinder = thread.asBinder(); 5307 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap(); 5308 for (int i = pmap.size()-1; i >= 0; i--) { 5309 final SparseArray<ProcessRecord> procs = pmap.valueAt(i); 5310 for (int j = procs.size()-1; j >= 0; j--) { 5311 final ProcessRecord proc = procs.valueAt(j); 5312 if (proc.thread != null && proc.thread.asBinder() == threadBinder) { 5313 Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: " 5314 + proc); 5315 return proc; 5316 } 5317 } 5318 } 5319 5320 return null; 5321 } 5322 5323 final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) { 5324 // If there are no longer any background processes running, 5325 // and the app that died was not running instrumentation, 5326 // then tell everyone we are now low on memory. 5327 boolean haveBg = false; 5328 for (int i=mLruProcesses.size()-1; i>=0; i--) { 5329 ProcessRecord rec = mLruProcesses.get(i); 5330 if (rec.thread != null 5331 && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 5332 haveBg = true; 5333 break; 5334 } 5335 } 5336 5337 if (!haveBg) { 5338 boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 5339 if (doReport) { 5340 long now = SystemClock.uptimeMillis(); 5341 if (now < (mLastMemUsageReportTime+5*60*1000)) { 5342 doReport = false; 5343 } else { 5344 mLastMemUsageReportTime = now; 5345 } 5346 } 5347 final ArrayList<ProcessMemInfo> memInfos 5348 = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null; 5349 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size()); 5350 long now = SystemClock.uptimeMillis(); 5351 for (int i=mLruProcesses.size()-1; i>=0; i--) { 5352 ProcessRecord rec = mLruProcesses.get(i); 5353 if (rec == dyingProc || rec.thread == null) { 5354 continue; 5355 } 5356 if (doReport) { 5357 memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj, 5358 rec.setProcState, rec.adjType, rec.makeAdjReason())); 5359 } 5360 if ((rec.lastLowMemory+mConstants.GC_MIN_INTERVAL) <= now) { 5361 // The low memory report is overriding any current 5362 // state for a GC request. Make sure to do 5363 // heavy/important/visible/foreground processes first. 5364 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 5365 rec.lastRequestedGc = 0; 5366 } else { 5367 rec.lastRequestedGc = rec.lastLowMemory; 5368 } 5369 rec.reportLowMemory = true; 5370 rec.lastLowMemory = now; 5371 mProcessesToGc.remove(rec); 5372 addProcessToGcListLocked(rec); 5373 } 5374 } 5375 if (doReport) { 5376 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos); 5377 mHandler.sendMessage(msg); 5378 } 5379 scheduleAppGcsLocked(); 5380 } 5381 } 5382 5383 final void appDiedLocked(ProcessRecord app) { 5384 appDiedLocked(app, app.pid, app.thread, false); 5385 } 5386 5387 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, 5388 boolean fromBinderDied) { 5389 // First check if this ProcessRecord is actually active for the pid. 5390 synchronized (mPidsSelfLocked) { 5391 ProcessRecord curProc = mPidsSelfLocked.get(pid); 5392 if (curProc != app) { 5393 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc); 5394 return; 5395 } 5396 } 5397 5398 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 5399 synchronized (stats) { 5400 stats.noteProcessDiedLocked(app.info.uid, pid); 5401 } 5402 5403 if (!app.killed) { 5404 if (!fromBinderDied) { 5405 killProcessQuiet(pid); 5406 } 5407 killProcessGroup(app.uid, pid); 5408 app.killed = true; 5409 } 5410 5411 // Clean up already done if the process has been re-started. 5412 if (app.pid == pid && app.thread != null && 5413 app.thread.asBinder() == thread.asBinder()) { 5414 boolean doLowMem = app.instr == null; 5415 boolean doOomAdj = doLowMem; 5416 if (!app.killedByAm) { 5417 Slog.i(TAG, "Process " + app.processName + " (pid " + pid + ") has died: " 5418 + ProcessList.makeOomAdjString(app.setAdj) 5419 + ProcessList.makeProcStateString(app.setProcState)); 5420 mAllowLowerMemLevel = true; 5421 } else { 5422 // Note that we always want to do oom adj to update our state with the 5423 // new number of procs. 5424 mAllowLowerMemLevel = false; 5425 doLowMem = false; 5426 } 5427 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName, 5428 app.setAdj, app.setProcState); 5429 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 5430 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder()); 5431 handleAppDiedLocked(app, false, true); 5432 5433 if (doOomAdj) { 5434 updateOomAdjLocked(); 5435 } 5436 if (doLowMem) { 5437 doLowMemReportIfNeededLocked(app); 5438 } 5439 } else if (app.pid != pid) { 5440 // A new process has already been started. 5441 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 5442 + ") has died and restarted (pid " + app.pid + ")."); 5443 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 5444 } else if (DEBUG_PROCESSES) { 5445 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread " 5446 + thread.asBinder()); 5447 } 5448 } 5449 5450 /** 5451 * If a stack trace dump file is configured, dump process stack traces. 5452 * @param clearTraces causes the dump file to be erased prior to the new 5453 * traces being written, if true; when false, the new traces will be 5454 * appended to any existing file content. 5455 * @param firstPids of dalvik VM processes to dump stack traces for first 5456 * @param lastPids of dalvik VM processes to dump stack traces for last 5457 * @param nativePids optional list of native pids to dump stack crawls 5458 * @return file containing stack traces, or null if no dump file is configured 5459 */ 5460 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, 5461 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 5462 ArrayList<Integer> nativePids) { 5463 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 5464 if (tracesPath == null || tracesPath.length() == 0) { 5465 return null; 5466 } 5467 5468 File tracesFile = new File(tracesPath); 5469 try { 5470 if (clearTraces && tracesFile.exists()) tracesFile.delete(); 5471 tracesFile.createNewFile(); 5472 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 5473 } catch (IOException e) { 5474 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e); 5475 return null; 5476 } 5477 5478 dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativePids); 5479 return tracesFile; 5480 } 5481 5482 public static class DumpStackFileObserver extends FileObserver { 5483 // Keep in sync with frameworks/native/cmds/dumpstate/utils.cpp 5484 private static final int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds 5485 static final int NATIVE_DUMP_TIMEOUT_MS = 2000; // 2 seconds; 5486 5487 private final String mTracesPath; 5488 private boolean mClosed; 5489 5490 public DumpStackFileObserver(String tracesPath) { 5491 super(tracesPath, FileObserver.CLOSE_WRITE); 5492 mTracesPath = tracesPath; 5493 } 5494 5495 @Override 5496 public synchronized void onEvent(int event, String path) { 5497 mClosed = true; 5498 notify(); 5499 } 5500 5501 public long dumpWithTimeout(int pid, long timeout) { 5502 sendSignal(pid, SIGNAL_QUIT); 5503 final long start = SystemClock.elapsedRealtime(); 5504 5505 final long waitTime = Math.min(timeout, TRACE_DUMP_TIMEOUT_MS); 5506 synchronized (this) { 5507 try { 5508 wait(waitTime); // Wait for traces file to be closed. 5509 } catch (InterruptedException e) { 5510 Slog.wtf(TAG, e); 5511 } 5512 } 5513 5514 // This avoids a corner case of passing a negative time to the native 5515 // trace in case we've already hit the overall timeout. 5516 final long timeWaited = SystemClock.elapsedRealtime() - start; 5517 if (timeWaited >= timeout) { 5518 return timeWaited; 5519 } 5520 5521 if (!mClosed) { 5522 Slog.w(TAG, "Didn't see close of " + mTracesPath + " for pid " + pid + 5523 ". Attempting native stack collection."); 5524 5525 final long nativeDumpTimeoutMs = Math.min( 5526 NATIVE_DUMP_TIMEOUT_MS, timeout - timeWaited); 5527 5528 Debug.dumpNativeBacktraceToFileTimeout(pid, mTracesPath, 5529 (int) (nativeDumpTimeoutMs / 1000)); 5530 } 5531 5532 final long end = SystemClock.elapsedRealtime(); 5533 mClosed = false; 5534 5535 return (end - start); 5536 } 5537 } 5538 5539 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids, 5540 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 5541 ArrayList<Integer> nativePids) { 5542 // Use a FileObserver to detect when traces finish writing. 5543 // The order of traces is considered important to maintain for legibility. 5544 DumpStackFileObserver observer = new DumpStackFileObserver(tracesPath); 5545 5546 // We must complete all stack dumps within 20 seconds. 5547 long remainingTime = 20 * 1000; 5548 try { 5549 observer.startWatching(); 5550 5551 // First collect all of the stacks of the most important pids. 5552 if (firstPids != null) { 5553 int num = firstPids.size(); 5554 for (int i = 0; i < num; i++) { 5555 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for pid " 5556 + firstPids.get(i)); 5557 final long timeTaken = observer.dumpWithTimeout(firstPids.get(i), remainingTime); 5558 5559 remainingTime -= timeTaken; 5560 if (remainingTime <= 0) { 5561 Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + firstPids.get(i) + 5562 "); deadline exceeded."); 5563 return; 5564 } 5565 5566 if (DEBUG_ANR) { 5567 Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms"); 5568 } 5569 } 5570 } 5571 5572 // Next collect the stacks of the native pids 5573 if (nativePids != null) { 5574 for (int pid : nativePids) { 5575 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for native pid " + pid); 5576 final long nativeDumpTimeoutMs = Math.min( 5577 DumpStackFileObserver.NATIVE_DUMP_TIMEOUT_MS, remainingTime); 5578 5579 final long start = SystemClock.elapsedRealtime(); 5580 Debug.dumpNativeBacktraceToFileTimeout( 5581 pid, tracesPath, (int) (nativeDumpTimeoutMs / 1000)); 5582 final long timeTaken = SystemClock.elapsedRealtime() - start; 5583 5584 remainingTime -= timeTaken; 5585 if (remainingTime <= 0) { 5586 Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid + 5587 "); deadline exceeded."); 5588 return; 5589 } 5590 5591 if (DEBUG_ANR) { 5592 Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms"); 5593 } 5594 } 5595 } 5596 5597 // Lastly, measure CPU usage. 5598 if (processCpuTracker != null) { 5599 processCpuTracker.init(); 5600 System.gc(); 5601 processCpuTracker.update(); 5602 try { 5603 synchronized (processCpuTracker) { 5604 processCpuTracker.wait(500); // measure over 1/2 second. 5605 } 5606 } catch (InterruptedException e) { 5607 } 5608 processCpuTracker.update(); 5609 5610 // We'll take the stack crawls of just the top apps using CPU. 5611 final int N = processCpuTracker.countWorkingStats(); 5612 int numProcs = 0; 5613 for (int i=0; i<N && numProcs<5; i++) { 5614 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i); 5615 if (lastPids.indexOfKey(stats.pid) >= 0) { 5616 numProcs++; 5617 5618 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid); 5619 5620 final long timeTaken = observer.dumpWithTimeout(stats.pid, remainingTime); 5621 remainingTime -= timeTaken; 5622 if (remainingTime <= 0) { 5623 Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + stats.pid + 5624 "); deadline exceeded."); 5625 return; 5626 } 5627 5628 if (DEBUG_ANR) { 5629 Slog.d(TAG, "Done with extra pid " + stats.pid + " in " + timeTaken + "ms"); 5630 } 5631 } else if (DEBUG_ANR) {