• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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.wm;
18 
19 import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20 import static android.Manifest.permission.CHANGE_CONFIGURATION;
21 import static android.Manifest.permission.CONTROL_KEYGUARD;
22 import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
23 import static android.Manifest.permission.DETECT_SCREEN_CAPTURE;
24 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
25 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
26 import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
27 import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
28 import static android.Manifest.permission.MANAGE_ACTIVITY_TASKS;
29 import static android.Manifest.permission.MANAGE_GAME_ACTIVITY;
30 import static android.Manifest.permission.READ_FRAME_BUFFER;
31 import static android.Manifest.permission.REMOVE_TASKS;
32 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
33 import static android.Manifest.permission.STOP_APP_SWITCHES;
34 import static android.app.ActivityManager.DROP_CLOSE_SYSTEM_DIALOGS;
35 import static android.app.ActivityManager.LOCK_DOWN_CLOSE_SYSTEM_DIALOGS;
36 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
37 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
38 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
39 import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
40 import static android.app.WindowConfiguration.ACTIVITY_TYPE_DREAM;
41 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
42 import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
43 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
44 import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
45 import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
46 import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47 import static android.content.pm.PackageManager.FEATURE_CANT_SAVE_STATE;
48 import static android.content.pm.PackageManager.FEATURE_COMPANION_DEVICE_SETUP;
49 import static android.content.pm.PackageManager.FEATURE_EXPANDED_PICTURE_IN_PICTURE;
50 import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
51 import static android.content.pm.PackageManager.FEATURE_LEANBACK;
52 import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
53 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
54 import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55 import static android.os.InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
56 import static android.os.Process.FIRST_APPLICATION_UID;
57 import static android.os.Process.SYSTEM_UID;
58 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
59 import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60 import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_NON_RESIZABLE_MULTI_WINDOW;
61 import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
62 import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
63 import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
64 import static android.provider.Settings.System.FONT_SCALE;
65 import static android.service.controls.flags.Flags.homePanelDream;
66 import static android.view.Display.DEFAULT_DISPLAY;
67 import static android.view.Display.INVALID_DISPLAY;
68 import static android.view.WindowManager.TRANSIT_CHANGE;
69 import static android.view.WindowManager.TRANSIT_PIP;
70 import static android.view.WindowManager.TRANSIT_TO_FRONT;
71 import static android.view.WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_TO_LAUNCHER_CLEAR_SNAPSHOT;
72 import static android.window.TransitionInfo.FLAG_IN_TASK_WITH_EMBEDDED_ACTIVITY;
73 
74 import static com.android.internal.protolog.WmProtoLogGroups.WM_DEBUG_CONFIGURATION;
75 import static com.android.internal.protolog.WmProtoLogGroups.WM_DEBUG_DREAM;
76 import static com.android.internal.protolog.WmProtoLogGroups.WM_DEBUG_FOCUS;
77 import static com.android.internal.protolog.WmProtoLogGroups.WM_DEBUG_IMMERSIVE;
78 import static com.android.internal.protolog.WmProtoLogGroups.WM_DEBUG_LOCKTASK;
79 import static com.android.internal.protolog.WmProtoLogGroups.WM_DEBUG_TASKS;
80 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
81 import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
82 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
83 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
84 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
85 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
86 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
87 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
88 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
89 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
90 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
91 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
92 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
93 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
94 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
95 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
96 import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
97 import static com.android.server.am.EventLogTags.writeConfigurationChanged;
98 import static com.android.server.am.StackTracesDumpHelper.ANR_TRACE_DIR;
99 import static com.android.server.wm.ActivityInterceptorCallback.MAINLINE_FIRST_ORDERED_ID;
100 import static com.android.server.wm.ActivityInterceptorCallback.MAINLINE_LAST_ORDERED_ID;
101 import static com.android.server.wm.ActivityInterceptorCallback.SYSTEM_FIRST_ORDERED_ID;
102 import static com.android.server.wm.ActivityInterceptorCallback.SYSTEM_LAST_ORDERED_ID;
103 import static com.android.server.wm.ActivityRecord.State.DESTROYED;
104 import static com.android.server.wm.ActivityRecord.State.DESTROYING;
105 import static com.android.server.wm.ActivityRecord.State.FINISHING;
106 import static com.android.server.wm.ActivityRecord.State.PAUSING;
107 import static com.android.server.wm.ActivityRecord.State.RESUMED;
108 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ACTIVITY_STARTS;
109 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
110 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_ROOT_TASK;
111 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
112 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
113 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
114 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
115 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
116 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
117 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
118 import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
119 import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
120 import static com.android.server.wm.ActivityTaskSupervisor.DEFER_RESUME;
121 import static com.android.server.wm.ActivityTaskSupervisor.ON_TOP;
122 import static com.android.server.wm.ActivityTaskSupervisor.REMOVE_FROM_RECENTS;
123 import static com.android.server.wm.BackgroundActivityStartController.BalVerdict;
124 import static com.android.server.wm.LockTaskController.LOCK_TASK_AUTH_DONT_LOCK;
125 import static com.android.server.wm.RootWindowContainer.MATCH_ATTACHED_TASK_ONLY;
126 import static com.android.server.wm.RootWindowContainer.MATCH_ATTACHED_TASK_OR_RECENT_TASKS;
127 import static com.android.server.wm.Task.REPARENT_KEEP_ROOT_TASK_AT_FRONT;
128 import static com.android.server.wm.WindowManagerService.MY_PID;
129 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_NORMAL;
130 
131 import android.Manifest;
132 import android.annotation.IntDef;
133 import android.annotation.NonNull;
134 import android.annotation.Nullable;
135 import android.annotation.UserIdInt;
136 import android.app.ActivityManager;
137 import android.app.ActivityManagerInternal;
138 import android.app.ActivityOptions;
139 import android.app.ActivityTaskManager;
140 import android.app.ActivityTaskManager.RootTaskInfo;
141 import android.app.ActivityThread;
142 import android.app.AlertDialog;
143 import android.app.AnrController;
144 import android.app.AppGlobals;
145 import android.app.AppOpsManager;
146 import android.app.Dialog;
147 import android.app.IActivityClientController;
148 import android.app.IActivityController;
149 import android.app.IActivityTaskManager;
150 import android.app.IAppTask;
151 import android.app.IApplicationThread;
152 import android.app.IAssistDataReceiver;
153 import android.app.INotificationManager;
154 import android.app.IScreenCaptureObserver;
155 import android.app.ITaskStackListener;
156 import android.app.Notification;
157 import android.app.NotificationManager;
158 import android.app.PendingIntent;
159 import android.app.PictureInPictureParams;
160 import android.app.PictureInPictureUiState;
161 import android.app.ProfilerInfo;
162 import android.app.WaitResult;
163 import android.app.admin.DevicePolicyCache;
164 import android.app.admin.DeviceStateCache;
165 import android.app.assist.ActivityId;
166 import android.app.assist.AssistContent;
167 import android.app.assist.AssistStructure;
168 import android.app.compat.CompatChanges;
169 import android.app.sdksandbox.sandboxactivity.SdkSandboxActivityAuthority;
170 import android.app.usage.UsageStatsManagerInternal;
171 import android.content.ActivityNotFoundException;
172 import android.content.ComponentName;
173 import android.content.ContentResolver;
174 import android.content.Context;
175 import android.content.DialogInterface;
176 import android.content.IIntentSender;
177 import android.content.Intent;
178 import android.content.LocusId;
179 import android.content.pm.ActivityInfo;
180 import android.content.pm.ApplicationInfo;
181 import android.content.pm.ConfigurationInfo;
182 import android.content.pm.FeatureInfo;
183 import android.content.pm.IPackageManager;
184 import android.content.pm.PackageManager;
185 import android.content.pm.PackageManagerInternal;
186 import android.content.pm.ParceledListSlice;
187 import android.content.pm.ResolveInfo;
188 import android.content.pm.UserInfo;
189 import android.content.res.CompatibilityInfo;
190 import android.content.res.Configuration;
191 import android.content.res.Resources;
192 import android.database.ContentObserver;
193 import android.graphics.Bitmap;
194 import android.graphics.Point;
195 import android.graphics.Rect;
196 import android.net.Uri;
197 import android.os.Binder;
198 import android.os.Build;
199 import android.os.Bundle;
200 import android.os.FactoryTest;
201 import android.os.Handler;
202 import android.os.IBinder;
203 import android.os.IUserManager;
204 import android.os.LocaleList;
205 import android.os.Looper;
206 import android.os.Message;
207 import android.os.Parcel;
208 import android.os.PowerManager;
209 import android.os.PowerManagerInternal;
210 import android.os.Process;
211 import android.os.RemoteCallback;
212 import android.os.RemoteException;
213 import android.os.ServiceManager;
214 import android.os.SystemClock;
215 import android.os.SystemProperties;
216 import android.os.Trace;
217 import android.os.UpdateLock;
218 import android.os.UserHandle;
219 import android.os.UserManager;
220 import android.os.WorkSource;
221 import android.provider.Settings;
222 import android.service.dreams.DreamActivity;
223 import android.service.voice.IVoiceInteractionSession;
224 import android.service.voice.VoiceInteractionManagerInternal;
225 import android.sysprop.DisplayProperties;
226 import android.telecom.TelecomManager;
227 import android.util.ArrayMap;
228 import android.util.ArraySet;
229 import android.util.IntArray;
230 import android.util.Log;
231 import android.util.Slog;
232 import android.util.SparseArray;
233 import android.util.TimeUtils;
234 import android.util.proto.ProtoOutputStream;
235 import android.view.Display;
236 import android.view.RemoteAnimationAdapter;
237 import android.view.RemoteAnimationDefinition;
238 import android.view.WindowManager;
239 import android.window.BackAnimationAdapter;
240 import android.window.BackNavigationInfo;
241 import android.window.IWindowOrganizerController;
242 import android.window.SplashScreenView.SplashScreenViewParcelable;
243 import android.window.TaskSnapshot;
244 
245 import com.android.internal.R;
246 import com.android.internal.annotations.GuardedBy;
247 import com.android.internal.annotations.VisibleForTesting;
248 import com.android.internal.app.IVoiceInteractor;
249 import com.android.internal.app.ProcessMap;
250 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
251 import com.android.internal.notification.SystemNotificationChannels;
252 import com.android.internal.os.TransferPipe;
253 import com.android.internal.policy.AttributeCache;
254 import com.android.internal.policy.KeyguardDismissCallback;
255 import com.android.internal.protolog.ProtoLog;
256 import com.android.internal.util.ArrayUtils;
257 import com.android.internal.util.FastPrintWriter;
258 import com.android.internal.util.FrameworkStatsLog;
259 import com.android.internal.util.function.pooled.PooledLambda;
260 import com.android.server.LocalManagerRegistry;
261 import com.android.server.LocalServices;
262 import com.android.server.SystemConfig;
263 import com.android.server.SystemService;
264 import com.android.server.SystemServiceManager;
265 import com.android.server.UiThread;
266 import com.android.server.Watchdog;
267 import com.android.server.am.ActivityManagerService;
268 import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
269 import com.android.server.am.AppTimeTracker;
270 import com.android.server.am.AssistDataRequester;
271 import com.android.server.am.BaseErrorDialog;
272 import com.android.server.am.PendingIntentController;
273 import com.android.server.am.PendingIntentRecord;
274 import com.android.server.am.UserState;
275 import com.android.server.firewall.IntentFirewall;
276 import com.android.server.grammaticalinflection.GrammaticalInflectionManagerInternal;
277 import com.android.server.pm.UserManagerInternal;
278 import com.android.server.pm.UserManagerService;
279 import com.android.server.policy.PermissionPolicyInternal;
280 import com.android.server.sdksandbox.SdkSandboxManagerLocal;
281 import com.android.server.statusbar.StatusBarManagerInternal;
282 import com.android.server.uri.NeededUriGrants;
283 import com.android.server.uri.UriGrantsManagerInternal;
284 import com.android.server.wm.utils.WindowStyleCache;
285 import com.android.wm.shell.Flags;
286 
287 import java.io.BufferedReader;
288 import java.io.File;
289 import java.io.FileDescriptor;
290 import java.io.FileReader;
291 import java.io.IOException;
292 import java.io.PrintWriter;
293 import java.io.StringWriter;
294 import java.lang.annotation.ElementType;
295 import java.lang.annotation.Retention;
296 import java.lang.annotation.RetentionPolicy;
297 import java.lang.annotation.Target;
298 import java.lang.ref.WeakReference;
299 import java.text.DateFormat;
300 import java.util.ArrayList;
301 import java.util.Arrays;
302 import java.util.Collection;
303 import java.util.Collections;
304 import java.util.Date;
305 import java.util.HashSet;
306 import java.util.List;
307 import java.util.Map;
308 import java.util.Objects;
309 import java.util.Set;
310 import java.util.function.Supplier;
311 
312 /**
313  * System service for managing activities and their containers (task, displays,... ).
314  *
315  * {@hide}
316  */
317 public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
318     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
319     static final String TAG_ROOT_TASK = TAG + POSTFIX_ROOT_TASK;
320     static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
321 
322     // How long we wait until we timeout on key dispatching during instrumentation.
323     static final long INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MILLIS = 60 * 1000;
324     // How long we permit background activity starts after an activity in the process
325     // started or finished.
326     static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
327 
328     /**
329      * The duration to keep a process in animating state (top scheduling group) when the
330      * wakefulness is dozing (unlocking) or changing from awake to doze or sleep (locking).
331      */
332     private static final long DOZE_ANIMATING_STATE_RETAIN_TIME_MS = 2000;
333 
334     /** Used to indicate that an app transition should be animated. */
335     static final boolean ANIMATE = true;
336 
337     /** Hardware-reported OpenGLES version. */
338     final int GL_ES_VERSION;
339 
340     public static final String DUMP_ACTIVITIES_CMD = "activities";
341     public static final String DUMP_ACTIVITIES_SHORT_CMD = "a";
342     public static final String DUMP_LASTANR_CMD = "lastanr";
343     public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces";
344     public static final String DUMP_STARTER_CMD = "starter";
345     public static final String DUMP_CONTAINERS_CMD = "containers";
346     public static final String DUMP_RECENTS_CMD = "recents";
347     public static final String DUMP_RECENTS_SHORT_CMD = "r";
348     public static final String DUMP_TOP_RESUMED_ACTIVITY = "top-resumed";
349     public static final String DUMP_VISIBLE_ACTIVITIES = "visible";
350 
351     /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
352     public static final int RELAUNCH_REASON_NONE = 0;
353     /** This activity is being relaunched due to windowing mode change. */
354     public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
355     /** This activity is being relaunched due to a free-resize operation. */
356     public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
357 
358     Context mContext;
359 
360     /**
361      * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
362      * change at runtime. Use mContext for non-UI purposes.
363      */
364     private final Context mUiContext;
365     final ActivityThread mSystemThread;
366     H mH;
367     UiHandler mUiHandler;
368     ActivityManagerInternal mAmInternal;
369     UriGrantsManagerInternal mUgmInternal;
370     private PackageManagerInternal mPmInternal;
371     /** The cached sys ui service component name from package manager. */
372     private ComponentName mSysUiServiceComponent;
373     private PermissionPolicyInternal mPermissionPolicyInternal;
374     private StatusBarManagerInternal mStatusBarManagerInternal;
375     private UserManagerInternal mUserManagerInternal;
376     @VisibleForTesting
377     final ActivityTaskManagerInternal mInternal;
378     private PowerManagerInternal mPowerManagerInternal;
379     private UsageStatsManagerInternal mUsageStatsInternal;
380 
381     GrammaticalInflectionManagerInternal mGrammaticalManagerInternal;
382     PendingIntentController mPendingIntentController;
383     IntentFirewall mIntentFirewall;
384 
385     final VisibleActivityProcessTracker mVisibleActivityProcessTracker;
386 
387     /** The starting activities which are waiting for their processes to attach. */
388     final ArrayList<ActivityRecord> mStartingProcessActivities = new ArrayList<>();
389 
390     /* Global service lock used by the package the owns this service. */
391     final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
392     /**
393      * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
394      * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
395      * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
396      *
397      * @see WindowManagerThreadPriorityBooster
398      */
399     final Object mGlobalLockWithoutBoost = mGlobalLock;
400     ActivityTaskSupervisor mTaskSupervisor;
401     ActivityClientController mActivityClientController;
402     RootWindowContainer mRootWindowContainer;
403     WindowManagerService mWindowManager;
404     private UserManagerService mUserManager;
405     private AppOpsManager mAppOpsManager;
406     /** All active uids in the system. */
407     final MirrorActiveUids mActiveUids = new MirrorActiveUids();
408     /** All processes currently running that might have a window organized by name. */
409     final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
410     /** All processes we currently have running mapped by pid and uid */
411     final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
412     /** This is the process holding what we currently consider to be the "home" activity. */
413     volatile WindowProcessController mHomeProcess;
414     /** The currently running heavy-weight process, if any. */
415     volatile WindowProcessController mHeavyWeightProcess;
416     boolean mHasHeavyWeightFeature;
417     boolean mHasLeanbackFeature;
418     boolean mHasCompanionDeviceSetupFeature;
419     /** The process of the top most activity. */
420     volatile WindowProcessController mTopApp;
421     /** The process showing UI while the device is dozing. */
422     volatile WindowProcessController mVisibleDozeUiProcess;
423     /**
424      * This is the process holding the activity the user last visited that is in a different process
425      * from the one they are currently in.
426      */
427     volatile WindowProcessController mPreviousProcess;
428     /** The time at which the previous process was last visible. */
429     private long mPreviousProcessVisibleTime;
430 
431     /** It is set from keyguard-going-away to set-keyguard-shown. */
432     static final int DEMOTE_TOP_REASON_DURING_UNLOCKING = 1;
433     /** It is set when notification shade occludes the foreground app. */
434     static final int DEMOTE_TOP_REASON_EXPANDED_NOTIFICATION_SHADE = 1 << 1;
435 
436     @Retention(RetentionPolicy.SOURCE)
437     @IntDef({
438             DEMOTE_TOP_REASON_DURING_UNLOCKING,
439             DEMOTE_TOP_REASON_EXPANDED_NOTIFICATION_SHADE,
440     })
441     @interface DemoteTopReason {}
442 
443     /**
444      * If non-zero, getTopProcessState() will
445      * return {@link ActivityManager#PROCESS_STATE_IMPORTANT_FOREGROUND} to avoid top app from
446      * preempting CPU while another process is running an important animation.
447      */
448     @DemoteTopReason
449     volatile int mDemoteTopAppReasons;
450 
451     /** List of intents that were used to start the most recent tasks. */
452     private RecentTasks mRecentTasks;
453     /** State of external calls telling us if the device is awake or asleep. */
454     private boolean mKeyguardShown = false;
455 
456     // VoiceInteraction session ID that changes for each new request except when
457     // being called for multi-window assist in a single session.
458     private int mViSessionId = 1000;
459 
460     // How long to wait in getAssistContextExtras for the activity and foreground services
461     // to respond with the result.
462     private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
463 
464     // How long top wait when going through the modern assist (which doesn't need to block
465     // on getting this result before starting to launch its UI).
466     private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
467 
468     // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
469     private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
470 
471     private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
472 
473     // Keeps track of the active voice interaction service component, notified from
474     // VoiceInteractionManagerService
475     ComponentName mActiveVoiceInteractionServiceComponent;
476 
477     // A map userId and all its companion app uids
478     private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
479 
480     VrController mVrController;
481     KeyguardController mKeyguardController;
482     private final ClientLifecycleManager mLifecycleManager;
483 
484     final BackNavigationController mBackNavigationController;
485 
486     private TaskChangeNotificationController mTaskChangeNotificationController;
487     /** The controller for all operations related to locktask. */
488     private LockTaskController mLockTaskController;
489     private ActivityStartController mActivityStartController;
490     private SparseArray<ActivityInterceptorCallback> mActivityInterceptorCallbacks =
491             new SparseArray<>();
492     PackageConfigPersister mPackageConfigPersister;
493 
494     boolean mSuppressResizeConfigChanges;
495 
496     private final WindowStyleCache<ActivityRecord.WindowStyle> mWindowStyleCache =
497             new WindowStyleCache<>(ActivityRecord.WindowStyle::new);
498     final UpdateConfigurationResult mTmpUpdateConfigurationResult =
499             new UpdateConfigurationResult();
500 
501     // TODO(b/258618073): Remove this and make the related methods return whether config is changed.
502     static final class UpdateConfigurationResult {
503         // Configuration changes that were updated.
504         int changes;
505         // If the activity was relaunched to match the new configuration.
506         boolean activityRelaunched;
507     }
508 
509     /** Current sequencing integer of the configuration, for skipping old configurations. */
510     private int mConfigurationSeq;
511 
512     /** Current sequencing integer of the asset changes, for skipping old resources overlays. */
513     private int mGlobalAssetsSeq;
514 
515     // To cache the list of supported system locales
516     private String[] mSupportedSystemLocales = null;
517 
518     /**
519      * Temp object used when global and/or display override configuration is updated. It is also
520      * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
521      * anyone...
522      */
523     private Configuration mTempConfig = new Configuration();
524 
525     /**
526      * Whether normal application switches are allowed; a call to {@link #stopAppSwitches()
527      * disables this.
528      */
529     private volatile int mAppSwitchesState = APP_SWITCH_ALLOW;
530 
531     // The duration of resuming foreground app switch from disallow.
532     private static final long RESUME_FG_APP_SWITCH_MS = 500;
533 
534     /** App switch is not allowed. */
535     static final int APP_SWITCH_DISALLOW = 0;
536 
537     /** App switch is allowed only if the activity launch was requested by a foreground app. */
538     static final int APP_SWITCH_FG_ONLY = 1;
539 
540     /** App switch is allowed. */
541     static final int APP_SWITCH_ALLOW = 2;
542 
543     @IntDef({
544             APP_SWITCH_DISALLOW,
545             APP_SWITCH_FG_ONLY,
546             APP_SWITCH_ALLOW,
547     })
548     @Retention(RetentionPolicy.SOURCE)
549     @interface AppSwitchState {}
550 
551     /**
552      * Last stop app switches time, apps finished before this time cannot start background activity
553      * even if they are in grace period.
554      */
555     private volatile long mLastStopAppSwitchesTime;
556 
557     @GuardedBy("itself")
558     private final List<AnrController> mAnrController = new ArrayList<>();
559     IActivityController mController = null;
560     boolean mControllerIsAMonkey = false;
561 
562     final int mFactoryTest;
563 
564     /** Used to control how we initialize the service. */
565     ComponentName mTopComponent;
566     String mTopAction = Intent.ACTION_MAIN;
567     String mTopData;
568 
569     /** Profiling app information. */
570     String mProfileApp = null;
571     WindowProcessController mProfileProc = null;
572     ProfilerInfo mProfilerInfo = null;
573 
574     /**
575      * Dump of the activity state at the time of the last ANR. Cleared after
576      * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
577      */
578     String mLastANRState;
579 
580     /**
581      * Used to retain an update lock when the foreground activity is in
582      * immersive mode.
583      */
584     private final UpdateLock mUpdateLock = new UpdateLock("immersive");
585 
586     /**
587      * Packages that are being allowed to perform unrestricted app switches.  Mapping is
588      * User -> Type -> uid.
589      */
590     final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
591 
592     /** The dimensions of the thumbnails in the Recents UI. */
593     private int mThumbnailWidth;
594     private int mThumbnailHeight;
595 
596     /**
597      * Flag that indicates if multi-window is enabled.
598      *
599      * For any particular form of multi-window to be enabled, generic multi-window must be enabled
600      * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
601      * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
602      * At least one of the forms of multi-window must be enabled in order for this flag to be
603      * initialized to 'true'.
604      *
605      * @see #mSupportsSplitScreenMultiWindow
606      * @see #mSupportsFreeformWindowManagement
607      * @see #mSupportsPictureInPicture
608      * @see #mSupportsMultiDisplay
609      */
610     boolean mSupportsMultiWindow;
611     boolean mSupportsSplitScreenMultiWindow;
612     boolean mSupportsFreeformWindowManagement;
613     boolean mSupportsPictureInPicture;
614     boolean mSupportsExpandedPictureInPicture;
615     boolean mSupportsMultiDisplay;
616     boolean mForceResizableActivities;
617 
618     /** Development option to enable non resizable in multi window. */
619     // TODO(b/176061101) change the default value to false.
620     boolean mDevEnableNonResizableMultiWindow;
621 
622     /**
623      * Whether the device supports non-resizable in multi windowing modes.
624      * -1: The device doesn't support non-resizable in multi windowing modes.
625      *  0: The device supports non-resizable in multi windowing modes only if this is a large
626      *     screen (smallest width >= {@link WindowManager#LARGE_SCREEN_SMALLEST_SCREEN_WIDTH_DP}).
627      *  1: The device always supports non-resizable in multi windowing modes.
628      */
629     int mSupportsNonResizableMultiWindow;
630 
631     /**
632      * Whether the device checks activity min width/height to determine if it can be shown in multi
633      * windowing modes.
634      * -1: The device ignores activity min width/height when determining if it can be shown in multi
635      *     windowing modes.
636      *  0: If it is a small screen (smallest width <
637      *     {@link WindowManager#LARGE_SCREEN_SMALLEST_SCREEN_WIDTH_DP}),
638      *     the device compares the activity min width/height with the min multi windowing modes
639      *     dimensions {@link #mMinPercentageMultiWindowSupportHeight} the device supports to
640      *     determine whether the activity can be shown in multi windowing modes
641      *  1: The device always compare the activity min width/height with the min multi windowing
642      *     modes dimensions {@link #mMinPercentageMultiWindowSupportHeight} the device supports to
643      *     determine whether it can be shown in multi windowing modes.
644      */
645     int mRespectsActivityMinWidthHeightMultiWindow;
646 
647     /**
648      * This value is only used when the device checks activity min height to determine if it
649      * can be shown in multi windowing modes.
650      * If the activity min height is greater than this percentage of the display height in portrait,
651      * it will not be allowed to be shown in multi windowing modes.
652      * The value should be between [0 - 1].
653      */
654     float mMinPercentageMultiWindowSupportHeight;
655 
656     /**
657      * This value is only used when the device checks activity min width to determine if it
658      * can be shown in multi windowing modes.
659      * If the activity min width is greater than this percentage of the display width in landscape,
660      * it will not be allowed to be shown in multi windowing modes.
661      * The value should be between [0 - 1].
662      */
663     float mMinPercentageMultiWindowSupportWidth;
664 
665     final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers =
666             Collections.synchronizedList(new ArrayList<>());
667 
668     // VR Vr2d Display Id.
669     int mVr2dDisplayId = INVALID_DISPLAY;
670 
671     /**
672      * Set while we are wanting to sleep, to prevent any
673      * activities from being started/resumed.
674      *
675      * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
676      *
677      * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
678      * while in the sleep state until there is a pending transition out of sleep, in which case
679      * mSleeping is set to false, and remains false while awake.
680      *
681      * Whether mSleeping can quickly toggled between true/false without the device actually
682      * display changing states is undefined.
683      */
684     private volatile boolean mSleeping;
685 
686     /**
687      * The mActiveDreamComponent state is set by the {@link DreamManagerService} when it receives a
688      * request to start/stop the dream. It is set to the active dream shortly before the
689      * {@link DreamService} is started. It is set to null after the {@link DreamService} is stopped.
690      */
691     @Nullable
692     private volatile ComponentName mActiveDreamComponent;
693 
694     /**
695      * The process state used for processes that are running the top activities.
696      * This changes between TOP and TOP_SLEEPING to following mSleeping.
697      */
698     volatile int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
699 
700     /** Whether to keep higher priority to launch app while device is sleeping. */
701     private volatile boolean mRetainPowerModeAndTopProcessState;
702 
703     /** The timeout to restore power mode if {@link #mRetainPowerModeAndTopProcessState} is set. */
704     private static final long POWER_MODE_UNKNOWN_VISIBILITY_TIMEOUT_MS = 1000;
705 
706     @Retention(RetentionPolicy.SOURCE)
707     @IntDef({
708             POWER_MODE_REASON_START_ACTIVITY,
709             POWER_MODE_REASON_CHANGE_DISPLAY,
710             POWER_MODE_REASON_UNKNOWN_VISIBILITY,
711             POWER_MODE_REASON_ALL,
712     })
713     @interface PowerModeReason {}
714 
715     static final int POWER_MODE_REASON_START_ACTIVITY = 1 << 0;
716     static final int POWER_MODE_REASON_CHANGE_DISPLAY = 1 << 1;
717     /** @see UnknownAppVisibilityController */
718     static final int POWER_MODE_REASON_UNKNOWN_VISIBILITY = 1 << 2;
719     /**
720      * This can only be used by {@link #endPowerMode(int)}. Excluding UNKNOWN_VISIBILITY because
721      * that is guarded by a timeout while keyguard is locked.
722      */
723     static final int POWER_MODE_REASON_ALL = (1 << 2) - 1;
724 
725     /** The reasons to apply power modes. */
726     @PowerModeReason
727     private int mPowerModeReasons;
728 
729     @Retention(RetentionPolicy.SOURCE)
730     @IntDef({
731             LAYOUT_REASON_CONFIG_CHANGED,
732             LAYOUT_REASON_VISIBILITY_CHANGED,
733     })
734     @interface LayoutReason {
735     }
736 
737     static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
738     static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
739 
740     /** The reasons to perform surface placement. */
741     @LayoutReason
742     private int mLayoutReasons;
743 
744     // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
745     // automatically. Important for devices without direct input devices.
746     private boolean mShowDialogs = true;
747 
748     /** Set if we are shutting down the system, similar to sleeping. */
749     volatile boolean mShuttingDown;
750 
751     /**
752      * We want to hold a wake lock while running a voice interaction session, since
753      * this may happen with the screen off and we need to keep the CPU running to
754      * be able to continue to interact with the user.
755      */
756     PowerManager.WakeLock mVoiceWakeLock;
757 
758     /**
759      * Set while we are running a voice interaction. This overrides sleeping while it is active.
760      */
761     IVoiceInteractionSession mRunningVoice;
762 
763     /**
764      * The last resumed activity. This is identical to the current resumed activity most
765      * of the time but could be different when we're pausing one activity before we resume
766      * another activity.
767      */
768     ActivityRecord mLastResumedActivity;
769 
770     /**
771      * The activity that is currently being traced as the active resumed activity.
772      *
773      * @see #updateResumedAppTrace
774      */
775     @Nullable
776     private ActivityRecord mTracedResumedActivity;
777 
778     /** If non-null, we are tracking the time the user spends in the currently focused app. */
779     AppTimeTracker mCurAppTimeTracker;
780 
781     AppWarnings mAppWarnings;
782 
783     /**
784      * Packages that the user has asked to have run in screen size
785      * compatibility mode instead of filling the screen.
786      */
787     CompatModePackages mCompatModePackages;
788 
789     private SettingObserver mSettingsObserver;
790 
791     WindowOrganizerController mWindowOrganizerController;
792     TaskOrganizerController mTaskOrganizerController;
793     TaskFragmentOrganizerController mTaskFragmentOrganizerController;
794     ActionChain.Tracker mChainTracker;
795 
796     @Nullable
797     private BackgroundActivityStartCallback mBackgroundActivityStartCallback;
798 
799     private int[] mAccessibilityServiceUids = new int[0];
800 
801     private int mDeviceOwnerUid = Process.INVALID_UID;
802 
803     private Set<Integer> mProfileOwnerUids = new ArraySet<Integer>();
804 
805     private final class SettingObserver extends ContentObserver {
806         private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
807         private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
808         private final Uri mFontWeightAdjustmentUri = Settings.Secure.getUriFor(
809                 Settings.Secure.FONT_WEIGHT_ADJUSTMENT);
810 
SettingObserver()811         SettingObserver() {
812             super(mH);
813             final ContentResolver resolver = mContext.getContentResolver();
814             resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
815             resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
816                     UserHandle.USER_ALL);
817             resolver.registerContentObserver(
818                     mFontWeightAdjustmentUri, false, this, UserHandle.USER_ALL);
819         }
820 
821         @Override
onChange(boolean selfChange, Collection<Uri> uris, int flags, @UserIdInt int userId)822         public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
823                 @UserIdInt int userId) {
824             for (Uri uri : uris) {
825                 if (mFontScaleUri.equals(uri)) {
826                     updateFontScaleIfNeeded(userId);
827                 } else if (mHideErrorDialogsUri.equals(uri)) {
828                     synchronized (mGlobalLock) {
829                         updateShouldShowDialogsLocked(getGlobalConfiguration());
830                     }
831                 } else if (mFontWeightAdjustmentUri.equals(uri)) {
832                     updateFontWeightAdjustmentIfNeeded(userId);
833                 }
834             }
835         }
836     }
837 
838     /** Indicates that the method may be invoked frequently or is sensitive to performance. */
839     @Target(ElementType.METHOD)
840     @Retention(RetentionPolicy.SOURCE)
841     @interface HotPath {
842         int NONE = 0;
843         int OOM_ADJUSTMENT = 1;
844         int LRU_UPDATE = 2;
845         int PROCESS_CHANGE = 3;
846         int START_SERVICE = 4;
847 
caller()848         int caller() default NONE;
849     }
850 
851     private final Runnable mUpdateOomAdjRunnable = new Runnable() {
852         @Override
853         public void run() {
854             mAmInternal.updateOomAdj(ActivityManagerInternal.OOM_ADJ_REASON_ACTIVITY);
855         }
856     };
857 
858     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
ActivityTaskManagerService(Context context)859     public ActivityTaskManagerService(Context context) {
860         mContext = context;
861         mFactoryTest = FactoryTest.getMode();
862         mSystemThread = ActivityThread.currentActivityThread();
863         mUiContext = mSystemThread.getSystemUiContext();
864         mLifecycleManager = new ClientLifecycleManager();
865         mVisibleActivityProcessTracker = new VisibleActivityProcessTracker(this);
866         mInternal = new LocalService();
867         GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
868         mWindowOrganizerController = new WindowOrganizerController(this);
869         mChainTracker = new ActionChain.Tracker(this);
870         mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
871         mTaskFragmentOrganizerController =
872                 mWindowOrganizerController.mTaskFragmentOrganizerController;
873         mBackNavigationController = new BackNavigationController();
874     }
875 
onSystemReady()876     public void onSystemReady() {
877         synchronized (mGlobalLock) {
878             final PackageManager pm = mContext.getPackageManager();
879             mHasHeavyWeightFeature = pm.hasSystemFeature(FEATURE_CANT_SAVE_STATE);
880             mHasLeanbackFeature = pm.hasSystemFeature(FEATURE_LEANBACK);
881             mHasCompanionDeviceSetupFeature = pm.hasSystemFeature(FEATURE_COMPANION_DEVICE_SETUP);
882             mVrController.onSystemReady();
883             mRecentTasks.onSystemReadyLocked();
884             mTaskSupervisor.onSystemReady();
885             mActivityClientController.onSystemReady();
886             mAppWarnings.onSystemReady();
887             // TODO(b/258792202) Cleanup once ASM is ready to launch
888             ActivitySecurityModelFeatureFlags.initialize(mContext.getMainExecutor());
889             mGrammaticalManagerInternal = LocalServices.getService(
890                     GrammaticalInflectionManagerInternal.class);
891         }
892     }
893 
onInitPowerManagement()894     public void onInitPowerManagement() {
895         synchronized (mGlobalLock) {
896             mTaskSupervisor.initPowerManagement();
897             final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
898             mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
899             mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
900             mVoiceWakeLock.setReferenceCounted(false);
901         }
902     }
903 
installSystemProviders()904     public void installSystemProviders() {
905         mSettingsObserver = new SettingObserver();
906     }
907 
retrieveSettings(ContentResolver resolver)908     public void retrieveSettings(ContentResolver resolver) {
909         final boolean freeformWindowManagement =
910                 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
911                         || Settings.Global.getInt(
912                         resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
913 
914         final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
915         final boolean supportsPictureInPicture = supportsMultiWindow &&
916                 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
917         final boolean supportsExpandedPictureInPicture =
918                 supportsPictureInPicture && mContext.getPackageManager().hasSystemFeature(
919                         FEATURE_EXPANDED_PICTURE_IN_PICTURE);
920         final boolean supportsSplitScreenMultiWindow =
921                 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
922         final boolean supportsMultiDisplay = mContext.getPackageManager()
923                 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
924         final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
925         final boolean forceResizable = Settings.Global.getInt(
926                 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
927         final boolean devEnableNonResizableMultiWindow = Settings.Global.getInt(
928                 resolver, DEVELOPMENT_ENABLE_NON_RESIZABLE_MULTI_WINDOW, 0) != 0;
929         final int supportsNonResizableMultiWindow = mContext.getResources().getInteger(
930                 com.android.internal.R.integer.config_supportsNonResizableMultiWindow);
931         final int respectsActivityMinWidthHeightMultiWindow = mContext.getResources().getInteger(
932                 com.android.internal.R.integer.config_respectsActivityMinWidthHeightMultiWindow);
933         final float minPercentageMultiWindowSupportHeight = mContext.getResources().getFloat(
934                 com.android.internal.R.dimen.config_minPercentageMultiWindowSupportHeight);
935         final float minPercentageMultiWindowSupportWidth = mContext.getResources().getFloat(
936                 com.android.internal.R.dimen.config_minPercentageMultiWindowSupportWidth);
937 
938         // Transfer any global setting for forcing RTL layout, into a System Property
939         DisplayProperties.debug_force_rtl(forceRtl);
940 
941         final Configuration configuration = new Configuration();
942         Settings.System.getConfiguration(resolver, configuration);
943         if (forceRtl) {
944             // This will take care of setting the correct layout direction flags
945             configuration.setLayoutDirection(configuration.locale);
946         }
947 
948         configuration.setGrammaticalGender(
949                 mGrammaticalManagerInternal.mergedFinalSystemGrammaticalGender());
950 
951         synchronized (mGlobalLock) {
952             mForceResizableActivities = forceResizable;
953             mDevEnableNonResizableMultiWindow = devEnableNonResizableMultiWindow;
954             mSupportsNonResizableMultiWindow = supportsNonResizableMultiWindow;
955             mRespectsActivityMinWidthHeightMultiWindow = respectsActivityMinWidthHeightMultiWindow;
956             mMinPercentageMultiWindowSupportHeight = minPercentageMultiWindowSupportHeight;
957             mMinPercentageMultiWindowSupportWidth = minPercentageMultiWindowSupportWidth;
958             final boolean multiWindowFormEnabled = freeformWindowManagement
959                     || supportsSplitScreenMultiWindow
960                     || supportsPictureInPicture
961                     || supportsMultiDisplay;
962             if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
963                 mSupportsMultiWindow = true;
964                 mSupportsFreeformWindowManagement = freeformWindowManagement;
965                 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
966                 mSupportsPictureInPicture = supportsPictureInPicture;
967                 mSupportsExpandedPictureInPicture = supportsExpandedPictureInPicture;
968                 mSupportsMultiDisplay = supportsMultiDisplay;
969             } else {
970                 mSupportsMultiWindow = false;
971                 mSupportsFreeformWindowManagement = false;
972                 mSupportsSplitScreenMultiWindow = false;
973                 mSupportsPictureInPicture = false;
974                 mSupportsExpandedPictureInPicture = false;
975                 mSupportsMultiDisplay = false;
976             }
977             mWindowManager.mRoot.onSettingsRetrieved();
978             // This happens before any activities are started, so we can change global configuration
979             // in-place.
980             updateConfigurationLocked(configuration, null, true);
981             final Configuration globalConfig = getGlobalConfiguration();
982             ProtoLog.v(WM_DEBUG_CONFIGURATION, "Initial config: %s", globalConfig);
983 
984             // Load resources only after the current configuration has been set.
985             final Resources res = mContext.getResources();
986             mThumbnailWidth = res.getDimensionPixelSize(
987                     com.android.internal.R.dimen.thumbnail_width);
988             mThumbnailHeight = res.getDimensionPixelSize(
989                     com.android.internal.R.dimen.thumbnail_height);
990         }
991     }
992 
getGlobalLock()993     public WindowManagerGlobalLock getGlobalLock() {
994         return mGlobalLock;
995     }
996 
997     /** For test purpose only. */
998     @VisibleForTesting
getAtmInternal()999     public ActivityTaskManagerInternal getAtmInternal() {
1000         return mInternal;
1001     }
1002 
initialize(IntentFirewall intentFirewall, PendingIntentController intentController, Looper looper)1003     public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
1004             Looper looper) {
1005         mH = new H(looper);
1006         mUiHandler = new UiHandler();
1007         mIntentFirewall = intentFirewall;
1008         final File systemDir = SystemServiceManager.ensureSystemDir();
1009         mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
1010         mCompatModePackages = new CompatModePackages(this, systemDir, mH);
1011         mPendingIntentController = intentController;
1012         mTaskSupervisor = createTaskSupervisor();
1013         mActivityClientController = new ActivityClientController(this);
1014 
1015         mTaskChangeNotificationController =
1016                 new TaskChangeNotificationController(mTaskSupervisor, mH);
1017         mLockTaskController = new LockTaskController(mContext, mTaskSupervisor, mH,
1018                 mTaskChangeNotificationController);
1019         mActivityStartController = new ActivityStartController(this);
1020         setRecentTasks(new RecentTasks(this, mTaskSupervisor));
1021         mVrController = new VrController(mGlobalLock);
1022         mKeyguardController = mTaskSupervisor.getKeyguardController();
1023         mPackageConfigPersister = new PackageConfigPersister(mTaskSupervisor.mPersisterQueue, this);
1024     }
1025 
onActivityManagerInternalAdded()1026     public void onActivityManagerInternalAdded() {
1027         synchronized (mGlobalLock) {
1028             mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
1029             mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
1030         }
1031     }
1032 
increaseConfigurationSeqLocked()1033     int increaseConfigurationSeqLocked() {
1034         mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
1035         return mConfigurationSeq;
1036     }
1037 
createTaskSupervisor()1038     protected ActivityTaskSupervisor createTaskSupervisor() {
1039         final ActivityTaskSupervisor supervisor = new ActivityTaskSupervisor(this,
1040                 mH.getLooper());
1041         supervisor.initialize();
1042         return supervisor;
1043     }
1044 
createAppWarnings( Context uiContext, Handler handler, Handler uiHandler, File systemDir)1045     protected AppWarnings createAppWarnings(
1046             Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
1047         return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
1048     }
1049 
setWindowManager(WindowManagerService wm)1050     public void setWindowManager(WindowManagerService wm) {
1051         synchronized (mGlobalLock) {
1052             mWindowManager = wm;
1053             mRootWindowContainer = wm.mRoot;
1054             mWindowOrganizerController.mTransitionController.setWindowManager(wm);
1055             mLifecycleManager.setWindowManager(wm);
1056             mTempConfig.setToDefaults();
1057             mTempConfig.setLocales(LocaleList.getDefault());
1058             mConfigurationSeq = mTempConfig.seq = 1;
1059             mRootWindowContainer.onConfigurationChanged(mTempConfig);
1060             mLockTaskController.setWindowManager(wm);
1061             mTaskSupervisor.setWindowManager(wm);
1062             mRootWindowContainer.setWindowManager(wm);
1063             mBackNavigationController.setWindowManager(wm);
1064         }
1065     }
1066 
setUsageStatsManager(UsageStatsManagerInternal usageStatsManager)1067     public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
1068         synchronized (mGlobalLock) {
1069             mUsageStatsInternal = usageStatsManager;
1070         }
1071     }
1072 
getUiContext()1073     Context getUiContext() {
1074         return mUiContext;
1075     }
1076 
getUserManager()1077     UserManagerService getUserManager() {
1078         if (mUserManager == null) {
1079             IBinder b = ServiceManager.getService(Context.USER_SERVICE);
1080             mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
1081         }
1082         return mUserManager;
1083     }
1084 
getAppOpsManager()1085     AppOpsManager getAppOpsManager() {
1086         if (mAppOpsManager == null) {
1087             mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
1088         }
1089         return mAppOpsManager;
1090     }
1091 
hasUserRestriction(String restriction, int userId)1092     boolean hasUserRestriction(String restriction, int userId) {
1093         return getUserManager().hasUserRestriction(restriction, userId);
1094     }
1095 
hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage)1096     boolean hasSystemAlertWindowPermission(int callingUid, int callingPid,
1097             String callingPackage) {
1098         final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
1099                 callingUid, callingPackage, /* featureId */ null, "");
1100         if (mode == AppOpsManager.MODE_DEFAULT) {
1101             return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
1102                     == PERMISSION_GRANTED;
1103         }
1104         return mode == AppOpsManager.MODE_ALLOWED;
1105     }
1106 
1107     @VisibleForTesting
setRecentTasks(RecentTasks recentTasks)1108     protected void setRecentTasks(RecentTasks recentTasks) {
1109         mRecentTasks = recentTasks;
1110         mTaskSupervisor.setRecentTasks(recentTasks);
1111     }
1112 
getRecentTasks()1113     RecentTasks getRecentTasks() {
1114         return mRecentTasks;
1115     }
1116 
getLifecycleManager()1117     ClientLifecycleManager getLifecycleManager() {
1118         return mLifecycleManager;
1119     }
1120 
getActivityStartController()1121     ActivityStartController getActivityStartController() {
1122         return mActivityStartController;
1123     }
1124 
getTaskChangeNotificationController()1125     TaskChangeNotificationController getTaskChangeNotificationController() {
1126         return mTaskChangeNotificationController;
1127     }
1128 
getLockTaskController()1129     LockTaskController getLockTaskController() {
1130         return mLockTaskController;
1131     }
1132 
getTransitionController()1133     TransitionController getTransitionController() {
1134         return mWindowOrganizerController.getTransitionController();
1135     }
1136 
1137     /**
1138      * Return the global configuration used by the process corresponding to the input pid. This is
1139      * usually the global configuration with some overrides specific to that process.
1140      */
getGlobalConfigurationForCallingPid()1141     private Configuration getGlobalConfigurationForCallingPid() {
1142         final int pid = Binder.getCallingPid();
1143         if (pid == MY_PID || pid < 0) {
1144             return getGlobalConfiguration();
1145         }
1146         final WindowProcessController app = mProcessMap.getProcess(pid);
1147         return app != null ? app.getConfiguration() : getGlobalConfiguration();
1148     }
1149 
1150     /**
1151      * Return the device configuration info used by the process corresponding to the input pid.
1152      * The value is consistent with the global configuration for the process.
1153      */
1154     @Override
getDeviceConfigurationInfo()1155     public ConfigurationInfo getDeviceConfigurationInfo() {
1156         ConfigurationInfo config = new ConfigurationInfo();
1157         synchronized (mGlobalLock) {
1158             final Configuration globalConfig = getGlobalConfigurationForCallingPid();
1159             config.reqTouchScreen = globalConfig.touchscreen;
1160             config.reqKeyboardType = globalConfig.keyboard;
1161             config.reqNavigation = globalConfig.navigation;
1162             if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
1163                     || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
1164                 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
1165             }
1166             if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
1167                     && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
1168                 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
1169             }
1170             config.reqGlEsVersion = GL_ES_VERSION;
1171         }
1172         return config;
1173     }
1174 
1175     @Nullable
getBackgroundActivityStartCallback()1176     public BackgroundActivityStartCallback getBackgroundActivityStartCallback() {
1177         return mBackgroundActivityStartCallback;
1178     }
1179 
getActivityInterceptorCallbacks()1180     SparseArray<ActivityInterceptorCallback> getActivityInterceptorCallbacks() {
1181         return mActivityInterceptorCallbacks;
1182     }
1183 
start()1184     private void start() {
1185         LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
1186     }
1187 
1188     public static final class Lifecycle extends SystemService {
1189         private final ActivityTaskManagerService mService;
1190 
Lifecycle(Context context)1191         public Lifecycle(Context context) {
1192             super(context);
1193             mService = new ActivityTaskManagerService(context);
1194         }
1195 
1196         @Override
onStart()1197         public void onStart() {
1198             publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
1199             mService.start();
1200         }
1201 
1202         @Override
onUserUnlocked(@onNull TargetUser user)1203         public void onUserUnlocked(@NonNull TargetUser user) {
1204             synchronized (mService.getGlobalLock()) {
1205                 mService.mTaskSupervisor.onUserUnlocked(user.getUserIdentifier());
1206             }
1207         }
1208 
1209         @Override
onUserStopped(@onNull TargetUser user)1210         public void onUserStopped(@NonNull TargetUser user) {
1211             synchronized (mService.getGlobalLock()) {
1212                 mService.mTaskSupervisor.mLaunchParamsPersister
1213                         .onCleanupUser(user.getUserIdentifier());
1214             }
1215         }
1216 
getService()1217         public ActivityTaskManagerService getService() {
1218             return mService;
1219         }
1220     }
1221 
1222     @Override
startActivity(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)1223     public final int startActivity(IApplicationThread caller, String callingPackage,
1224             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1225             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1226             Bundle bOptions) {
1227         return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1228                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
1229                 UserHandle.getCallingUserId());
1230     }
1231 
1232     @Override
startActivities(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions, int userId)1233     public final int startActivities(IApplicationThread caller, String callingPackage,
1234             String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1235             Bundle bOptions, int userId) {
1236         assertPackageMatchesCallingUid(callingPackage);
1237         final String reason = "startActivities";
1238         enforceNotIsolatedCaller(reason);
1239         if (intents != null) {
1240             for (Intent intent : intents) {
1241                 mAmInternal.addCreatorToken(intent, callingPackage);
1242             }
1243         }
1244         final int callingPid = Binder.getCallingPid();
1245         final int callingUid = Binder.getCallingUid();
1246         userId = handleIncomingUser(callingPid, callingUid, userId, reason);
1247         // TODO: Switch to user app stacks here.
1248         return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1249                 callingFeatureId, intents, resolvedTypes, resultTo,
1250                 SafeActivityOptions.fromBundle(bOptions, callingPid, callingUid), userId, reason,
1251                 null /* originatingPendingIntent */, false);
1252     }
1253 
1254     @Override
startActivityAsUser(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)1255     public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1256             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1257             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1258             Bundle bOptions, int userId) {
1259         return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1260                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1261                 true /*validateIncomingUser*/);
1262     }
1263 
isSdkSandboxActivityIntent(Context context, Intent intent)1264     static boolean isSdkSandboxActivityIntent(Context context, Intent intent) {
1265         return SdkSandboxActivityAuthority.isSdkSandboxActivityIntent(context, intent);
1266     }
1267 
startActivityAsUser(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser)1268     private int startActivityAsUser(IApplicationThread caller, String callingPackage,
1269             @Nullable String callingFeatureId, Intent intent, String resolvedType,
1270             IBinder resultTo, String resultWho, int requestCode, int startFlags,
1271             ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
1272         mAmInternal.addCreatorToken(intent, callingPackage);
1273         final int callingPid = Binder.getCallingPid();
1274         final int callingUid = Binder.getCallingUid();
1275         final SafeActivityOptions opts = SafeActivityOptions.fromBundle(
1276                 bOptions, callingPid, callingUid);
1277 
1278         assertPackageMatchesCallingUid(callingPackage);
1279         enforceNotIsolatedCaller("startActivityAsUser");
1280 
1281         if (isSdkSandboxActivityIntent(mContext, intent)) {
1282             SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager(
1283                     SdkSandboxManagerLocal.class);
1284             sdkSandboxManagerLocal.enforceAllowedToHostSandboxedActivity(
1285                     intent, callingUid, callingPackage
1286             );
1287         }
1288 
1289         if (Process.isSdkSandboxUid(callingUid)) {
1290             SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager(
1291                     SdkSandboxManagerLocal.class);
1292             if (sdkSandboxManagerLocal == null) {
1293                 throw new IllegalStateException("SdkSandboxManagerLocal not found when starting"
1294                         + " an activity from an SDK sandbox uid.");
1295             }
1296             sdkSandboxManagerLocal.enforceAllowedToStartActivity(intent);
1297         }
1298 
1299         userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
1300                 callingPid, callingUid, "startActivityAsUser");
1301 
1302         // TODO: Switch to user app stacks here.
1303         return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
1304                 .setCaller(caller)
1305                 .setCallingPackage(callingPackage)
1306                 .setCallingFeatureId(callingFeatureId)
1307                 .setResolvedType(resolvedType)
1308                 .setResultTo(resultTo)
1309                 .setResultWho(resultWho)
1310                 .setRequestCode(requestCode)
1311                 .setStartFlags(startFlags)
1312                 .setProfilerInfo(profilerInfo)
1313                 .setActivityOptions(opts)
1314                 .setUserId(userId)
1315                 .execute();
1316     }
1317 
1318     @Override
startActivityIntentSender(IApplicationThread caller, IIntentSender target, IBinder allowlistToken, Intent fillInIntent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions)1319     public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1320             IBinder allowlistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
1321             String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1322         enforceNotIsolatedCaller("startActivityIntentSender");
1323         if (fillInIntent != null) {
1324             // Refuse possible leaked file descriptors
1325             if (fillInIntent.hasFileDescriptors()) {
1326                 throw new IllegalArgumentException("File descriptors passed in Intent");
1327             }
1328             // Remove existing mismatch flag so it can be properly updated later
1329             fillInIntent.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH);
1330         }
1331 
1332         if (!(target instanceof PendingIntentRecord)) {
1333             throw new IllegalArgumentException("Bad PendingIntent object");
1334         }
1335 
1336         PendingIntentRecord pir = (PendingIntentRecord) target;
1337 
1338         if (fillInIntent != null) {
1339             mAmInternal.addCreatorToken(fillInIntent, pir.getPackageName());
1340         }
1341 
1342         synchronized (mGlobalLock) {
1343             // If this is coming from the currently resumed activity, it is
1344             // effectively saying that app switches are allowed at this point.
1345             final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
1346             if (topFocusedRootTask != null && topFocusedRootTask.getTopResumedActivity() != null
1347                     && topFocusedRootTask.getTopResumedActivity().info.applicationInfo.uid
1348                     == Binder.getCallingUid()) {
1349                 mAppSwitchesState = APP_SWITCH_ALLOW;
1350             }
1351         }
1352 
1353         return pir.sendInner(caller, 0, fillInIntent, resolvedType, allowlistToken, null, null,
1354                 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
1355     }
1356 
1357     @Override
startNextMatchingActivity(IBinder callingActivity, Intent intent, Bundle bOptions)1358     public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1359             Bundle bOptions) {
1360         // Refuse possible leaked file descriptors
1361         if (intent != null && intent.hasFileDescriptors()) {
1362             throw new IllegalArgumentException("File descriptors passed in Intent");
1363         }
1364 
1365         final int origCallingPid = Binder.getCallingPid();
1366         final int origCallingUid = Binder.getCallingUid();
1367         SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions, origCallingPid,
1368                 origCallingUid);
1369 
1370         synchronized (mGlobalLock) {
1371             final ActivityRecord r = ActivityRecord.isInRootTaskLocked(callingActivity);
1372             if (r == null) {
1373                 SafeActivityOptions.abort(options);
1374                 return false;
1375             }
1376             if (!r.attachedToProcess()) {
1377                 // The caller is not running...  d'oh!
1378                 SafeActivityOptions.abort(options);
1379                 return false;
1380             }
1381 
1382             mAmInternal.addCreatorToken(intent, r.packageName);
1383 
1384             intent = new Intent(intent);
1385             // Remove existing mismatch flag so it can be properly updated later
1386             intent.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH);
1387             // The caller is not allowed to change the data.
1388             intent.setDataAndType(r.intent.getData(), r.intent.getType());
1389             // And we are resetting to find the next component...
1390             intent.setComponent(null);
1391 
1392             final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1393 
1394             final int userId = UserHandle.getCallingUserId();
1395             ActivityInfo aInfo = null;
1396             try {
1397                 List<ResolveInfo> resolves =
1398                         AppGlobals.getPackageManager().queryIntentActivities(
1399                                 intent, r.resolvedType,
1400                                 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1401                                 userId).getList();
1402 
1403                 // Look for the original activity in the list...
1404                 final int N = resolves != null ? resolves.size() : 0;
1405                 for (int i = 0; i < N; i++) {
1406                     ResolveInfo rInfo = resolves.get(i);
1407                     if (rInfo.activityInfo.packageName.equals(r.packageName)
1408                             && rInfo.activityInfo.name.equals(r.info.name)) {
1409                         // We found the current one...  the next matching is
1410                         // after it.
1411                         i++;
1412                         if (i < N) {
1413                             aInfo = resolves.get(i).activityInfo;
1414                         }
1415                         if (debug) {
1416                             Slog.v(TAG, "Next matching activity: found current " + r.packageName
1417                                     + "/" + r.info.name);
1418                             Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1419                                     ? "null" : aInfo.packageName + "/" + aInfo.name));
1420                         }
1421                         break;
1422                     }
1423                 }
1424             } catch (RemoteException e) {
1425             }
1426 
1427             if (aInfo == null) {
1428                 // Nobody who is next!
1429                 SafeActivityOptions.abort(options);
1430                 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1431                 return false;
1432             }
1433 
1434             intent.setComponent(new ComponentName(
1435                     aInfo.applicationInfo.packageName, aInfo.name));
1436             intent.setFlags(intent.getFlags() & ~(Intent.FLAG_ACTIVITY_FORWARD_RESULT
1437                     | Intent.FLAG_ACTIVITY_CLEAR_TOP
1438                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
1439                     | FLAG_ACTIVITY_NEW_TASK));
1440 
1441             // Okay now we need to start the new activity, replacing the currently running activity.
1442             // This is a little tricky because we want to start the new one as if the current one is
1443             // finished, but not finish the current one first so that there is no flicker.
1444             // And thus...
1445             final boolean wasFinishing = r.finishing;
1446             r.finishing = true;
1447 
1448             // Propagate reply information over to the new activity.
1449             final ActivityRecord resultTo = r.resultTo;
1450             final String resultWho = r.resultWho;
1451             final int requestCode = r.requestCode;
1452             r.resultTo = null;
1453             if (resultTo != null) {
1454                 resultTo.removeResultsLocked(r, resultWho, requestCode);
1455             }
1456 
1457             final long origId = Binder.clearCallingIdentity();
1458             // TODO(b/64750076): Check if calling pid should really be -1.
1459             try {
1460                 if (options == null) {
1461                     options = new SafeActivityOptions(ActivityOptions.makeBasic(),
1462                             Binder.getCallingPid(), Binder.getCallingUid());
1463                 }
1464 
1465                 // Fixes b/230492947 b/337726734
1466                 // Prevents background activity launch through #startNextMatchingActivity
1467                 // launchedFromUid of the calling activity represents the app that launches it.
1468                 // It may have BAL privileges (i.e. the Launcher App). Using its identity to
1469                 // launch to launch next matching activity causes BAL.
1470                 // Change the realCallingUid to the calling activity's uid.
1471                 // In ActivityStarter, when caller is set, the callingUid and callingPid are
1472                 // ignored. So now both callingUid and realCallingUid is set to the caller app.
1473                 final int res = getActivityStartController()
1474                         .obtainStarter(intent, "startNextMatchingActivity")
1475                         .setCaller(r.app.getThread())
1476                         .setResolvedType(r.resolvedType)
1477                         .setActivityInfo(aInfo)
1478                         .setResultTo(resultTo != null ? resultTo.token : null)
1479                         .setResultWho(resultWho)
1480                         .setRequestCode(requestCode)
1481                         .setCallingPid(-1)
1482                         .setCallingUid(r.launchedFromUid)
1483                         .setCallingPackage(r.launchedFromPackage)
1484                         .setCallingFeatureId(r.launchedFromFeatureId)
1485                         .setRealCallingPid(origCallingPid)
1486                         .setRealCallingUid(origCallingUid)
1487                         .setActivityOptions(options)
1488                         .setUserId(userId)
1489                         .execute();
1490                 r.finishing = wasFinishing;
1491                 return res == ActivityManager.START_SUCCESS;
1492             } finally {
1493                 Binder.restoreCallingIdentity(origId);
1494             }
1495         }
1496     }
1497 
isDreaming()1498     boolean isDreaming() {
1499         return mActiveDreamComponent != null;
1500     }
1501 
canLaunchDreamActivity(String packageName)1502     boolean canLaunchDreamActivity(String packageName) {
1503         if (mActiveDreamComponent == null || packageName == null) {
1504             ProtoLog.e(WM_DEBUG_DREAM, "Cannot launch dream activity due to invalid state. "
1505                     + "dream component: %s packageName: %s", mActiveDreamComponent, packageName);
1506             return false;
1507         }
1508         if (packageName.equals(mActiveDreamComponent.getPackageName())) {
1509             return true;
1510         }
1511         ProtoLog.e(WM_DEBUG_DREAM,
1512                 "Dream packageName does not match active dream. Package %s does not match %s",
1513                 packageName, String.valueOf(mActiveDreamComponent));
1514         return false;
1515     }
1516 
startDreamActivityInternal(@onNull Intent intent, int callingUid, int callingPid)1517     private IAppTask startDreamActivityInternal(@NonNull Intent intent, int callingUid,
1518             int callingPid) {
1519         final ActivityInfo a = new ActivityInfo();
1520         a.theme = com.android.internal.R.style.Theme_Dream;
1521         a.exported = true;
1522         a.name = DreamActivity.class.getName();
1523         a.enabled = true;
1524         a.persistableMode = ActivityInfo.PERSIST_NEVER;
1525         a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1526         a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1527         a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | ActivityInfo.FLAG_SHOW_WHEN_LOCKED;
1528         a.configChanges = 0xffffffff;
1529 
1530         if (homePanelDream()) {
1531             a.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
1532             a.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_ALWAYS;
1533         } else {
1534             a.resizeMode = RESIZE_MODE_UNRESIZEABLE;
1535             a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1536         }
1537 
1538         final ActivityOptions options = ActivityOptions.makeBasic();
1539         options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1540 
1541         synchronized (mGlobalLock) {
1542             final WindowProcessController process = mProcessMap.getProcess(callingPid);
1543 
1544             a.packageName = process.mInfo.packageName;
1545             a.applicationInfo = process.mInfo;
1546             a.processName = process.mName;
1547             a.uiOptions = process.mInfo.uiOptions;
1548             a.taskAffinity = "android:" + a.packageName + "/dream";
1549 
1550 
1551             final ActivityRecord[] outActivity = new ActivityRecord[1];
1552             final int res = getActivityStartController()
1553                     .obtainStarter(intent, "dream")
1554                     .setCallingUid(callingUid)
1555                     .setCallingPid(callingPid)
1556                     .setCallingPackage(intent.getPackage())
1557                     .setActivityInfo(a)
1558                     .setActivityOptions(createSafeActivityOptionsWithBalAllowed(options))
1559                     .setOutActivity(outActivity)
1560                     // To start the dream from background, we need to start it from a persistent
1561                     // system process. Here we set the real calling uid to the system server uid
1562                     .setRealCallingUid(Binder.getCallingUid())
1563                     .setAllowBalExemptionForSystemProcess(true)
1564                     .execute();
1565 
1566             final ActivityRecord started = outActivity[0];
1567             if (started == null || !ActivityManager.isStartResultSuccessful(res)) {
1568                 // start the dream activity failed.
1569                 return null;
1570             }
1571             return new AppTaskImpl(this, started.getTask().mTaskId, callingUid);
1572         }
1573     }
1574 
1575     @Override
startActivityAndWait(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)1576     public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1577             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1578             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1579             Bundle bOptions, int userId) {
1580         assertPackageMatchesCallingUid(callingPackage);
1581         final WaitResult res = new WaitResult();
1582         enforceNotIsolatedCaller("startActivityAndWait");
1583         final int callingPid = Binder.getCallingPid();
1584         final int callingUid = Binder.getCallingUid();
1585         userId = handleIncomingUser(callingPid, callingUid, userId, "startActivityAndWait");
1586         // TODO: Switch to user app stacks here.
1587         getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1588                 .setCaller(caller)
1589                 .setCallingPackage(callingPackage)
1590                 .setCallingFeatureId(callingFeatureId)
1591                 .setResolvedType(resolvedType)
1592                 .setResultTo(resultTo)
1593                 .setResultWho(resultWho)
1594                 .setRequestCode(requestCode)
1595                 .setStartFlags(startFlags)
1596                 .setActivityOptions(bOptions, callingPid, callingUid)
1597                 .setUserId(userId)
1598                 .setProfilerInfo(profilerInfo)
1599                 .setWaitResult(res)
1600                 .execute();
1601         return res;
1602     }
1603 
1604     @Override
startActivityWithConfig(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, Configuration config, Bundle bOptions, int userId)1605     public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1606             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1607             String resultWho, int requestCode, int startFlags, Configuration config,
1608             Bundle bOptions, int userId) {
1609         assertPackageMatchesCallingUid(callingPackage);
1610         enforceNotIsolatedCaller("startActivityWithConfig");
1611         final int callingPid = Binder.getCallingPid();
1612         final int callingUid = Binder.getCallingUid();
1613         userId = handleIncomingUser(callingPid, callingUid, userId, "startActivityWithConfig");
1614         // TODO: Switch to user app stacks here.
1615         return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1616                 .setCaller(caller)
1617                 .setCallingPackage(callingPackage)
1618                 .setCallingFeatureId(callingFeatureId)
1619                 .setResolvedType(resolvedType)
1620                 .setResultTo(resultTo)
1621                 .setResultWho(resultWho)
1622                 .setRequestCode(requestCode)
1623                 .setStartFlags(startFlags)
1624                 .setGlobalConfiguration(config)
1625                 .setActivityOptions(bOptions, callingPid, callingUid)
1626                 .setUserId(userId)
1627                 .execute();
1628     }
1629 
1630     @Override
startActivityAsCaller(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity, int userId)1631     public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1632             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1633             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions,
1634             boolean ignoreTargetSecurity, int userId) {
1635         // This is very dangerous -- it allows you to perform a start activity (including
1636         // permission grants) as any app that may launch one of your own activities.  So we only
1637         // allow this in two cases:
1638         // 1)  The calling process holds the signature permission START_ACTIVITY_AS_CALLER
1639         //
1640         // 2) The calling process is an activity belonging to the package "android" which is
1641         //    running as UID_SYSTEM or as the target UID (the activity which started the activity
1642         //    calling this method).
1643 
1644         final ActivityRecord sourceRecord;
1645         final int targetUid;
1646         final String targetPackage;
1647         final String targetFeatureId;
1648         final boolean isResolver;
1649         synchronized (mGlobalLock) {
1650             if (resultTo == null) {
1651                 throw new SecurityException("Must be called from an activity");
1652             }
1653 
1654             sourceRecord = ActivityRecord.isInAnyTask(resultTo);
1655             if (sourceRecord == null) {
1656                 throw new SecurityException("Called with bad activity token: " + resultTo);
1657             }
1658             if (sourceRecord.app == null) {
1659                 throw new SecurityException("Called without a process attached to activity");
1660             }
1661 
1662             if (checkCallingPermission(Manifest.permission.START_ACTIVITY_AS_CALLER)
1663                     != PERMISSION_GRANTED) {
1664                 // Whether called directly or from a delegate, the source activity must be from the
1665                 // android package.
1666                 if (!sourceRecord.info.packageName.equals("android")) {
1667                     throw new SecurityException("Must be called from an activity that is "
1668                             + "declared in the android package");
1669                 }
1670                 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
1671                     // This is still okay, as long as this activity is running under the
1672                     // uid of the original calling activity.
1673                     if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
1674                         throw new SecurityException(
1675                                 "Calling activity in uid " + sourceRecord.app.mUid
1676                                         + " must be system uid or original calling uid "
1677                                         + sourceRecord.launchedFromUid);
1678                     }
1679                 }
1680             }
1681             if (ignoreTargetSecurity) {
1682                 if (intent.getComponent() == null) {
1683                     throw new SecurityException(
1684                             "Component must be specified with ignoreTargetSecurity");
1685                 }
1686                 if (intent.getSelector() != null) {
1687                     throw new SecurityException(
1688                             "Selector not allowed with ignoreTargetSecurity");
1689                 }
1690             }
1691             targetUid = sourceRecord.launchedFromUid;
1692             targetPackage = sourceRecord.launchedFromPackage;
1693             targetFeatureId = sourceRecord.launchedFromFeatureId;
1694             isResolver = sourceRecord.isResolverOrChildActivity();
1695         }
1696 
1697         if (userId == UserHandle.USER_NULL) {
1698             userId = UserHandle.getUserId(sourceRecord.app.mUid);
1699         }
1700 
1701         // TODO: Switch to user app stacks here.
1702         try {
1703             return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
1704                     .setCallingUid(targetUid)
1705                     .setCallingPackage(targetPackage)
1706                     .setCallingFeatureId(targetFeatureId)
1707                     .setResolvedType(resolvedType)
1708                     .setResultTo(resultTo)
1709                     .setResultWho(resultWho)
1710                     .setRequestCode(requestCode)
1711                     .setStartFlags(startFlags)
1712                     .setActivityOptions(createSafeActivityOptionsWithBalAllowed(bOptions))
1713                     .setUserId(userId)
1714                     .setIgnoreTargetSecurity(ignoreTargetSecurity)
1715                     .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1716                     // The target may well be in the background, which would normally prevent it
1717                     // from starting an activity. Here we definitely want the start to succeed.
1718                     .setAllowBalExemptionForSystemProcess(true)
1719                     .execute();
1720         } catch (SecurityException e) {
1721             // XXX need to figure out how to propagate to original app.
1722             // A SecurityException here is generally actually a fault of the original
1723             // calling activity (such as a fairly granting permissions), so propagate it
1724             // back to them.
1725             /*
1726             StringBuilder msg = new StringBuilder();
1727             msg.append("While launching");
1728             msg.append(intent.toString());
1729             msg.append(": ");
1730             msg.append(e.getMessage());
1731             */
1732             throw e;
1733         }
1734     }
1735 
handleIncomingUser(int callingPid, int callingUid, int userId, String name)1736     int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1737         return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1738                 ALLOW_NON_FULL, name, null /* callerPackage */);
1739     }
1740 
1741     @Override
startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid, int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session, IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)1742     public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1743             int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
1744             IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1745             Bundle bOptions, int userId) {
1746         assertPackageMatchesCallingUid(callingPackage);
1747         mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
1748         if (session == null || interactor == null) {
1749             throw new NullPointerException("null session or interactor");
1750         }
1751         userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
1752         // TODO: Switch to user app stacks here.
1753         return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
1754                 .setCallingUid(callingUid)
1755                 .setCallingPackage(callingPackage)
1756                 .setCallingFeatureId(callingFeatureId)
1757                 .setResolvedType(resolvedType)
1758                 .setVoiceSession(session)
1759                 .setVoiceInteractor(interactor)
1760                 .setStartFlags(startFlags)
1761                 .setProfilerInfo(profilerInfo)
1762                 .setActivityOptions(createSafeActivityOptionsWithBalAllowed(bOptions))
1763                 .setUserId(userId)
1764                 .setAllowBalExemptionForSystemProcess(true)
1765                 .execute();
1766     }
1767 
1768     @Override
getVoiceInteractorPackageName(IBinder callingVoiceInteractor)1769     public String getVoiceInteractorPackageName(IBinder callingVoiceInteractor) {
1770         return LocalServices.getService(VoiceInteractionManagerInternal.class)
1771                 .getVoiceInteractorPackageName(callingVoiceInteractor);
1772     }
1773 
1774     @Override
startAssistantActivity(String callingPackage, @NonNull String callingFeatureId, int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions, int userId)1775     public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1776             int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1777             int userId) {
1778         assertPackageMatchesCallingUid(callingPackage);
1779         mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1780         userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
1781 
1782         final long origId = Binder.clearCallingIdentity();
1783         try {
1784             return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
1785                     .setCallingUid(callingUid)
1786                     .setCallingPackage(callingPackage)
1787                     .setCallingFeatureId(callingFeatureId)
1788                     .setResolvedType(resolvedType)
1789                     .setActivityOptions(createSafeActivityOptionsWithBalAllowed(bOptions))
1790                     .setUserId(userId)
1791                     .setAllowBalExemptionForSystemProcess(true)
1792                     .execute();
1793         } finally {
1794             Binder.restoreCallingIdentity(origId);
1795         }
1796     }
1797 
1798     /**
1799      * Preload the recents activity.
1800      *
1801      * @param intent The intent to preload the recents activity.
1802      */
1803     @Override
preloadRecentsActivity(Intent intent)1804     public void preloadRecentsActivity(Intent intent) {
1805         enforceTaskPermission("preloadRecentsActivity()");
1806         final long origId = Binder.clearCallingIdentity();
1807         try {
1808             synchronized (mGlobalLock) {
1809                 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1810                 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
1811                 final int recentsUid = mRecentTasks.getRecentsComponentUid();
1812                 final RecentsAnimation anim = new RecentsAnimation(this, mTaskSupervisor,
1813                         getActivityStartController(), intent, recentsComponent,
1814                         recentsFeatureId, recentsUid);
1815                 anim.preloadRecentsActivity();
1816             }
1817         } finally {
1818             Binder.restoreCallingIdentity(origId);
1819         }
1820     }
1821 
1822     @Override
startActivityFromRecents(int taskId, Bundle bOptions)1823     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
1824         mAmInternal.enforceCallingPermission(START_TASKS_FROM_RECENTS,
1825                 "startActivityFromRecents()");
1826 
1827         final int callingPid = Binder.getCallingPid();
1828         final int callingUid = Binder.getCallingUid();
1829         final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(
1830                 bOptions, callingPid, callingUid);
1831         final long origId = Binder.clearCallingIdentity();
1832         try {
1833             return mTaskSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1834                     safeOptions);
1835         } finally {
1836             Binder.restoreCallingIdentity(origId);
1837         }
1838     }
1839 
1840     @Override
startActivityFromGameSession(IApplicationThread caller, String callingPackage, String callingFeatureId, int callingPid, int callingUid, Intent intent, int taskId, int userId)1841     public int startActivityFromGameSession(IApplicationThread caller, String callingPackage,
1842             String callingFeatureId, int callingPid, int callingUid, Intent intent, int taskId,
1843             int userId) {
1844         if (checkCallingPermission(MANAGE_GAME_ACTIVITY) != PERMISSION_GRANTED) {
1845             final String msg = "Permission Denial: startActivityFromGameSession() from pid="
1846                     + Binder.getCallingPid()
1847                     + ", uid=" + Binder.getCallingUid()
1848                     + " requires " + MANAGE_GAME_ACTIVITY;
1849             Slog.w(TAG, msg);
1850             throw new SecurityException(msg);
1851         }
1852         assertPackageMatchesCallingUid(callingPackage);
1853 
1854         mAmInternal.addCreatorToken(intent, callingPackage);
1855 
1856         final ActivityOptions activityOptions = ActivityOptions.makeBasic();
1857         activityOptions.setLaunchTaskId(taskId);
1858         // Pass in the system UID to allow setting launch taskId with MANAGE_GAME_ACTIVITY.
1859         final SafeActivityOptions safeOptions = new SafeActivityOptions(
1860                 activityOptions, Process.myPid(), Process.SYSTEM_UID);
1861 
1862         userId = handleIncomingUser(callingPid, callingUid, userId, "startActivityFromGameSession");
1863 
1864         final long origId = Binder.clearCallingIdentity();
1865         try {
1866             return getActivityStartController()
1867                     .obtainStarter(intent, "startActivityFromGameSession")
1868                     .setCaller(caller)
1869                     .setCallingUid(callingUid)
1870                     .setCallingPid(callingPid)
1871                     .setCallingPackage(intent.getPackage())
1872                     .setCallingFeatureId(callingFeatureId)
1873                     .setUserId(userId)
1874                     .setActivityOptions(safeOptions)
1875                     .setRealCallingUid(Binder.getCallingUid())
1876                     .execute();
1877         } finally {
1878             Binder.restoreCallingIdentity(origId);
1879         }
1880     }
1881 
1882     @Override
startBackNavigation( RemoteCallback navigationObserver, BackAnimationAdapter adapter)1883     public BackNavigationInfo startBackNavigation(
1884             RemoteCallback navigationObserver, BackAnimationAdapter adapter) {
1885         mAmInternal.enforceCallingPermission(START_TASKS_FROM_RECENTS,
1886                 "startBackNavigation()");
1887         final long origId = Binder.clearCallingIdentity();
1888         try {
1889             return mBackNavigationController.startBackNavigation(navigationObserver, adapter);
1890         } finally {
1891             Binder.restoreCallingIdentity(origId);
1892         }
1893     }
1894 
1895     @Override
registerBackGestureDelegate(RemoteCallback requestObserver)1896     public void registerBackGestureDelegate(RemoteCallback requestObserver) {
1897         mAmInternal.enforceCallingPermission(START_TASKS_FROM_RECENTS,
1898                 "registerBackGestureDelegate()");
1899         final long origId = Binder.clearCallingIdentity();
1900         try {
1901             mBackNavigationController.registerBackGestureDelegate(requestObserver);
1902         } finally {
1903             Binder.restoreCallingIdentity(origId);
1904         }
1905     }
1906 
1907     /**
1908      * Public API to check if the client is allowed to start an activity on specified display.
1909      *
1910      * If the target display is private or virtual, some restrictions will apply.
1911      *
1912      * @param displayId    Target display id.
1913      * @param intent       Intent used to launch the activity.
1914      * @param resolvedType The MIME type of the intent.
1915      * @param userId       The id of the user for whom the call is made.
1916      * @return {@code true} if a call to start an activity on the target display should succeed and
1917      * no {@link SecurityException} will be thrown, {@code false} otherwise.
1918      */
1919     @Override
isActivityStartAllowedOnDisplay(int displayId, Intent intent, String resolvedType, int userId)1920     public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1921             String resolvedType, int userId) {
1922         final int callingUid = Binder.getCallingUid();
1923         final int callingPid = Binder.getCallingPid();
1924         final long origId = Binder.clearCallingIdentity();
1925 
1926         try {
1927             // Collect information about the target of the Intent.
1928             final ActivityInfo aInfo = resolveActivityInfoForIntent(intent, resolvedType, userId,
1929                     callingUid, callingPid);
1930 
1931             synchronized (mGlobalLock) {
1932                 return mTaskSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1933                         aInfo);
1934             }
1935         } finally {
1936             Binder.restoreCallingIdentity(origId);
1937         }
1938     }
1939 
resolveActivityInfoForIntent(Intent intent, String resolvedType, int userId, int callingUid, int callingPid)1940     ActivityInfo resolveActivityInfoForIntent(Intent intent, String resolvedType,
1941             int userId, int callingUid, int callingPid) {
1942         ActivityInfo aInfo = mTaskSupervisor.resolveActivity(intent, resolvedType,
1943                 0 /* startFlags */, null /* profilerInfo */, userId,
1944                 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1945                         UserHandle.USER_NULL), callingPid);
1946         return mAmInternal.getActivityInfoForUser(aInfo, userId);
1947     }
1948 
1949     @Override
getActivityClientController()1950     public IActivityClientController getActivityClientController() {
1951         return mActivityClientController;
1952     }
1953 
applyUpdateLockStateLocked(ActivityRecord r)1954     void applyUpdateLockStateLocked(ActivityRecord r) {
1955         // Modifications to the UpdateLock state are done on our handler, outside
1956         // the activity manager's locks.  The new state is determined based on the
1957         // state *now* of the relevant activity record.  The object is passed to
1958         // the handler solely for logging detail, not to be consulted/modified.
1959         final boolean nextState = r != null && r.immersive;
1960         mH.post(() -> {
1961             if (mUpdateLock.isHeld() != nextState) {
1962                 ProtoLog.d(WM_DEBUG_IMMERSIVE, "Applying new update lock state '%s' for %s",
1963                         nextState, r);
1964                 if (nextState) {
1965                     mUpdateLock.acquire();
1966                 } else {
1967                     mUpdateLock.release();
1968                 }
1969             }
1970         });
1971     }
1972 
1973     @Override
isTopActivityImmersive()1974     public boolean isTopActivityImmersive() {
1975         enforceNotIsolatedCaller("isTopActivityImmersive");
1976         synchronized (mGlobalLock) {
1977             final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
1978             if (topFocusedRootTask == null) {
1979                 return false;
1980             }
1981 
1982             final ActivityRecord r = topFocusedRootTask.topRunningActivity();
1983             return r != null && r.immersive;
1984         }
1985     }
1986 
1987     @Override
getFrontActivityScreenCompatMode()1988     public int getFrontActivityScreenCompatMode() {
1989         enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
1990         synchronized (mGlobalLock) {
1991             final Task rootTask = getTopDisplayFocusedRootTask();
1992             final ActivityRecord r = rootTask != null ? rootTask.topRunningActivity() : null;
1993             if (r == null) {
1994                 return ActivityManager.COMPAT_MODE_UNKNOWN;
1995             }
1996             return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
1997         }
1998     }
1999 
2000     @Override
setFrontActivityScreenCompatMode(int mode)2001     public void setFrontActivityScreenCompatMode(int mode) {
2002         mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2003                 "setFrontActivityScreenCompatMode");
2004         ApplicationInfo ai;
2005         synchronized (mGlobalLock) {
2006             final Task rootTask = getTopDisplayFocusedRootTask();
2007             final ActivityRecord r = rootTask != null ? rootTask.topRunningActivity() : null;
2008             if (r == null) {
2009                 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2010                 return;
2011             }
2012             ai = r.info.applicationInfo;
2013             mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
2014         }
2015     }
2016 
2017 
2018     @Override
getFocusedRootTaskInfo()2019     public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException {
2020         enforceTaskPermission("getFocusedRootTaskInfo()");
2021         final long ident = Binder.clearCallingIdentity();
2022         try {
2023             synchronized (mGlobalLock) {
2024                 Task focusedRootTask = getTopDisplayFocusedRootTask();
2025                 if (focusedRootTask != null) {
2026                     return mRootWindowContainer.getRootTaskInfo(focusedRootTask.mTaskId);
2027                 }
2028                 return null;
2029             }
2030         } finally {
2031             Binder.restoreCallingIdentity(ident);
2032         }
2033     }
2034 
2035     @Override
setFocusedRootTask(int taskId)2036     public void setFocusedRootTask(int taskId) {
2037         enforceTaskPermission("setFocusedRootTask()");
2038         ProtoLog.d(WM_DEBUG_FOCUS, "setFocusedRootTask: taskId=%d", taskId);
2039         final long callingId = Binder.clearCallingIdentity();
2040         try {
2041             synchronized (mGlobalLock) {
2042                 final Task task = mRootWindowContainer.getRootTask(taskId);
2043                 if (task == null) {
2044                     Slog.w(TAG, "setFocusedRootTask: No task with id=" + taskId);
2045                     return;
2046                 }
2047                 final ActivityRecord r = task.topRunningActivity();
2048                 if (r != null && r.moveFocusableActivityToTop("setFocusedRootTask")) {
2049                     mRootWindowContainer.resumeFocusedTasksTopActivities();
2050                 }
2051             }
2052         } finally {
2053             Binder.restoreCallingIdentity(callingId);
2054         }
2055     }
2056 
2057     @Override
setFocusedTask(int taskId)2058     public void setFocusedTask(int taskId) {
2059         enforceTaskPermission("setFocusedTask()");
2060         final long callingId = Binder.clearCallingIdentity();
2061         try {
2062             synchronized (mGlobalLock) {
2063                 setFocusedTask(taskId, null /* touchedActivity */);
2064             }
2065         } finally {
2066             Binder.restoreCallingIdentity(callingId);
2067         }
2068     }
2069 
2070     @Override
focusTopTask(int displayId)2071     public void focusTopTask(int displayId) {
2072         enforceTaskPermission("focusTopTask()");
2073         final long callingId = Binder.clearCallingIdentity();
2074         try {
2075             synchronized (mGlobalLock) {
2076                 final DisplayContent dc = mRootWindowContainer.getDisplayContent(displayId);
2077                 if (dc == null) return;
2078                 final Task task = dc.getTask((t) -> t.isLeafTask() && t.isTopActivityFocusable(),
2079                         true /*  traverseTopToBottom */);
2080                 if (task == null) return;
2081                 setFocusedTask(task.mTaskId, null /* touchedActivity */);
2082             }
2083         } finally {
2084             Binder.restoreCallingIdentity(callingId);
2085         }
2086     }
2087 
setFocusedTask(int taskId, ActivityRecord touchedActivity)2088     void setFocusedTask(int taskId, ActivityRecord touchedActivity) {
2089         ProtoLog.d(WM_DEBUG_FOCUS, "setFocusedTask: taskId=%d touchedActivity=%s", taskId,
2090                 touchedActivity);
2091         final Task task = mRootWindowContainer.anyTaskForId(taskId, MATCH_ATTACHED_TASK_ONLY);
2092         if (task == null) {
2093             return;
2094         }
2095         final ActivityRecord r = task.topRunningActivityLocked();
2096         if (r == null) {
2097             return;
2098         }
2099 
2100         if ((touchedActivity == null || r == touchedActivity) && r.isState(RESUMED)
2101                 && r == mRootWindowContainer.getTopResumedActivity()) {
2102             setLastResumedActivityUncheckLocked(r, "setFocusedTask-alreadyTop");
2103             return;
2104         }
2105         final Transition transition = (getTransitionController().isCollecting()
2106                 || !getTransitionController().isShellTransitionsEnabled()) ? null
2107                 : getTransitionController().createTransition(TRANSIT_TO_FRONT);
2108         if (transition != null) {
2109             // Set ready before doing anything. If order does change, then that will set it unready
2110             // so that we wait for the new lifecycles to complete.
2111             transition.setReady(task, true /* ready */);
2112         }
2113         final boolean movedToTop = r.moveFocusableActivityToTop("setFocusedTask");
2114         if (movedToTop) {
2115             if (transition != null) {
2116                 getTransitionController().requestStartTransition(
2117                         transition, null /* startTask */, null /* remote */, null /* display */);
2118             }
2119             mRootWindowContainer.resumeFocusedTasksTopActivities();
2120         } else if (touchedActivity != null && touchedActivity.isFocusable()) {
2121             final TaskFragment parent = touchedActivity.getTaskFragment();
2122             if (parent != null && parent.isEmbedded()) {
2123                 // Set the focused app directly if the focused window is currently embedded
2124                 final DisplayContent displayContent = touchedActivity.getDisplayContent();
2125                 displayContent.setFocusedApp(touchedActivity);
2126                 mWindowManager.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL,
2127                         true /* updateInputWindows */);
2128             }
2129         }
2130         if (transition != null && !movedToTop) {
2131             // No order changes and focus-changes, alone, aren't captured in transitions.
2132             transition.abort();
2133         }
2134     }
2135 
2136     @Override
setTaskIsPerceptible(int taskId, boolean isPerceptible)2137     public boolean setTaskIsPerceptible(int taskId, boolean isPerceptible) {
2138         enforceTaskPermission("setTaskIsPerceptible()");
2139         final long ident = Binder.clearCallingIdentity();
2140         try {
2141             synchronized (mGlobalLock) {
2142                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2143                         MATCH_ATTACHED_TASK_ONLY);
2144                 if (task == null) {
2145                     Slog.w(TAG, "setTaskIsPerceptible: No task to set with id=" + taskId);
2146                     return false;
2147                 }
2148                 task.mIsPerceptible = isPerceptible;
2149             }
2150             return true;
2151         } finally {
2152             Binder.restoreCallingIdentity(ident);
2153         }
2154     }
2155 
2156     @Override
removeTask(int taskId)2157     public boolean removeTask(int taskId) {
2158         mAmInternal.enforceCallingPermission(REMOVE_TASKS, "removeTask()");
2159         synchronized (mGlobalLock) {
2160             final long ident = Binder.clearCallingIdentity();
2161             try {
2162                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2163                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
2164                 if (task == null) {
2165                     Slog.w(TAG, "removeTask: No task remove with id=" + taskId);
2166                     return false;
2167                 }
2168                 removeTask(task);
2169                 return true;
2170             } finally {
2171                 Binder.restoreCallingIdentity(ident);
2172             }
2173         }
2174     }
2175 
removeTask(@onNull Task task)2176     void removeTask(@NonNull Task task) {
2177         if (task.isLeafTask()) {
2178             mTaskSupervisor.removeTask(task, true, REMOVE_FROM_RECENTS, "remove-task");
2179         } else {
2180             mTaskSupervisor.removeRootTask(task);
2181         }
2182     }
2183 
2184     /**
2185      * @return ehether the application could be universal resizeable on a large screen,
2186      * ignoring any overrides
2187      */
2188     @Override
canBeUniversalResizeable(@onNull ApplicationInfo appInfo)2189     public boolean canBeUniversalResizeable(@NonNull ApplicationInfo appInfo) {
2190         return ActivityRecord.canBeUniversalResizeable(appInfo, mWindowManager,
2191                 /* isLargeScreen */ true, /* forActivity */ false);
2192     }
2193 
2194     @Override
removeAllVisibleRecentTasks()2195     public void removeAllVisibleRecentTasks() {
2196         mAmInternal.enforceCallingPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2197         synchronized (mGlobalLock) {
2198             final long ident = Binder.clearCallingIdentity();
2199             try {
2200                 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
2201             } finally {
2202                 Binder.restoreCallingIdentity(ident);
2203             }
2204         }
2205     }
2206 
2207     @Override
getTaskBounds(int taskId)2208     public Rect getTaskBounds(int taskId) {
2209         enforceTaskPermission("getTaskBounds()");
2210         final long ident = Binder.clearCallingIdentity();
2211         Rect rect = new Rect();
2212         try {
2213             synchronized (mGlobalLock) {
2214                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2215                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
2216                 if (task == null) {
2217                     Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2218                     return rect;
2219                 }
2220                 if (task.getParent() != null) {
2221                     rect.set(task.getBounds());
2222                 } else if (task.mLastNonFullscreenBounds != null) {
2223                     rect.set(task.mLastNonFullscreenBounds);
2224                 }
2225             }
2226         } finally {
2227             Binder.restoreCallingIdentity(ident);
2228         }
2229         return rect;
2230     }
2231 
2232     /**
2233      * Sets the locusId for a particular activity.
2234      *
2235      * @param locusId the locusId to set.
2236      * @param appToken the ActivityRecord's appToken.
2237      */
setLocusId(LocusId locusId, IBinder appToken)2238     public void setLocusId(LocusId locusId, IBinder appToken) {
2239         synchronized (mGlobalLock) {
2240             final ActivityRecord r = ActivityRecord.isInRootTaskLocked(appToken);
2241             if (r != null) {
2242                 r.setLocusId(locusId);
2243             }
2244         }
2245     }
2246 
collectGrants(Intent intent, ActivityRecord target)2247     NeededUriGrants collectGrants(Intent intent, ActivityRecord target) {
2248         if (target != null) {
2249             return mUgmInternal.checkGrantUriPermissionFromIntent(intent,
2250                     Binder.getCallingUid(), target.packageName, target.mUserId);
2251         } else {
2252             return null;
2253         }
2254     }
2255 
2256     @Override
unhandledBack()2257     public void unhandledBack() {
2258         mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
2259                 "unhandledBack()");
2260 
2261         synchronized (mGlobalLock) {
2262             final long origId = Binder.clearCallingIdentity();
2263             try {
2264                 final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
2265                 if (topFocusedRootTask != null) {
2266                     topFocusedRootTask.unhandledBackLocked();
2267                 }
2268             } finally {
2269                 Binder.restoreCallingIdentity(origId);
2270             }
2271         }
2272     }
2273 
2274     /**
2275      * TODO: Add mController hook
2276      */
2277     @Override
moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)2278     public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2279             int flags, Bundle bOptions) {
2280         mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
2281                 "moveTaskToFront()");
2282 
2283         ProtoLog.d(WM_DEBUG_TASKS, "moveTaskToFront: moving taskId=%d", taskId);
2284         synchronized (mGlobalLock) {
2285             final int callingPid = Binder.getCallingPid();
2286             final int callingUid = Binder.getCallingUid();
2287             moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2288                     SafeActivityOptions.fromBundle(bOptions, callingPid, callingUid));
2289         }
2290     }
2291 
moveTaskToFrontLocked(@ullable IApplicationThread appThread, @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options)2292     void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2293             @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options) {
2294         final int callingPid = Binder.getCallingPid();
2295         final int callingUid = Binder.getCallingUid();
2296         assertPackageMatchesCallingUid(callingPackage);
2297 
2298         final long origId = Binder.clearCallingIdentity();
2299         WindowProcessController callerApp = null;
2300         if (appThread != null) {
2301             callerApp = getProcessController(appThread);
2302         }
2303         final BackgroundActivityStartController balController =
2304                 mTaskSupervisor.getBackgroundActivityLaunchController();
2305         final BalVerdict balVerdict = balController.checkBackgroundActivityStart(
2306                 callingUid,
2307                 callingPid,
2308                 callingPackage,
2309                 -1,
2310                 -1,
2311                 callerApp,
2312                 null,
2313                 false,
2314                 null,
2315                 null,
2316                 null);
2317         if (balVerdict.blocks() && !isBackgroundActivityStartsEnabled()) {
2318             Slog.w(TAG, "moveTaskToFront blocked: " + balVerdict);
2319             return;
2320         }
2321         if (DEBUG_ACTIVITY_STARTS) {
2322             Slog.d(TAG, "moveTaskToFront allowed: " + balVerdict);
2323         }
2324         try {
2325             final Task task = mRootWindowContainer.anyTaskForId(taskId);
2326             if (task == null) {
2327                 ProtoLog.d(WM_DEBUG_TASKS, "Could not find task for id: %d", taskId);
2328                 SafeActivityOptions.abort(options);
2329                 return;
2330             }
2331             if (getLockTaskController().isLockTaskModeViolation(task)) {
2332                 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
2333                 SafeActivityOptions.abort(options);
2334                 return;
2335             }
2336             ActivityOptions realOptions = options != null
2337                     ? options.getOptions(mTaskSupervisor)
2338                     : null;
2339             mTaskSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2340                     false /* forceNonResizable */);
2341         } finally {
2342             Binder.restoreCallingIdentity(origId);
2343         }
2344     }
2345 
2346     /**
2347      * Return true if callingUid is system, or packageName belongs to that callingUid.
2348      */
isSameApp(int callingUid, @Nullable String packageName)2349     private boolean isSameApp(int callingUid, @Nullable String packageName) {
2350         if (callingUid != 0 && callingUid != SYSTEM_UID) {
2351             return mPmInternal.isSameApp(packageName, callingUid, UserHandle.getUserId(callingUid));
2352         }
2353         return true;
2354     }
2355 
2356     /**
2357      * Checks that the provided package name matches the current calling UID, throws a security
2358      * exception if it doesn't.
2359      */
assertPackageMatchesCallingUid(@ullable String packageName)2360     void assertPackageMatchesCallingUid(@Nullable String packageName) {
2361         final int callingUid = Binder.getCallingUid();
2362         if (isSameApp(callingUid, packageName)) {
2363             return;
2364         }
2365         final String msg = "Permission Denial: package=" + packageName
2366                 + " does not belong to uid=" + callingUid;
2367         Slog.w(TAG, msg);
2368         throw new SecurityException(msg);
2369     }
2370 
2371     /**
2372      * Return true if app switching is allowed.
2373      */
getBalAppSwitchesState()2374     @AppSwitchState int getBalAppSwitchesState() {
2375         return mAppSwitchesState;
2376     }
2377 
2378     /** Register an {@link AnrController} to control the ANR dialog behavior */
registerAnrController(AnrController controller)2379     public void registerAnrController(AnrController controller) {
2380         synchronized (mAnrController) {
2381             mAnrController.add(controller);
2382         }
2383     }
2384 
2385     /** Unregister an {@link AnrController} */
unregisterAnrController(AnrController controller)2386     public void unregisterAnrController(AnrController controller) {
2387         synchronized (mAnrController) {
2388             mAnrController.remove(controller);
2389         }
2390     }
2391 
2392     /**
2393      * @return the controller with the max ANR delay from all registered
2394      * {@link AnrController} instances
2395      */
2396     @Nullable
getAnrController(ApplicationInfo info)2397     public AnrController getAnrController(ApplicationInfo info) {
2398         if (info == null || info.packageName == null) {
2399             return null;
2400         }
2401 
2402         final ArrayList<AnrController> controllers;
2403         synchronized (mAnrController) {
2404             controllers = new ArrayList<>(mAnrController);
2405         }
2406 
2407         final String packageName = info.packageName;
2408         final int uid = info.uid;
2409         long maxDelayMs = 0;
2410         AnrController controllerWithMaxDelay = null;
2411 
2412         for (AnrController controller : controllers) {
2413             long delayMs = controller.getAnrDelayMillis(packageName, uid);
2414             if (delayMs > 0 && delayMs > maxDelayMs) {
2415                 controllerWithMaxDelay = controller;
2416                 maxDelayMs = delayMs;
2417             }
2418         }
2419 
2420         return controllerWithMaxDelay;
2421     }
2422 
2423     @Override
setActivityController(IActivityController controller, boolean imAMonkey)2424     public void setActivityController(IActivityController controller, boolean imAMonkey) {
2425         mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2426                 "setActivityController()");
2427         synchronized (mGlobalLock) {
2428             mController = controller;
2429             mControllerIsAMonkey = imAMonkey;
2430             Watchdog.getInstance().setActivityController(controller);
2431         }
2432     }
2433 
isControllerAMonkey()2434     public boolean isControllerAMonkey() {
2435         synchronized (mGlobalLock) {
2436             return mController != null && mControllerIsAMonkey;
2437         }
2438     }
2439 
2440     /**
2441      * Gets info of running tasks up to the given number.
2442      *
2443      * @param maxNum the maximum number of task info returned by this method. If the total number of
2444      *               running tasks is larger than it then there is no guarantee which task will be
2445      *               left out.
2446      * @return a list of {@link ActivityManager.RunningTaskInfo} with up to {@code maxNum} items
2447      */
getTasks(int maxNum)2448     public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2449         return getTasks(maxNum, false /* filterForVisibleRecents */, false /* keepIntentExtra */,
2450                 INVALID_DISPLAY);
2451     }
2452 
2453     /**
2454      * @param filterOnlyVisibleRecents whether to filter the tasks based on whether they would ever
2455      *                                 be visible in the recent task list in systemui
2456      */
getTasks(int maxNum, boolean filterOnlyVisibleRecents, boolean keepIntentExtra)2457     public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum,
2458             boolean filterOnlyVisibleRecents, boolean keepIntentExtra) {
2459         return getTasks(maxNum, filterOnlyVisibleRecents, keepIntentExtra, INVALID_DISPLAY);
2460     }
2461 
2462     /**
2463      * @param displayId the target display id, or {@link INVALID_DISPLAY} not to filter by displayId
2464      */
2465     @Override
getTasks(int maxNum, boolean filterOnlyVisibleRecents, boolean keepIntentExtra, int displayId)2466     public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum,
2467             boolean filterOnlyVisibleRecents, boolean keepIntentExtra, int displayId) {
2468         final int callingUid = Binder.getCallingUid();
2469         final int callingPid = Binder.getCallingPid();
2470 
2471         int flags = filterOnlyVisibleRecents ? RunningTasks.FLAG_FILTER_ONLY_VISIBLE_RECENTS : 0;
2472         flags |= (keepIntentExtra ? RunningTasks.FLAG_KEEP_INTENT_EXTRA : 0);
2473         final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
2474         flags |= (crossUser ? RunningTasks.FLAG_CROSS_USERS : 0);
2475         final int[] profileIds = getUserManager().getProfileIds(
2476                 UserHandle.getUserId(callingUid), true);
2477         ArraySet<Integer> callingProfileIds = new ArraySet<>();
2478         for (int i = 0; i < profileIds.length; i++) {
2479             callingProfileIds.add(profileIds[i]);
2480         }
2481         ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2482 
2483         synchronized (mGlobalLock) {
2484             if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2485 
2486             final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
2487             flags |= (allowed ? RunningTasks.FLAG_ALLOWED : 0);
2488             mRootWindowContainer.getRunningTasks(
2489                     maxNum, list, flags, callingUid, callingProfileIds, displayId);
2490         }
2491 
2492         return list;
2493     }
2494 
2495     @Override
moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)2496     public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) {
2497         enforceTaskPermission("moveTaskToRootTask()");
2498         synchronized (mGlobalLock) {
2499             final long ident = Binder.clearCallingIdentity();
2500             try {
2501                 final Task task = mRootWindowContainer.anyTaskForId(taskId);
2502                 if (task == null) {
2503                     Slog.w(TAG, "moveTaskToRootTask: No task for id=" + taskId);
2504                     return;
2505                 }
2506 
2507                 ProtoLog.d(WM_DEBUG_TASKS, "moveTaskToRootTask: moving task=%d to "
2508                         + "rootTaskId=%d toTop=%b", taskId, rootTaskId, toTop);
2509 
2510                 final Task rootTask = mRootWindowContainer.getRootTask(rootTaskId);
2511                 if (rootTask == null) {
2512                     throw new IllegalStateException(
2513                             "moveTaskToRootTask: No rootTask for rootTaskId=" + rootTaskId);
2514                 }
2515                 if (!rootTask.isActivityTypeStandardOrUndefined()) {
2516                     throw new IllegalArgumentException("moveTaskToRootTask: Attempt to move task "
2517                             + taskId + " to rootTask " + rootTaskId);
2518                 }
2519                 task.reparent(rootTask, toTop, REPARENT_KEEP_ROOT_TASK_AT_FRONT, ANIMATE,
2520                         !DEFER_RESUME, "moveTaskToRootTask");
2521             } finally {
2522                 Binder.restoreCallingIdentity(ident);
2523             }
2524         }
2525     }
2526 
2527     /**
2528      * Removes root tasks in the input windowing modes from the system if they are of activity type
2529      * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2530      */
2531     @Override
removeRootTasksInWindowingModes(int[] windowingModes)2532     public void removeRootTasksInWindowingModes(int[] windowingModes) {
2533         enforceTaskPermission("removeRootTasksInWindowingModes()");
2534 
2535         synchronized (mGlobalLock) {
2536             final long ident = Binder.clearCallingIdentity();
2537             try {
2538                 mRootWindowContainer.removeRootTasksInWindowingModes(windowingModes);
2539             } finally {
2540                 Binder.restoreCallingIdentity(ident);
2541             }
2542         }
2543     }
2544 
2545     @Override
removeRootTasksWithActivityTypes(int[] activityTypes)2546     public void removeRootTasksWithActivityTypes(int[] activityTypes) {
2547         enforceTaskPermission("removeRootTasksWithActivityTypes()");
2548 
2549         synchronized (mGlobalLock) {
2550             final long ident = Binder.clearCallingIdentity();
2551             try {
2552                 mRootWindowContainer.removeRootTasksWithActivityTypes(activityTypes);
2553             } finally {
2554                 Binder.restoreCallingIdentity(ident);
2555             }
2556         }
2557     }
2558 
2559     @Override
getRecentTasks(int maxNum, int flags, int userId)2560     public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2561             int userId) {
2562         final int callingUid = Binder.getCallingUid();
2563         userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2564         final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
2565                 callingUid);
2566         if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_AND_UNLOCKED)) {
2567             Slog.i(TAG, "User " + userId + " is locked. Cannot load recents");
2568             return ParceledListSlice.emptyList();
2569         }
2570         mRecentTasks.loadRecentTasksIfNeeded(userId);
2571         synchronized (mGlobalLock) {
2572             return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
2573         }
2574     }
2575 
2576     @Override
getAllRootTaskInfos()2577     public List<RootTaskInfo> getAllRootTaskInfos() {
2578         enforceTaskPermission("getAllRootTaskInfos()");
2579         final long ident = Binder.clearCallingIdentity();
2580         try {
2581             synchronized (mGlobalLock) {
2582                 return mRootWindowContainer.getAllRootTaskInfos(INVALID_DISPLAY);
2583             }
2584         } finally {
2585             Binder.restoreCallingIdentity(ident);
2586         }
2587     }
2588 
2589     @Override
getRootTaskInfo(int windowingMode, int activityType)2590     public RootTaskInfo getRootTaskInfo(int windowingMode, int activityType) {
2591         enforceTaskPermission("getRootTaskInfo()");
2592         final long ident = Binder.clearCallingIdentity();
2593         try {
2594             synchronized (mGlobalLock) {
2595                 return mRootWindowContainer.getRootTaskInfo(windowingMode, activityType);
2596             }
2597         } finally {
2598             Binder.restoreCallingIdentity(ident);
2599         }
2600     }
2601 
2602     @Override
getAllRootTaskInfosOnDisplay(int displayId)2603     public List<RootTaskInfo> getAllRootTaskInfosOnDisplay(int displayId) {
2604         enforceTaskPermission("getAllRootTaskInfosOnDisplay()");
2605         final long ident = Binder.clearCallingIdentity();
2606         try {
2607             synchronized (mGlobalLock) {
2608                 return mRootWindowContainer.getAllRootTaskInfos(displayId);
2609             }
2610         } finally {
2611             Binder.restoreCallingIdentity(ident);
2612         }
2613     }
2614 
2615     @Override
getRootTaskInfoOnDisplay(int windowingMode, int activityType, int displayId)2616     public RootTaskInfo getRootTaskInfoOnDisplay(int windowingMode, int activityType,
2617             int displayId) {
2618         enforceTaskPermission("getRootTaskInfoOnDisplay()");
2619         final long ident = Binder.clearCallingIdentity();
2620         try {
2621             synchronized (mGlobalLock) {
2622                 return mRootWindowContainer.getRootTaskInfo(windowingMode, activityType, displayId);
2623             }
2624         } finally {
2625             Binder.restoreCallingIdentity(ident);
2626         }
2627     }
2628 
2629     @Override
startSystemLockTaskMode(int taskId)2630     public void startSystemLockTaskMode(int taskId) {
2631         enforceTaskPermission("startSystemLockTaskMode");
2632         // This makes inner call to look as if it was initiated by system.
2633         final long ident = Binder.clearCallingIdentity();
2634         try {
2635             synchronized (mGlobalLock) {
2636                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2637                         MATCH_ATTACHED_TASK_ONLY);
2638                 if (task == null) {
2639                     return;
2640                 }
2641 
2642                 // When starting lock task mode the root task must be in front and focused
2643                 task.getRootTask().moveToFront("startSystemLockTaskMode");
2644                 startLockTaskMode(task, true /* isSystemCaller */);
2645             }
2646         } finally {
2647             Binder.restoreCallingIdentity(ident);
2648         }
2649     }
2650 
2651     /**
2652      * This API should be called by SystemUI only when user perform certain action to dismiss
2653      * lock task mode. We should only dismiss pinned lock task mode in this case.
2654      */
2655     @Override
stopSystemLockTaskMode()2656     public void stopSystemLockTaskMode() throws RemoteException {
2657         enforceTaskPermission("stopSystemLockTaskMode");
2658         stopLockTaskModeInternal(null, true /* isSystemCaller */);
2659     }
2660 
startLockTaskMode(@ullable Task task, boolean isSystemCaller)2661     void startLockTaskMode(@Nullable Task task, boolean isSystemCaller) {
2662         ProtoLog.w(WM_DEBUG_LOCKTASK, "startLockTaskMode: %s", task);
2663         if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2664             return;
2665         }
2666 
2667         final Task rootTask = mRootWindowContainer.getTopDisplayFocusedRootTask();
2668         if (rootTask == null || task != rootTask.getTopMostTask()) {
2669             throw new IllegalArgumentException("Invalid task, not in foreground");
2670         }
2671 
2672         // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2673         // system or a specific app.
2674         // * System-initiated requests will only start the pinned mode (screen pinning)
2675         // * App-initiated requests
2676         //   - will put the device in fully locked mode (LockTask), if the app is allowlisted
2677         //   - will start the pinned mode, otherwise
2678         final int callingUid = Binder.getCallingUid();
2679         final long ident = Binder.clearCallingIdentity();
2680         try {
2681             getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
2682         } finally {
2683             Binder.restoreCallingIdentity(ident);
2684         }
2685     }
2686 
stopLockTaskModeInternal(@ullable IBinder token, boolean isSystemCaller)2687     void stopLockTaskModeInternal(@Nullable IBinder token, boolean isSystemCaller) {
2688         final int callingUid = Binder.getCallingUid();
2689         final long ident = Binder.clearCallingIdentity();
2690         try {
2691             synchronized (mGlobalLock) {
2692                 Task task = null;
2693                 if (token != null) {
2694                     final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2695                     if (r == null) {
2696                         return;
2697                     }
2698                     task = r.getTask();
2699                 }
2700                 // If {@code isSystemCaller} is {@code true}, it means the user intends to stop
2701                 // pinned mode through UI; otherwise, it's called by an app and we need to stop
2702                 // locked or pinned mode, subject to checks.
2703                 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
2704             }
2705             // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2706             // task and jumping straight into a call in the case of emergency call back.
2707             TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2708             if (tm != null) {
2709                 tm.showInCallScreen(false);
2710             }
2711         } finally {
2712             Binder.restoreCallingIdentity(ident);
2713         }
2714     }
2715 
2716     @Override
updateLockTaskPackages(int userId, String[] packages)2717     public void updateLockTaskPackages(int userId, String[] packages) {
2718         final int callingUid = Binder.getCallingUid();
2719         if (callingUid != 0 && callingUid != SYSTEM_UID) {
2720             mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2721                     "updateLockTaskPackages()");
2722         }
2723         final long origId = Binder.clearCallingIdentity();
2724         try {
2725             synchronized (mGlobalLock) {
2726                 ProtoLog.w(WM_DEBUG_LOCKTASK, "Allowlisting %d:%s", userId,
2727                         Arrays.toString(packages));
2728                 getLockTaskController().updateLockTaskPackages(userId, packages);
2729             }
2730         } finally {
2731             Binder.restoreCallingIdentity(origId);
2732         }
2733     }
2734 
2735     @Override
isInLockTaskMode()2736     public boolean isInLockTaskMode() {
2737         return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2738     }
2739 
2740     @Override
getLockTaskModeState()2741     public int getLockTaskModeState() {
2742         return getLockTaskController().getLockTaskModeState();
2743     }
2744 
2745     @Override
getAppTasks(String callingPackage)2746     public List<IBinder> getAppTasks(String callingPackage) {
2747         assertPackageMatchesCallingUid(callingPackage);
2748         return getAppTasks(callingPackage, Binder.getCallingUid());
2749     }
2750 
getAppTasks(String pkgName, int uid)2751     private List<IBinder> getAppTasks(String pkgName, int uid) {
2752         final long ident = Binder.clearCallingIdentity();
2753         try {
2754             synchronized (mGlobalLock) {
2755                 return mRecentTasks.getAppTasksList(uid, pkgName);
2756             }
2757         } finally {
2758             Binder.restoreCallingIdentity(ident);
2759         }
2760     }
2761 
2762     @Override
finishVoiceTask(IVoiceInteractionSession session)2763     public void finishVoiceTask(IVoiceInteractionSession session) {
2764         synchronized (mGlobalLock) {
2765             final long origId = Binder.clearCallingIdentity();
2766             try {
2767                 // TODO: VI Consider treating local voice interactions and voice tasks
2768                 // differently here
2769                 mRootWindowContainer.finishVoiceTask(session);
2770             } finally {
2771                 Binder.restoreCallingIdentity(origId);
2772             }
2773         }
2774 
2775     }
2776 
2777     @Override
reportAssistContextExtras(IBinder assistToken, Bundle extras, AssistStructure structure, AssistContent content, Uri referrer)2778     public void reportAssistContextExtras(IBinder assistToken, Bundle extras,
2779             AssistStructure structure, AssistContent content, Uri referrer) {
2780         final PendingAssistExtras pae = (PendingAssistExtras) assistToken;
2781         synchronized (pae) {
2782             pae.result = extras;
2783             pae.structure = structure;
2784             pae.content = content;
2785             if (referrer != null) {
2786                 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2787             }
2788             if (!pae.activity.isAttached()) {
2789                 // Skip directly because the caller activity may have been destroyed. If a caller
2790                 // is waiting for the assist data, it will be notified by timeout
2791                 // (see PendingAssistExtras#run()) and then pendingAssistExtrasTimedOut will clean
2792                 // up the request.
2793                 return;
2794             }
2795             if (structure != null) {
2796                 // Pre-fill the task/activity component for all assist data receivers
2797                 structure.setTaskId(pae.activity.getTask().mTaskId);
2798                 structure.setActivityComponent(pae.activity.mActivityComponent);
2799                 structure.setHomeActivity(pae.isHome);
2800             }
2801             pae.haveResult = true;
2802             pae.notifyAll();
2803             if (pae.intent == null && pae.receiver == null) {
2804                 // Caller is just waiting for the result.
2805                 return;
2806             }
2807         }
2808         // We are now ready to launch the assist activity.
2809         IAssistDataReceiver sendReceiver = null;
2810         Bundle sendBundle = null;
2811         synchronized (mGlobalLock) {
2812             buildAssistBundleLocked(pae, extras);
2813             boolean exists = mPendingAssistExtras.remove(pae);
2814             mUiHandler.removeCallbacks(pae);
2815             if (!exists) {
2816                 // Timed out.
2817                 return;
2818             }
2819 
2820             if ((sendReceiver = pae.receiver) != null) {
2821                 // Caller wants result sent back to them.
2822                 sendBundle = new Bundle();
2823                 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
2824                         pae.activity.getTask().mTaskId);
2825                 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
2826                         pae.activity.assistToken);
2827                 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2828                 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2829                 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2830                 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2831             }
2832         }
2833         if (sendReceiver != null) {
2834             try {
2835                 sendReceiver.onHandleAssistData(sendBundle);
2836             } catch (RemoteException e) {
2837             }
2838             return;
2839         }
2840 
2841         final long ident = Binder.clearCallingIdentity();
2842         try {
2843             pae.intent.replaceExtras(pae.extras);
2844             pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2845                     | Intent.FLAG_ACTIVITY_SINGLE_TOP
2846                     | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2847             mInternal.closeSystemDialogs("assist");
2848 
2849             try {
2850                 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2851             } catch (ActivityNotFoundException e) {
2852                 Slog.w(TAG, "No activity to handle assist action.", e);
2853             }
2854         } finally {
2855             Binder.restoreCallingIdentity(ident);
2856         }
2857     }
2858 
2859     @Override
addAppTask(IBinder activityToken, Intent intent, ActivityManager.TaskDescription description, Bitmap thumbnail)2860     public int addAppTask(IBinder activityToken, Intent intent,
2861             ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2862         final int callingUid = Binder.getCallingUid();
2863         final long callingIdent = Binder.clearCallingIdentity();
2864 
2865         try {
2866             synchronized (mGlobalLock) {
2867                 ActivityRecord r = ActivityRecord.isInRootTaskLocked(activityToken);
2868                 if (r == null) {
2869                     throw new IllegalArgumentException("Activity does not exist; token="
2870                             + activityToken);
2871                 }
2872                 ComponentName comp = intent.getComponent();
2873                 if (comp == null) {
2874                     throw new IllegalArgumentException("Intent " + intent
2875                             + " must specify explicit component");
2876                 }
2877                 if (thumbnail.getWidth() != mThumbnailWidth
2878                         || thumbnail.getHeight() != mThumbnailHeight) {
2879                     throw new IllegalArgumentException("Bad thumbnail size: got "
2880                             + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
2881                             + mThumbnailWidth + "x" + mThumbnailHeight);
2882                 }
2883                 if (intent.getSelector() != null) {
2884                     intent.setSelector(null);
2885                 }
2886                 if (intent.getSourceBounds() != null) {
2887                     intent.setSourceBounds(null);
2888                 }
2889                 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2890                     if ((intent.getFlags() & Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2891                         // The caller has added this as an auto-remove task...  that makes no
2892                         // sense, so turn off auto-remove.
2893                         intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2894                     }
2895                 }
2896                 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2897                         STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2898                 if (ainfo == null || ainfo.applicationInfo.uid != callingUid) {
2899                     Slog.e(TAG, "Can't add task for another application: target uid="
2900                             + (ainfo == null ? Process.INVALID_UID : ainfo.applicationInfo.uid)
2901                             + ", calling uid=" + callingUid);
2902                     return INVALID_TASK_ID;
2903                 }
2904 
2905                 final Task rootTask = r.getRootTask();
2906                 final Task task = new Task.Builder(this)
2907                         .setWindowingMode(rootTask.getWindowingMode())
2908                         .setActivityType(rootTask.getActivityType())
2909                         .setActivityInfo(ainfo)
2910                         .setIntent(intent)
2911                         .setTaskId(rootTask.getDisplayArea().getNextRootTaskId())
2912                         .build();
2913 
2914                 if (!mRecentTasks.addToBottom(task)) {
2915                     // The app has too many tasks already and we can't add any more
2916                     rootTask.removeChild(task, "addAppTask");
2917                     return INVALID_TASK_ID;
2918                 }
2919                 task.getTaskDescription().copyFrom(description);
2920 
2921                 // TODO: Send the thumbnail to WM to store it.
2922 
2923                 return task.mTaskId;
2924             }
2925         } finally {
2926             Binder.restoreCallingIdentity(callingIdent);
2927         }
2928     }
2929 
2930     @Override
getAppTaskThumbnailSize()2931     public Point getAppTaskThumbnailSize() {
2932         synchronized (mGlobalLock) {
2933             return new Point(mThumbnailWidth, mThumbnailHeight);
2934         }
2935     }
2936 
2937     @Override
setTaskResizeable(int taskId, int resizeableMode)2938     public void setTaskResizeable(int taskId, int resizeableMode) {
2939         synchronized (mGlobalLock) {
2940             final Task task = mRootWindowContainer.anyTaskForId(
2941                     taskId, MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
2942             if (task == null) {
2943                 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2944                 return;
2945             }
2946             task.setResizeMode(resizeableMode);
2947         }
2948     }
2949 
2950     @Override
resizeTask(int taskId, Rect bounds, int resizeMode)2951     public void resizeTask(int taskId, Rect bounds, int resizeMode) {
2952         enforceTaskPermission("resizeTask()");
2953         final long ident = Binder.clearCallingIdentity();
2954         try {
2955             synchronized (mGlobalLock) {
2956                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2957                         MATCH_ATTACHED_TASK_ONLY);
2958                 if (task == null) {
2959                     Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2960                     return;
2961                 }
2962                 if (!task.getWindowConfiguration().canResizeTask()) {
2963                     Slog.w(TAG, "resizeTask not allowed on task=" + task);
2964                     return;
2965                 }
2966 
2967                 // Reparent the task to the right root task if necessary
2968                 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2969 
2970                 if (!getTransitionController().isShellTransitionsEnabled()) {
2971                     // After reparenting (which only resizes the task to the root task bounds),
2972                     // resize the task to the actual bounds provided
2973                     task.resize(bounds, resizeMode, preserveWindow);
2974                     return;
2975                 }
2976 
2977                 final Transition transition = new Transition(TRANSIT_CHANGE, 0 /* flags */,
2978                         getTransitionController(), mWindowManager.mSyncEngine);
2979                 getTransitionController().startCollectOrQueue(transition,
2980                         (deferred) -> {
2981                             if (deferred && !task.getWindowConfiguration().canResizeTask()) {
2982                                 Slog.w(TAG, "resizeTask not allowed on task=" + task);
2983                                 transition.abort();
2984                                 return;
2985                             }
2986                             getTransitionController().requestStartTransition(transition, task,
2987                                     null /* remoteTransition */, null /* displayChange */);
2988                             transition.collect(task);
2989                             task.resize(bounds, resizeMode, preserveWindow);
2990                             transition.setReady(task, true);
2991                         });
2992             }
2993         } finally {
2994             Binder.restoreCallingIdentity(ident);
2995         }
2996     }
2997 
2998     @Override
releaseSomeActivities(IApplicationThread appInt)2999     public void releaseSomeActivities(IApplicationThread appInt) {
3000         synchronized (mGlobalLock) {
3001             final long origId = Binder.clearCallingIdentity();
3002             try {
3003                 final WindowProcessController app = getProcessController(appInt);
3004                 app.releaseSomeActivities("low-mem");
3005             } finally {
3006                 Binder.restoreCallingIdentity(origId);
3007             }
3008         }
3009     }
3010 
3011     @Override
setLockScreenShown(boolean keyguardShowing, boolean aodShowing)3012     public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
3013         if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
3014                 != PackageManager.PERMISSION_GRANTED) {
3015             throw new SecurityException("Requires permission "
3016                     + android.Manifest.permission.DEVICE_POWER);
3017         }
3018         final long ident = Binder.clearCallingIdentity();
3019         try {
3020             synchronized (mGlobalLock) {
3021                 setLockScreenShownLocked(keyguardShowing, aodShowing);
3022             }
3023         } finally {
3024             Binder.restoreCallingIdentity(ident);
3025         }
3026     }
3027 
3028     @GuardedBy("mGlobalLock")
setLockScreenShownLocked(boolean keyguardShowing, boolean aodShowing)3029     void setLockScreenShownLocked(boolean keyguardShowing, boolean aodShowing) {
3030         if (mKeyguardShown != keyguardShowing) {
3031             mKeyguardShown = keyguardShowing;
3032             final Message msg = PooledLambda.obtainMessage(
3033                     ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3034                     keyguardShowing);
3035             mH.sendMessage(msg);
3036         }
3037         // Always reset the state regardless of keyguard-showing change, because that means the
3038         // unlock is either completed or canceled.
3039         if ((mDemoteTopAppReasons & DEMOTE_TOP_REASON_DURING_UNLOCKING) != 0) {
3040             mDemoteTopAppReasons &= ~DEMOTE_TOP_REASON_DURING_UNLOCKING;
3041             // The scheduling group of top process was demoted by unlocking, so recompute
3042             // to restore its real top priority if possible.
3043             if (mTopApp != null) {
3044                 mTopApp.scheduleUpdateOomAdj();
3045             }
3046         }
3047         try {
3048             Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "setLockScreenShown");
3049             mRootWindowContainer.forAllDisplays(displayContent -> {
3050                 mKeyguardController.setKeyguardShown(displayContent.getDisplayId(),
3051                         keyguardShowing, aodShowing);
3052             });
3053             maybeHideLockedProfileActivityLocked();
3054         } finally {
3055             Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
3056         }
3057 
3058         mH.post(() -> {
3059             for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3060                 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3061             }
3062         });
3063     }
3064 
3065     /**
3066      * Hides locked profile activity by going to home screen to avoid showing the user two lock
3067      * screens in a row.
3068      */
3069     @GuardedBy("mGlobalLock")
maybeHideLockedProfileActivityLocked()3070     private void maybeHideLockedProfileActivityLocked() {
3071         if (!mKeyguardController.isKeyguardLocked(DEFAULT_DISPLAY)
3072                 || mLastResumedActivity == null) {
3073             return;
3074         }
3075         var userInfo = getUserManager().getUserInfo(mLastResumedActivity.mUserId);
3076         if (userInfo == null || !userInfo.isManagedProfile()) {
3077             return;
3078         }
3079         if (mAmInternal.shouldConfirmCredentials(mLastResumedActivity.mUserId)) {
3080             mInternal.startHomeActivity(
3081                     mAmInternal.getCurrentUserId(), "maybeHideLockedProfileActivityLocked");
3082         }
3083     }
3084 
3085     // The caller MUST NOT hold the global lock.
onScreenAwakeChanged(boolean isAwake)3086     public void onScreenAwakeChanged(boolean isAwake) {
3087         mH.post(() -> {
3088             for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3089                 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3090             }
3091         });
3092 
3093         if (isAwake) {
3094             return;
3095         }
3096         // If the device is going to sleep, keep a higher priority temporarily for potential
3097         // animation of system UI. Even if AOD is not enabled, it should be no harm.
3098         final WindowProcessController proc;
3099         synchronized (mGlobalLockWithoutBoost) {
3100             mDemoteTopAppReasons &= ~DEMOTE_TOP_REASON_DURING_UNLOCKING;
3101             final WindowState notificationShade = mRootWindowContainer.getDefaultDisplay()
3102                     .getDisplayPolicy().getNotificationShade();
3103             proc = notificationShade != null ? notificationShade.getProcess() : null;
3104         }
3105         setProcessAnimatingWhileDozing(proc);
3106     }
3107 
3108     // The caller MUST NOT hold the global lock because it calls AM method directly.
setProcessAnimatingWhileDozing(WindowProcessController proc)3109     void setProcessAnimatingWhileDozing(WindowProcessController proc) {
3110         if (proc == null) return;
3111         // Set to activity manager directly to make sure the state can be seen by the subsequent
3112         // update of scheduling group.
3113         proc.setRunningAnimationUnsafe();
3114         mH.sendMessage(mH.obtainMessage(H.ADD_WAKEFULNESS_ANIMATING_REASON, proc));
3115         mH.removeMessages(H.REMOVE_WAKEFULNESS_ANIMATING_REASON, proc);
3116         mH.sendMessageDelayed(mH.obtainMessage(H.REMOVE_WAKEFULNESS_ANIMATING_REASON, proc),
3117                 DOZE_ANIMATING_STATE_RETAIN_TIME_MS);
3118         Trace.instant(TRACE_TAG_WINDOW_MANAGER, "requestWakefulnessAnimating");
3119     }
3120 
3121     @Override
getTaskDescriptionIcon(String filePath, int userId)3122     public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
3123         final int callingUid = Binder.getCallingUid();
3124         // Verify that the caller can make the request for the given userId
3125         userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
3126                 "getTaskDescriptionIcon");
3127         synchronized (mGlobalLock) {
3128             // Verify that the caller can make the request for given icon file path
3129             final ActivityRecord matchingActivity = mRootWindowContainer.getActivity(
3130                     r -> {
3131                         if (r.taskDescription == null
3132                                 || r.taskDescription.getIconFilename() == null) {
3133                             return false;
3134                         }
3135                         return r.taskDescription.getIconFilename().equals(filePath);
3136                     });
3137             if (matchingActivity == null || (matchingActivity.getUid() != callingUid)) {
3138                 // Caller UID doesn't match the requested Activity's UID, check if caller is
3139                 // privileged
3140                 try {
3141                     enforceActivityTaskPermission("getTaskDescriptionIcon");
3142                 } catch (SecurityException e) {
3143                     Slog.w(TAG, "getTaskDescriptionIcon(): request (callingUid=" + callingUid
3144                             + ", filePath=" + filePath + ", user=" + userId + ") doesn't match any "
3145                             + "activity");
3146                     throw e;
3147                 }
3148             }
3149         }
3150 
3151         final File passedIconFile = new File(filePath);
3152         final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3153                 passedIconFile.getName());
3154         if (!legitIconFile.getPath().equals(filePath)
3155                 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3156             throw new IllegalArgumentException("Bad file path: " + filePath
3157                     + " passed for userId " + userId);
3158         }
3159         return mRecentTasks.getTaskDescriptionIcon(filePath);
3160     }
3161 
3162     @Override
moveRootTaskToDisplay(int taskId, int displayId)3163     public void moveRootTaskToDisplay(int taskId, int displayId) {
3164         mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveRootTaskToDisplay()");
3165 
3166         synchronized (mGlobalLock) {
3167             final long ident = Binder.clearCallingIdentity();
3168             try {
3169                 ProtoLog.d(WM_DEBUG_TASKS, "moveRootTaskToDisplay: moving taskId=%d to "
3170                         + "displayId=%d", taskId, displayId);
3171                 mRootWindowContainer.moveRootTaskToDisplay(taskId, displayId, ON_TOP);
3172             } finally {
3173                 Binder.restoreCallingIdentity(ident);
3174             }
3175         }
3176     }
3177 
3178     /** Sets the task stack listener that gets callbacks when a task stack changes. */
3179     @Override
registerTaskStackListener(ITaskStackListener listener)3180     public void registerTaskStackListener(ITaskStackListener listener) {
3181         enforceTaskPermission("registerTaskStackListener()");
3182         mTaskChangeNotificationController.registerTaskStackListener(listener);
3183     }
3184 
3185     /** Unregister a task stack listener so that it stops receiving callbacks. */
3186     @Override
unregisterTaskStackListener(ITaskStackListener listener)3187     public void unregisterTaskStackListener(ITaskStackListener listener) {
3188         enforceTaskPermission("unregisterTaskStackListener()");
3189         mTaskChangeNotificationController.unregisterTaskStackListener(listener);
3190     }
3191 
3192     @Override
requestAssistContextExtras(int requestType, IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken, boolean checkActivityIsTop, boolean newSessionId)3193     public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3194             Bundle receiverExtras, IBinder activityToken, boolean checkActivityIsTop,
3195             boolean newSessionId) {
3196         return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3197                 activityToken, checkActivityIsTop, newSessionId, UserHandle.getCallingUserId(),
3198                 null, PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3199     }
3200 
3201     /**
3202      * Requests assist data for a particular Task.
3203      *
3204      * <p>This is used by the system components to request assist data for a Task.
3205      *
3206      * @param receiver The receiver to send the assist data to.
3207      * @param taskId The Task to request assist data for.
3208      * @param callingPackageName The package name of the caller.
3209      * @param callingAttributionTag The attribution tag of the caller.
3210      * @param fetchStructure Whether to fetch the assist structure. Note that this is slow and
3211      *     should be avoided if possible.
3212      * @return Whether the request was successful.
3213      */
3214     @Override
requestAssistDataForTask(IAssistDataReceiver receiver, int taskId, String callingPackageName, @Nullable String callingAttributionTag, boolean fetchStructure)3215     public boolean requestAssistDataForTask(IAssistDataReceiver receiver, int taskId,
3216             String callingPackageName, @Nullable String callingAttributionTag,
3217             boolean fetchStructure) {
3218         mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
3219                 "requestAssistDataForTask()");
3220         final long callingId = Binder.clearCallingIdentity();
3221         LocalService.ActivityTokens tokens = null;
3222         try {
3223             tokens = mInternal.getAttachedNonFinishingActivityForTask(taskId, null);
3224         } finally {
3225             Binder.restoreCallingIdentity(callingId);
3226         }
3227         if (tokens == null) {
3228             Log.e(TAG, "Could not find activity for task " + taskId);
3229             return false;
3230         }
3231 
3232         final AssistDataReceiverProxy proxy =
3233                 new AssistDataReceiverProxy(receiver, callingPackageName);
3234         Object lock = new Object();
3235         AssistDataRequester requester = new AssistDataRequester(mContext, mWindowManager,
3236                 getAppOpsManager(), proxy, lock, AppOpsManager.OP_ASSIST_STRUCTURE,
3237                 AppOpsManager.OP_NONE);
3238 
3239         List<IBinder> topActivityToken = new ArrayList<>();
3240         topActivityToken.add(tokens.getActivityToken());
3241         requester.requestAssistData(topActivityToken, true /* fetchData */,
3242                 false /* fetchScreenshot */, fetchStructure, true /* allowFetchData */,
3243                 false /* allowFetchScreenshot*/, true /* ignoreFocusCheck */,
3244                 Binder.getCallingUid(), callingPackageName, callingAttributionTag);
3245 
3246         return true;
3247     }
3248 
3249     @Override
requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken, int flags)3250     public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3251             IBinder activityToken, int flags) {
3252         return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3253                 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3254                 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3255     }
3256 
3257     @Override
getAssistContextExtras(int requestType)3258     public Bundle getAssistContextExtras(int requestType) {
3259         PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3260                 null, null, true /* checkActivityIsTop */, true /* newSessionId */,
3261                 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3262         if (pae == null) {
3263             return null;
3264         }
3265         synchronized (pae) {
3266             while (!pae.haveResult) {
3267                 try {
3268                     pae.wait();
3269                 } catch (InterruptedException e) {
3270                 }
3271             }
3272         }
3273         synchronized (mGlobalLock) {
3274             buildAssistBundleLocked(pae, pae.result);
3275             mPendingAssistExtras.remove(pae);
3276             mUiHandler.removeCallbacks(pae);
3277         }
3278         return pae.extras;
3279     }
3280 
3281     /**
3282      * Binder IPC calls go through the public entry point.
3283      * This can be called with or without the global lock held.
3284      */
checkCallingPermission(String permission)3285     private static int checkCallingPermission(String permission) {
3286         return checkPermission(
3287                 permission, Binder.getCallingPid(), Binder.getCallingUid());
3288     }
3289 
3290     /**
3291      * Returns true if the app can close system dialogs. Otherwise it either throws a {@link
3292      * SecurityException} or returns false with a logcat message depending on whether the app
3293      * targets SDK level {@link android.os.Build.VERSION_CODES#S} or not.
3294      */
checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName)3295     boolean checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName) {
3296         final WindowProcessController process;
3297         synchronized (mGlobalLock) {
3298             process = mProcessMap.getProcess(pid);
3299         }
3300         if (packageName == null && process != null) {
3301             // WindowProcessController.mInfo is final, so after the synchronized memory barrier
3302             // above, process.mInfo can't change. As for reading mInfo.packageName,
3303             // WindowProcessController doesn't own the ApplicationInfo object referenced by mInfo.
3304             // ProcessRecord for example also holds a reference to that object, so protecting access
3305             // to packageName with the WM lock would not be enough as we'd also need to synchronize
3306             // on the AM lock if we are worried about races, but we can't synchronize on AM lock
3307             // here. Hence, since this is only used for logging, we don't synchronize here.
3308             packageName = process.mInfo.packageName;
3309         }
3310         String caller = "(pid=" + pid + ", uid=" + uid + ")";
3311         if (packageName != null) {
3312             caller = packageName + " " + caller;
3313         }
3314         if (!canCloseSystemDialogs(pid, uid)) {
3315             // The app can't close system dialogs, throw only if it targets S+
3316             if (CompatChanges.isChangeEnabled(LOCK_DOWN_CLOSE_SYSTEM_DIALOGS, uid)) {
3317                 throw new SecurityException(
3318                         "Permission Denial: " + Intent.ACTION_CLOSE_SYSTEM_DIALOGS
3319                                 + " broadcast from " + caller + " requires "
3320                                 + Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS + ".");
3321             } else if (CompatChanges.isChangeEnabled(DROP_CLOSE_SYSTEM_DIALOGS, uid)) {
3322                 Slog.e(TAG,
3323                         "Permission Denial: " + Intent.ACTION_CLOSE_SYSTEM_DIALOGS
3324                                 + " broadcast from " + caller + " requires "
3325                                 + Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS
3326                                 + ", dropping broadcast.");
3327                 return false;
3328             } else {
3329                 Slog.w(TAG, Intent.ACTION_CLOSE_SYSTEM_DIALOGS
3330                         + " broadcast from " + caller + " will require "
3331                         + Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS
3332                         + " in future builds.");
3333                 return true;
3334             }
3335         }
3336         return true;
3337     }
3338 
canCloseSystemDialogs(int pid, int uid)3339     private boolean canCloseSystemDialogs(int pid, int uid) {
3340         if (checkPermission(Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS, pid, uid)
3341                 == PERMISSION_GRANTED) {
3342             return true;
3343         }
3344         synchronized (mGlobalLock) {
3345             // Check all the processes from the given uid, especially since for PendingIntents sent
3346             // the pid equals -1
3347             ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
3348             if (processes != null) {
3349                 for (int i = 0, n = processes.size(); i < n; i++) {
3350                     WindowProcessController process = processes.valueAt(i);
3351                     // Check if the instrumentation of the process has the permission. This covers
3352                     // the usual test started from the shell (which has the permission) case. This
3353                     // is needed for apps targeting SDK level < S but we are also allowing for
3354                     // targetSdk S+ as a convenience to avoid breaking a bunch of existing tests and
3355                     // asking them to adopt shell permissions to do this.
3356                     int sourceUid = process.getInstrumentationSourceUid();
3357                     if (process.isInstrumenting() && sourceUid != -1 && checkPermission(
3358                             Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS, -1, sourceUid)
3359                             == PERMISSION_GRANTED) {
3360                         return true;
3361                     }
3362                     // This is the notification trampoline use-case for example, where apps use
3363                     // Intent.ACSD to close the shade prior to starting an activity.
3364                     if (process.canCloseSystemDialogsByToken()) {
3365                         return true;
3366                     }
3367                 }
3368             }
3369             if (!CompatChanges.isChangeEnabled(LOCK_DOWN_CLOSE_SYSTEM_DIALOGS, uid)) {
3370                 // This covers the case where the app is displaying some UI on top of the
3371                 // notification shade and wants to start an activity. The app then sends the intent
3372                 // in order to move the notification shade out of the way and show the activity to
3373                 // the user. This is fine since the caller already has privilege to show a visible
3374                 // window on top of the notification shade, so it can already prevent the user from
3375                 // accessing the shade if it wants to. We only allow for targetSdk < S, for S+ we
3376                 // automatically collapse the shade on startActivity() for these apps.
3377                 // It's ok that the owner of the shade is not allowed *per this rule* because it has
3378                 // BROADCAST_CLOSE_SYSTEM_DIALOGS (SystemUI), so it would fall into that rule.
3379                 if (mRootWindowContainer.hasVisibleWindowAboveButDoesNotOwnNotificationShade(uid)) {
3380                     return true;
3381                 }
3382                 // Accessibility services are allowed to send the intent unless they are targeting
3383                 // S+, in which case they should use {@link AccessibilityService
3384                 // #GLOBAL_ACTION_DISMISS_NOTIFICATION_SHADE} to dismiss the notification shade.
3385                 if (ArrayUtils.contains(mAccessibilityServiceUids, uid)) {
3386                     return true;
3387                 }
3388             }
3389         }
3390         return false;
3391     }
3392 
3393     /**
3394      * An instance method that's easier for mocking in tests.
3395      */
enforceActivityTaskPermission(String func)3396     void enforceActivityTaskPermission(String func) {
3397         enforceTaskPermission(func);
3398     }
3399 
enforceTaskPermission(String func)3400     static void enforceTaskPermission(String func) {
3401         if (checkCallingPermission(MANAGE_ACTIVITY_TASKS) == PackageManager.PERMISSION_GRANTED) {
3402             return;
3403         }
3404 
3405         if (checkCallingPermission(MANAGE_ACTIVITY_STACKS) == PackageManager.PERMISSION_GRANTED) {
3406             Slog.w(TAG, "MANAGE_ACTIVITY_STACKS is deprecated, "
3407                     + "please use alternative permission: MANAGE_ACTIVITY_TASKS");
3408             return;
3409         }
3410 
3411         String msg = "Permission Denial: " + func + " from pid=" + Binder.getCallingPid() + ", uid="
3412                 + Binder.getCallingUid() + " requires android.permission.MANAGE_ACTIVITY_TASKS";
3413         Slog.w(TAG, msg);
3414         throw new SecurityException(msg);
3415     }
3416 
checkPermission(String permission, int pid, int uid)3417     static int checkPermission(String permission, int pid, int uid) {
3418         if (permission == null) {
3419             return PackageManager.PERMISSION_DENIED;
3420         }
3421         return checkComponentPermission(permission, pid, uid, -1, true);
3422     }
3423 
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)3424     public static int checkComponentPermission(String permission, int pid, int uid,
3425             int owningUid, boolean exported) {
3426         return ActivityManagerService.checkComponentPermission(
3427                 permission, pid, uid, owningUid, exported);
3428     }
3429 
isCallerRecents(int callingUid)3430     boolean isCallerRecents(int callingUid) {
3431         return mRecentTasks.isCallerRecents(callingUid);
3432     }
3433 
isGetTasksAllowed(String caller, int callingPid, int callingUid)3434     boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3435         if (isCallerRecents(callingUid)) {
3436             // Always allow the recents component to get tasks
3437             return true;
3438         }
3439 
3440         boolean allowed = checkPermission(android.Manifest.permission.REAL_GET_TASKS,
3441                 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3442         if (!allowed) {
3443             if (checkPermission(android.Manifest.permission.GET_TASKS,
3444                     callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3445                 // Temporary compatibility: some existing apps on the system image may
3446                 // still be requesting the old permission and not switched to the new
3447                 // one; if so, we'll still allow them full access.  This means we need
3448                 // to see if they are holding the old permission and are a system app.
3449                 try {
3450                     if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3451                         allowed = true;
3452                         ProtoLog.w(WM_DEBUG_TASKS,
3453                                 "%s: caller %d is using old GET_TASKS but privileged; allowing",
3454                                 caller, callingUid);
3455                     }
3456                 } catch (RemoteException e) {
3457                 }
3458             }
3459             ProtoLog.w(WM_DEBUG_TASKS,
3460                     "%s: caller %d does not hold REAL_GET_TASKS; limiting output", caller,
3461                     callingUid);
3462         }
3463         return allowed;
3464     }
3465 
isCrossUserAllowed(int pid, int uid)3466     boolean isCrossUserAllowed(int pid, int uid) {
3467         return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3468                 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3469     }
3470 
enqueueAssistContext(int requestType, Intent intent, String hint, IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken, boolean checkActivityIsTop, boolean newSessionId, int userHandle, Bundle args, long timeout, int flags)3471     private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3472             IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3473             boolean checkActivityIsTop, boolean newSessionId, int userHandle, Bundle args,
3474             long timeout, int flags) {
3475         mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
3476                 "enqueueAssistContext()");
3477 
3478         synchronized (mGlobalLock) {
3479             final Task rootTask = getTopDisplayFocusedRootTask();
3480             ActivityRecord activity =
3481                     rootTask != null ? rootTask.getTopNonFinishingActivity() : null;
3482             if (activity == null) {
3483                 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3484                 return null;
3485             }
3486             if (!activity.attachedToProcess()) {
3487                 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3488                 return null;
3489             }
3490             if (checkActivityIsTop) {
3491                 if (activityToken != null) {
3492                     ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3493                     if (activity != caller) {
3494                         Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3495                                 + " is not current top " + activity);
3496                         return null;
3497                     }
3498                 }
3499             } else {
3500                 activity = ActivityRecord.forTokenLocked(activityToken);
3501                 if (activity == null) {
3502                     Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3503                             + " couldn't be found");
3504                     return null;
3505                 }
3506                 if (!activity.attachedToProcess()) {
3507                     Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3508                     return null;
3509                 }
3510             }
3511 
3512             PendingAssistExtras pae;
3513             Bundle extras = new Bundle();
3514             if (args != null) {
3515                 extras.putAll(args);
3516             }
3517             extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
3518             extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
3519 
3520             pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3521                     userHandle);
3522             pae.isHome = activity.isActivityTypeHome();
3523 
3524             // Increment the sessionId if necessary
3525             if (newSessionId) {
3526                 mViSessionId++;
3527             }
3528             try {
3529                 activity.app.getThread().requestAssistContextExtras(activity.token, pae,
3530                         requestType, mViSessionId, flags);
3531                 mPendingAssistExtras.add(pae);
3532                 mUiHandler.postDelayed(pae, timeout);
3533             } catch (RemoteException e) {
3534                 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3535                 return null;
3536             }
3537             return pae;
3538         }
3539     }
3540 
buildAssistBundleLocked(PendingAssistExtras pae, Bundle result)3541     private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3542         if (result != null) {
3543             pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3544         }
3545         if (pae.hint != null) {
3546             pae.extras.putBoolean(pae.hint, true);
3547         }
3548     }
3549 
pendingAssistExtrasTimedOut(PendingAssistExtras pae)3550     private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3551         IAssistDataReceiver receiver;
3552         synchronized (mGlobalLock) {
3553             mPendingAssistExtras.remove(pae);
3554             receiver = pae.receiver;
3555         }
3556         if (receiver != null) {
3557             // Caller wants result sent back to them.
3558             Bundle sendBundle = new Bundle();
3559             // At least return the receiver extras
3560             sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3561             try {
3562                 pae.receiver.onHandleAssistData(sendBundle);
3563             } catch (RemoteException e) {
3564             }
3565         }
3566     }
3567 
3568     public class PendingAssistExtras extends Binder implements Runnable {
3569         public final ActivityRecord activity;
3570         public boolean isHome;
3571         public final Bundle extras;
3572         public final Intent intent;
3573         public final String hint;
3574         public final IAssistDataReceiver receiver;
3575         public final int userHandle;
3576         public boolean haveResult = false;
3577         public Bundle result = null;
3578         public AssistStructure structure = null;
3579         public AssistContent content = null;
3580         public Bundle receiverExtras;
3581 
PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent, String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras, int _userHandle)3582         public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3583                 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3584                 int _userHandle) {
3585             activity = _activity;
3586             extras = _extras;
3587             intent = _intent;
3588             hint = _hint;
3589             receiver = _receiver;
3590             receiverExtras = _receiverExtras;
3591             userHandle = _userHandle;
3592         }
3593 
3594         @Override
run()3595         public void run() {
3596             Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3597             synchronized (this) {
3598                 haveResult = true;
3599                 notifyAll();
3600             }
3601             pendingAssistExtrasTimedOut(this);
3602         }
3603     }
3604 
3605     @Override
isAssistDataAllowed()3606     public boolean isAssistDataAllowed() {
3607         int userId;
3608         boolean hasRestrictedWindow;
3609         synchronized (mGlobalLock) {
3610             final Task focusedRootTask = getTopDisplayFocusedRootTask();
3611             if (focusedRootTask == null || focusedRootTask.isActivityTypeAssistant()) {
3612                 return false;
3613             }
3614 
3615             final ActivityRecord activity = focusedRootTask.getTopNonFinishingActivity();
3616             if (activity == null) {
3617                 return false;
3618             }
3619             userId = activity.mUserId;
3620             DisplayContent displayContent = activity.getDisplayContent();
3621             if (displayContent == null) {
3622                 return false;
3623             }
3624             final long callingIdentity = Binder.clearCallingIdentity();
3625             try {
3626                 hasRestrictedWindow = displayContent.forAllWindows(
3627                         windowState -> windowState.isOnScreen() && (
3628                                 UserManager.isUserTypePrivateProfile(
3629                                         getUserManager().getProfileType(windowState.mShowUserId))
3630                                         || hasUserRestriction(
3631                                         UserManager.DISALLOW_ASSIST_CONTENT,
3632                                         windowState.mShowUserId)), true /* traverseTopToBottom */);
3633             } finally {
3634                 Binder.restoreCallingIdentity(callingIdentity);
3635             }
3636         }
3637         return DevicePolicyCache.getInstance().isScreenCaptureAllowed(userId)
3638                 && !hasRestrictedWindow;
3639     }
3640 
onLocalVoiceInteractionStartedLocked(IBinder activity, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor)3641     private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3642             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3643         ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3644         if (activityToCallback == null) return;
3645         activityToCallback.setVoiceSessionLocked(voiceSession);
3646 
3647         // Inform the activity
3648         try {
3649             activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3650                     voiceInteractor);
3651             final long token = Binder.clearCallingIdentity();
3652             try {
3653                 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
3654             } finally {
3655                 Binder.restoreCallingIdentity(token);
3656             }
3657             // TODO: VI Should we cache the activity so that it's easier to find later
3658             // rather than scan through all the root tasks and activities?
3659         } catch (RemoteException re) {
3660             activityToCallback.clearVoiceSessionLocked();
3661             // TODO: VI Should this terminate the voice session?
3662         }
3663     }
3664 
startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid)3665     private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3666         Slog.d(TAG, "<<<  startRunningVoiceLocked()");
3667         mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3668         if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3669             boolean wasRunningVoice = mRunningVoice != null;
3670             mRunningVoice = session;
3671             if (!wasRunningVoice) {
3672                 mVoiceWakeLock.acquire();
3673                 updateSleepIfNeededLocked();
3674             }
3675         }
3676     }
3677 
finishRunningVoiceLocked()3678     void finishRunningVoiceLocked() {
3679         if (mRunningVoice != null) {
3680             mRunningVoice = null;
3681             mVoiceWakeLock.release();
3682             updateSleepIfNeededLocked();
3683         }
3684     }
3685 
3686     @Override
setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake)3687     public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3688         synchronized (mGlobalLock) {
3689             if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3690                 if (keepAwake) {
3691                     mVoiceWakeLock.acquire();
3692                 } else {
3693                     mVoiceWakeLock.release();
3694                 }
3695             }
3696         }
3697     }
3698 
3699     @Override
keyguardGoingAway(int flags)3700     public void keyguardGoingAway(int flags) {
3701         mAmInternal.enforceCallingPermission(CONTROL_KEYGUARD, "unlock keyguard");
3702         enforceNotIsolatedCaller("keyguardGoingAway");
3703         final long token = Binder.clearCallingIdentity();
3704         try {
3705             synchronized (mGlobalLock) {
3706                 boolean isPowerModePreApplied = false;
3707                 if (mPowerModeReasons == 0) {
3708                     startPowerMode(POWER_MODE_REASON_START_ACTIVITY);
3709                     isPowerModePreApplied = true;
3710                 }
3711                 // Keyguard asked us to clear the home task snapshot before going away, so do that.
3712                 if ((flags & KEYGUARD_GOING_AWAY_FLAG_TO_LAUNCHER_CLEAR_SNAPSHOT) != 0) {
3713                     mActivityClientController.invalidateHomeTaskSnapshot(null /* token */);
3714                 } else if (mKeyguardShown) {
3715                     // Only set if it is not unlocking to launcher which may also animate.
3716                     mDemoteTopAppReasons |= DEMOTE_TOP_REASON_DURING_UNLOCKING;
3717                 }
3718 
3719                 boolean foundResumed = false;
3720                 for (int i = mRootWindowContainer.getChildCount() - 1; i >= 0; i--) {
3721                     final DisplayContent dc = mRootWindowContainer.getChildAt(i);
3722                     final boolean wasNoResumed = dc.mFocusedApp == null
3723                             || !dc.mFocusedApp.isState(RESUMED);
3724                     mKeyguardController.keyguardGoingAway(dc.mDisplayId, flags);
3725                     if (wasNoResumed && dc.mFocusedApp != null && dc.mFocusedApp.isState(RESUMED)) {
3726                         foundResumed = true;
3727                     }
3728                 }
3729                 if (isPowerModePreApplied && !foundResumed) {
3730                     endPowerMode(POWER_MODE_REASON_START_ACTIVITY);
3731                 }
3732 
3733                 mH.post(() -> {
3734                     for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3735                         mScreenObservers.get(i).onKeyguardGoingAway();
3736                     }
3737                 });
3738             }
3739         } finally {
3740             Binder.restoreCallingIdentity(token);
3741         }
3742     }
3743 
3744     @Override
suppressResizeConfigChanges(boolean suppress)3745     public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
3746         mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_TASKS,
3747                 "suppressResizeConfigChanges()");
3748         synchronized (mGlobalLock) {
3749             mSuppressResizeConfigChanges = suppress;
3750         }
3751     }
3752 
3753     /**
3754      * A splash screen view has copied, pass it to an activity.
3755      *
3756      * @param taskId Id of task to handle the material to reconstruct the view.
3757      * @param parcelable Used to reconstruct the view, null means the surface is un-copyable.
3758      * @hide
3759      */
3760     @Override
onSplashScreenViewCopyFinished(int taskId, @Nullable SplashScreenViewParcelable parcelable)3761     public void onSplashScreenViewCopyFinished(int taskId,
3762             @Nullable SplashScreenViewParcelable parcelable)
3763                 throws RemoteException {
3764         mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_TASKS,
3765                 "copySplashScreenViewFinish()");
3766         synchronized (mGlobalLock) {
3767             final Task task = mRootWindowContainer.anyTaskForId(taskId,
3768                     MATCH_ATTACHED_TASK_ONLY);
3769             if (task != null) {
3770                 final ActivityRecord r = task.getTopWaitSplashScreenActivity();
3771                 if (r != null) {
3772                     r.onCopySplashScreenFinish(parcelable);
3773                 }
3774             }
3775         }
3776     }
3777 
3778     /**
3779      * Prepare to enter PiP mode after {@link TransitionController#requestStartDisplayTransition}.
3780      *
3781      * @param r activity auto entering pip
3782      * @return true if the activity is about to auto-enter pip or is already in pip mode.
3783      */
prepareAutoEnterPictureAndPictureMode(ActivityRecord r)3784     boolean prepareAutoEnterPictureAndPictureMode(ActivityRecord r) {
3785         // If the activity is already in picture in picture mode, then just return early
3786         if (r.inPinnedWindowingMode()) {
3787             return true;
3788         }
3789 
3790         if (r.canAutoEnterPip() && getTransitionController().getCollectingTransition() != null) {
3791             // This will be used later to construct TransitionRequestInfo for Shell to resolve.
3792             // It will also be passed into a direct moveActivityToPinnedRootTask() call via
3793             // startTransition()
3794             getTransitionController().getCollectingTransition().setPipActivity(r);
3795             return true;
3796         }
3797         return false;
3798     }
3799 
enterPictureInPictureMode(@onNull ActivityRecord r, @NonNull PictureInPictureParams params, boolean fromClient)3800     boolean enterPictureInPictureMode(@NonNull ActivityRecord r,
3801             @NonNull PictureInPictureParams params, boolean fromClient) {
3802         return enterPictureInPictureMode(r, params, fromClient, false /* isAutoEnter */);
3803     }
3804 
3805     /**
3806      * Puts the given activity in picture in picture mode if possible.
3807      *
3808      * @param fromClient true if this comes from a client call (eg. Activity.enterPip).
3809      * @param isAutoEnter true if this comes from an automatic pip-enter.
3810      * @return true if the activity is now in picture-in-picture mode, or false if it could not
3811      * enter picture-in-picture mode.
3812      */
enterPictureInPictureMode(@onNull ActivityRecord r, @NonNull PictureInPictureParams params, boolean fromClient, boolean isAutoEnter)3813     boolean enterPictureInPictureMode(@NonNull ActivityRecord r,
3814             @NonNull PictureInPictureParams params, boolean fromClient, boolean isAutoEnter) {
3815         // If the activity is already in picture in picture mode, then just return early
3816         if (r.inPinnedWindowingMode()) {
3817             return true;
3818         }
3819 
3820         // Activity supports picture-in-picture, now check that we can enter PiP at this
3821         // point, if it is
3822         if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3823                 false /* beforeStopping */)) {
3824             return false;
3825         }
3826 
3827         // If the app is using auto-enter, and it explicitly requests entering PiP while pausing,
3828         // return false immediately since auto-enter should take in place instead.
3829         if (fromClient && r.isState(PAUSING) && params.isAutoEnterEnabled()) {
3830             Slog.w(TAG, "Skip client enterPictureInPictureMode request while pausing,"
3831                     + " auto-enter-pip is enabled");
3832             return false;
3833         }
3834 
3835         if (isPip2ExperimentEnabled()) {
3836             // If PiP2 flag is on and request to enter PiP comes in,
3837             // we request a direct transition TRANSIT_PIP from Shell to get the right entry bounds.
3838             // So PiP activity isn't moved to a pinned task until after
3839             // Shell calls back into Core with the entry bounds to be applied with startWCT.
3840             final Transition enterPipTransition = new Transition(TRANSIT_PIP,
3841                     0 /* flags */, getTransitionController(), mWindowManager.mSyncEngine);
3842             r.setPictureInPictureParams(params);
3843             enterPipTransition.setPipActivity(r);
3844             r.mAutoEnteringPip = isAutoEnter;
3845 
3846             if (r.getTaskFragment() != null && r.getTaskFragment().isEmbeddedWithBoundsOverride()
3847                     && enterPipTransition != null) {
3848                 enterPipTransition.addFlag(FLAG_IN_TASK_WITH_EMBEDDED_ACTIVITY);
3849             }
3850 
3851             getTransitionController().startCollectOrQueue(enterPipTransition, (deferred) -> {
3852                 getTransitionController().requestStartTransition(enterPipTransition,
3853                         r.getTask(), null /* remoteTransition */, null /* displayChange */);
3854             });
3855             return true;
3856         }
3857 
3858         // If the app is using legacy-entry (not auto-enter), then we will get a client-request
3859         // that was actually a server-request (via pause(userLeaving=true)). This happens when
3860         // the app is PAUSING, so detect that case here.
3861         boolean originallyFromClient = fromClient
3862                 && (!r.isState(PAUSING) || params.isAutoEnterEnabled());
3863 
3864         // Create a transition only for this pip entry if it is coming from the app without the
3865         // system requesting that the app enter-pip. If the system requested it, that means it
3866         // should be part of that transition if possible.
3867         final Transition transition =
3868                 (getTransitionController().isShellTransitionsEnabled() && originallyFromClient)
3869                 ? new Transition(TRANSIT_PIP, 0 /* flags */,
3870                         getTransitionController(), mWindowManager.mSyncEngine)
3871                 : null;
3872 
3873         if (r.getTaskFragment() != null && r.getTaskFragment().isEmbeddedWithBoundsOverride()
3874                 && transition != null) {
3875             transition.addFlag(FLAG_IN_TASK_WITH_EMBEDDED_ACTIVITY);
3876         }
3877 
3878         final Runnable enterPipRunnable = () -> {
3879             synchronized (mGlobalLock) {
3880                 if (r.getParent() == null) {
3881                     Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
3882                     if (transition != null) {
3883                         transition.abort();
3884                     }
3885                     return;
3886                 }
3887                 EventLogTags.writeWmEnterPip(r.mUserId, System.identityHashCode(r),
3888                         r.shortComponentName, Boolean.toString(isAutoEnter));
3889                 r.setPictureInPictureParams(params);
3890                 r.mAutoEnteringPip = isAutoEnter;
3891 
3892                 if (transition != null) {
3893                     mRootWindowContainer.moveActivityToPinnedRootTaskAndRequestStart(r,
3894                             "enterPictureInPictureMode");
3895                 } else if (getTransitionController().isCollecting()
3896                         || !getTransitionController().isShellTransitionsEnabled()) {
3897                     mRootWindowContainer.moveActivityToPinnedRootTask(r,
3898                             null /* launchIntoPipHostActivity */, "enterPictureInPictureMode",
3899                             null /* bounds */);
3900                 } else {
3901                     // Need to make a transition just for this. This shouldn't really happen
3902                     // though because if transition == null, we should be part of an existing one.
3903                     getTransitionController().createTransition(TRANSIT_PIP);
3904                     mRootWindowContainer.moveActivityToPinnedRootTaskAndRequestStart(r,
3905                             "enterPictureInPictureMode");
3906                 }
3907                 // Continue the pausing process after entering pip.
3908                 if (r.isState(PAUSING) && r.mPauseSchedulePendingForPip) {
3909                     r.getTask().schedulePauseActivity(r, false /* userLeaving */,
3910                             false /* pauseImmediately */, true /* autoEnteringPip */,
3911                             "auto-pip");
3912                 }
3913                 r.mAutoEnteringPip = false;
3914             }
3915         };
3916 
3917         if (r.isKeyguardLocked()) {
3918             // If the keyguard is showing or occluded, then try and dismiss it before
3919             // entering picture-in-picture (this will prompt the user to authenticate if the
3920             // device is currently locked).
3921             mActivityClientController.dismissKeyguard(r.token, new KeyguardDismissCallback() {
3922                 @Override
3923                 public void onDismissSucceeded() {
3924                     if (transition == null) {
3925                         mH.post(enterPipRunnable);
3926                         return;
3927                     }
3928                     getTransitionController().startCollectOrQueue(transition, (deferred) -> {
3929                         if (deferred) {
3930                             enterPipRunnable.run();
3931                         } else {
3932                             mH.post(enterPipRunnable);
3933                         }
3934                     });
3935                 }
3936             }, null /* message */);
3937         } else {
3938             // Enter picture in picture immediately otherwise
3939             if (transition != null) {
3940                 getTransitionController().startCollectOrQueue(transition,
3941                         (deferred) -> enterPipRunnable.run());
3942             } else {
3943                 enterPipRunnable.run();
3944             }
3945         }
3946         return true;
3947     }
3948 
3949     @Override
getWindowOrganizerController()3950     public IWindowOrganizerController getWindowOrganizerController() {
3951         return mWindowOrganizerController;
3952     }
3953 
3954     /**
3955      * Check that we have the features required for VR-related API calls, and throw an exception if
3956      * not.
3957      */
enforceSystemHasVrFeature()3958     public void enforceSystemHasVrFeature() {
3959         if (!mContext.getPackageManager().hasSystemFeature(
3960                 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3961             throw new UnsupportedOperationException("VR mode not supported on this device!");
3962         }
3963     }
3964 
3965     @Override
supportsLocalVoiceInteraction()3966     public boolean supportsLocalVoiceInteraction() {
3967         return LocalServices.getService(VoiceInteractionManagerInternal.class)
3968                 .supportsLocalVoiceInteraction();
3969     }
3970 
3971     @Override
requestOpenInBrowserEducation(IBinder appToken)3972     public void requestOpenInBrowserEducation(IBinder appToken) {
3973         synchronized (mGlobalLock) {
3974             final ActivityRecord r = ActivityRecord.isInRootTaskLocked(appToken);
3975             if (r != null) {
3976                 r.requestOpenInBrowserEducation();
3977             }
3978         }
3979     }
3980 
3981     @Override
updateConfiguration(Configuration values)3982     public boolean updateConfiguration(Configuration values) {
3983         mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
3984 
3985         synchronized (mGlobalLock) {
3986             if (mWindowManager == null) {
3987                 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
3988                 return false;
3989             }
3990 
3991             if (values == null) {
3992                 // sentinel: fetch the current configuration from the window manager
3993                 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
3994             }
3995 
3996             mH.sendMessage(PooledLambda.obtainMessage(
3997                     ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
3998                     DEFAULT_DISPLAY));
3999 
4000             final long origId = Binder.clearCallingIdentity();
4001             try {
4002                 if (values != null) {
4003                     Settings.System.clearConfiguration(values);
4004                 }
4005                 updateConfigurationLocked(values, null, false, false /* persistent */,
4006                         UserHandle.USER_NULL, false /* deferResume */);
4007                 return mTmpUpdateConfigurationResult.changes != 0;
4008             } finally {
4009                 Binder.restoreCallingIdentity(origId);
4010             }
4011         }
4012     }
4013 
4014     @Override
cancelTaskWindowTransition(int taskId)4015     public void cancelTaskWindowTransition(int taskId) {
4016         enforceTaskPermission("cancelTaskWindowTransition()");
4017         final long ident = Binder.clearCallingIdentity();
4018         try {
4019             synchronized (mGlobalLock) {
4020                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
4021                         MATCH_ATTACHED_TASK_ONLY);
4022                 if (task == null) {
4023                     Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4024                     return;
4025                 }
4026                 task.cancelTaskWindowTransition();
4027             }
4028         } finally {
4029             Binder.restoreCallingIdentity(ident);
4030         }
4031     }
4032 
getTaskSnapshotInner(int taskId, boolean isLowResolution, @TaskSnapshot.ReferenceFlags int usage)4033     private TaskSnapshot getTaskSnapshotInner(int taskId, boolean isLowResolution,
4034             @TaskSnapshot.ReferenceFlags int usage) {
4035         final Task task;
4036         synchronized (mGlobalLock) {
4037             task = mRootWindowContainer.anyTaskForId(taskId, MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
4038             if (task == null) {
4039                 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4040                 return null;
4041             }
4042             // Try to load snapshot from cache first, and add reference if the snapshot is in cache.
4043             final TaskSnapshot snapshot = mWindowManager.mTaskSnapshotController.getSnapshot(taskId,
4044                     isLowResolution, usage);
4045             if (snapshot != null) {
4046                 return snapshot;
4047             }
4048         }
4049         // Don't call this while holding the lock as this operation might hit the disk.
4050         return mWindowManager.mTaskSnapshotController.getSnapshotFromDisk(taskId,
4051                 task.mUserId,  isLowResolution, usage);
4052     }
4053 
4054     @Override
getTaskSnapshot(int taskId, boolean isLowResolution)4055     public TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
4056         mAmInternal.enforceCallingPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
4057         final long ident = Binder.clearCallingIdentity();
4058         try {
4059             final Task task;
4060             synchronized (mGlobalLock) {
4061                 task = mRootWindowContainer.anyTaskForId(taskId,
4062                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
4063                 if (task == null) {
4064                     Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4065                     return null;
4066                 }
4067                 final TaskSnapshot snapshot = mWindowManager.mTaskSnapshotController.getSnapshot(
4068                         taskId, isLowResolution, TaskSnapshot.REFERENCE_WRITE_TO_PARCEL);
4069                 if (snapshot != null) {
4070                     return snapshot;
4071                 }
4072             }
4073             // Don't call this while holding the lock as this operation might hit the disk.
4074             return mWindowManager.mTaskSnapshotController.getSnapshotFromDisk(taskId,
4075                     task.mUserId, isLowResolution, TaskSnapshot.REFERENCE_WRITE_TO_PARCEL);
4076         } finally {
4077             Binder.restoreCallingIdentity(ident);
4078         }
4079     }
4080 
4081     @Override
takeTaskSnapshot(int taskId, boolean updateCache)4082     public TaskSnapshot takeTaskSnapshot(int taskId, boolean updateCache) {
4083         mAmInternal.enforceCallingPermission(READ_FRAME_BUFFER, "takeTaskSnapshot()");
4084         final long ident = Binder.clearCallingIdentity();
4085         try {
4086             final Supplier<TaskSnapshot> supplier;
4087             synchronized (mGlobalLock) {
4088                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
4089                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
4090                 if (task == null || !task.isVisible()) {
4091                     Slog.w(TAG, "takeTaskSnapshot: taskId=" + taskId + " not found or not visible");
4092                     return null;
4093                 }
4094                 // Note that if updateCache is true, ActivityRecord#shouldUseAppThemeSnapshot will
4095                 // be used to decide whether the task is allowed to be captured because that may
4096                 // be retrieved by recents. While if updateCache is false, the real snapshot will
4097                 // always be taken and the snapshot won't be put into SnapshotPersister.
4098                 if (updateCache) {
4099                     supplier = mWindowManager.mTaskSnapshotController
4100                             .getRecordSnapshotSupplier(task);
4101                 } else {
4102                     return mWindowManager.mTaskSnapshotController.snapshot(task);
4103                 }
4104             }
4105             return supplier != null ? supplier.get() : null;
4106         } finally {
4107             Binder.restoreCallingIdentity(ident);
4108         }
4109     }
4110 
4111     /** Return the user id of the last resumed activity. */
4112     @Override
4113     public @UserIdInt
getLastResumedActivityUserId()4114     int getLastResumedActivityUserId() {
4115         mAmInternal.enforceCallingPermission(
4116                 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4117         synchronized (mGlobalLock) {
4118             if (mLastResumedActivity == null) {
4119                 return getCurrentUserId();
4120             }
4121             return mLastResumedActivity.mUserId;
4122         }
4123     }
4124 
4125     @Override
updateLockTaskFeatures(int userId, int flags)4126     public void updateLockTaskFeatures(int userId, int flags) {
4127         final int callingUid = Binder.getCallingUid();
4128         if (callingUid != 0 && callingUid != SYSTEM_UID) {
4129             mAmInternal.enforceCallingPermission(
4130                     android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
4131                     "updateLockTaskFeatures()");
4132         }
4133         synchronized (mGlobalLock) {
4134             ProtoLog.w(WM_DEBUG_LOCKTASK, "Allowing features %d:0x%s",
4135                     userId, Integer.toHexString(flags));
4136             getLockTaskController().updateLockTaskFeatures(userId, flags);
4137         }
4138     }
4139 
4140     @Override
registerRemoteAnimationForNextActivityStart(String packageName, RemoteAnimationAdapter adapter, IBinder launchCookie)4141     public void registerRemoteAnimationForNextActivityStart(String packageName,
4142             RemoteAnimationAdapter adapter, IBinder launchCookie) {
4143         mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4144                 "registerRemoteAnimationForNextActivityStart");
4145         adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
4146         synchronized (mGlobalLock) {
4147             final long origId = Binder.clearCallingIdentity();
4148             try {
4149                 getActivityStartController().registerRemoteAnimationForNextActivityStart(
4150                         packageName, adapter, launchCookie);
4151             } finally {
4152                 Binder.restoreCallingIdentity(origId);
4153             }
4154         }
4155     }
4156 
4157     @Override
registerRemoteAnimationsForDisplay(int displayId, RemoteAnimationDefinition definition)4158     public void registerRemoteAnimationsForDisplay(int displayId,
4159             RemoteAnimationDefinition definition) {
4160         // TODO(b/365884835): Remove callers.
4161     }
4162 
4163     /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4164     @Override
alwaysShowUnsupportedCompileSdkWarning(ComponentName activity)4165     public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4166         synchronized (mGlobalLock) {
4167             final long origId = Binder.clearCallingIdentity();
4168             try {
4169                 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
4170             } finally {
4171                 Binder.restoreCallingIdentity(origId);
4172             }
4173         }
4174     }
4175 
4176     @Override
setVrThread(int tid)4177     public void setVrThread(int tid) {
4178         enforceSystemHasVrFeature();
4179         synchronized (mGlobalLock) {
4180             final int pid = Binder.getCallingPid();
4181             final WindowProcessController wpc = mProcessMap.getProcess(pid);
4182             mVrController.setVrThreadLocked(tid, pid, wpc);
4183         }
4184     }
4185 
4186     @Override
setPersistentVrThread(int tid)4187     public void setPersistentVrThread(int tid) {
4188         if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
4189                 != PERMISSION_GRANTED) {
4190             final String msg = "Permission Denial: setPersistentVrThread() from pid="
4191                     + Binder.getCallingPid()
4192                     + ", uid=" + Binder.getCallingUid()
4193                     + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4194             Slog.w(TAG, msg);
4195             throw new SecurityException(msg);
4196         }
4197         enforceSystemHasVrFeature();
4198         synchronized (mGlobalLock) {
4199             final int pid = Binder.getCallingPid();
4200             final WindowProcessController proc = mProcessMap.getProcess(pid);
4201             mVrController.setPersistentVrThreadLocked(tid, pid, proc);
4202         }
4203     }
4204 
4205     @Override
stopAppSwitches()4206     public void stopAppSwitches() {
4207         mAmInternal.enforceCallingPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4208         synchronized (mGlobalLock) {
4209             mAppSwitchesState = APP_SWITCH_DISALLOW;
4210             mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
4211             mH.removeMessages(H.RESUME_FG_APP_SWITCH_MSG);
4212             mH.sendEmptyMessageDelayed(H.RESUME_FG_APP_SWITCH_MSG, RESUME_FG_APP_SWITCH_MS);
4213         }
4214     }
4215 
4216     @Override
resumeAppSwitches()4217     public void resumeAppSwitches() {
4218         mAmInternal.enforceCallingPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4219         synchronized (mGlobalLock) {
4220             mAppSwitchesState = APP_SWITCH_ALLOW;
4221             mH.removeMessages(H.RESUME_FG_APP_SWITCH_MSG);
4222         }
4223     }
4224 
getLastStopAppSwitchesTime()4225     long getLastStopAppSwitchesTime() {
4226         return mLastStopAppSwitchesTime;
4227     }
4228 
4229     /** @return whether the system should disable UI modes incompatible with VR mode. */
shouldDisableNonVrUiLocked()4230     boolean shouldDisableNonVrUiLocked() {
4231         return mVrController.shouldDisableNonVrUiLocked();
4232     }
4233 
applyUpdateVrModeLocked(ActivityRecord r)4234     void applyUpdateVrModeLocked(ActivityRecord r) {
4235         // VR apps are expected to run in a main display. If an app is turning on VR for
4236         // itself, but isn't on the main display, then move it there before enabling VR Mode.
4237         if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4238             Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4239                     + " to main display for VR");
4240             mRootWindowContainer.moveRootTaskToDisplay(
4241                     r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
4242         }
4243         mH.post(() -> {
4244             if (!mVrController.onVrModeChanged(r)) {
4245                 return;
4246             }
4247             synchronized (mGlobalLock) {
4248                 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4249                 mWindowManager.disableNonVrUi(disableNonVrUi);
4250                 if (disableNonVrUi) {
4251                     // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4252                     // then remove the root pinned task.
4253                     mRootWindowContainer.removeRootTasksInWindowingModes(WINDOWING_MODE_PINNED);
4254                 }
4255             }
4256         });
4257     }
4258 
4259     @Override
getPackageScreenCompatMode(String packageName)4260     public int getPackageScreenCompatMode(String packageName) {
4261         enforceNotIsolatedCaller("getPackageScreenCompatMode");
4262         synchronized (mGlobalLock) {
4263             return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4264         }
4265     }
4266 
4267     @Override
setPackageScreenCompatMode(String packageName, int mode)4268     public void setPackageScreenCompatMode(String packageName, int mode) {
4269         mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4270                 "setPackageScreenCompatMode");
4271         synchronized (mGlobalLock) {
4272             mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4273         }
4274     }
4275 
4276     @Override
getPackageAskScreenCompat(String packageName)4277     public boolean getPackageAskScreenCompat(String packageName) {
4278         enforceNotIsolatedCaller("getPackageAskScreenCompat");
4279         synchronized (mGlobalLock) {
4280             return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4281         }
4282     }
4283 
4284     @Override
setPackageAskScreenCompat(String packageName, boolean ask)4285     public void setPackageAskScreenCompat(String packageName, boolean ask) {
4286         mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4287                 "setPackageAskScreenCompat");
4288         synchronized (mGlobalLock) {
4289             mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4290         }
4291     }
4292 
relaunchReasonToString(int relaunchReason)4293     public static String relaunchReasonToString(int relaunchReason) {
4294         switch (relaunchReason) {
4295             case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4296                 return "window_resize";
4297             case RELAUNCH_REASON_FREE_RESIZE:
4298                 return "free_resize";
4299             default:
4300                 return null;
4301         }
4302     }
4303 
getTopDisplayFocusedRootTask()4304     Task getTopDisplayFocusedRootTask() {
4305         return mRootWindowContainer.getTopDisplayFocusedRootTask();
4306     }
4307 
4308     /** Pokes the task persister. */
notifyTaskPersisterLocked(Task task, boolean flush)4309     void notifyTaskPersisterLocked(Task task, boolean flush) {
4310         mRecentTasks.notifyTaskPersisterLocked(task, flush);
4311     }
4312 
4313     /**
4314      * Clears launch params for the given package.
4315      *
4316      * @param packageNames the names of the packages of which the launch params are to be cleared
4317      */
4318     @Override
clearLaunchParamsForPackages(List<String> packageNames)4319     public void clearLaunchParamsForPackages(List<String> packageNames) {
4320         enforceTaskPermission("clearLaunchParamsForPackages");
4321         synchronized (mGlobalLock) {
4322             for (int i = 0; i < packageNames.size(); ++i) {
4323                 mTaskSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4324             }
4325         }
4326     }
4327 
4328     @Override
onPictureInPictureUiStateChanged(PictureInPictureUiState pipState)4329     public void onPictureInPictureUiStateChanged(PictureInPictureUiState pipState) {
4330         enforceTaskPermission("onPictureInPictureUiStateChanged");
4331         synchronized (mGlobalLock) {
4332             // The PictureInPictureUiState is sent to current pip task if there is any
4333             // -or- the top standard task (state like entering PiP does not require a pinned task).
4334             final Task task;
4335             if (mRootWindowContainer.getDefaultTaskDisplayArea().hasPinnedTask()) {
4336                 task = mRootWindowContainer.getDefaultTaskDisplayArea().getRootPinnedTask();
4337             } else {
4338                 task = mRootWindowContainer.getDefaultTaskDisplayArea().getRootTask(
4339                         t -> t.isActivityTypeStandard());
4340             }
4341             final ActivityRecord topActivity = task != null
4342                     ? task.getTopMostActivity()
4343                     : null;
4344             if (topActivity != null && !topActivity.isState(FINISHING, DESTROYING, DESTROYED)) {
4345                 mWindowManager.mAtmService.mActivityClientController
4346                         .onPictureInPictureUiStateChanged(topActivity, pipState);
4347             }
4348         }
4349     }
4350 
4351     @Override
detachNavigationBarFromApp(@onNull IBinder transition)4352     public void detachNavigationBarFromApp(@NonNull IBinder transition) {
4353         mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4354                 "detachNavigationBarFromApp");
4355         final long token = Binder.clearCallingIdentity();
4356         try {
4357             synchronized (mGlobalLock) {
4358                 getTransitionController().legacyDetachNavigationBarFromApp(transition);
4359             }
4360         } finally {
4361             Binder.restoreCallingIdentity(token);
4362         }
4363     }
4364 
dumpLastANRLocked(PrintWriter pw)4365     void dumpLastANRLocked(PrintWriter pw) {
4366         pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4367         if (mLastANRState == null) {
4368             pw.println("  <no ANR has occurred since boot>");
4369         } else {
4370             pw.println(mLastANRState);
4371         }
4372     }
4373 
dumpLastANRTracesLocked(PrintWriter pw)4374     void dumpLastANRTracesLocked(PrintWriter pw) {
4375         pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4376 
4377         final File[] files = new File(ANR_TRACE_DIR).listFiles();
4378         if (ArrayUtils.isEmpty(files)) {
4379             pw.println("  <no ANR has occurred since boot>");
4380             return;
4381         }
4382         // Find the latest file.
4383         File latest = null;
4384         for (File f : files) {
4385             if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4386                 latest = f;
4387             }
4388         }
4389         pw.print("File: ");
4390         pw.print(latest.getName());
4391         pw.println();
4392         try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4393             String line;
4394             while ((line = in.readLine()) != null) {
4395                 pw.println(line);
4396             }
4397         } catch (IOException e) {
4398             pw.print("Unable to read: ");
4399             pw.print(e);
4400             pw.println();
4401         }
4402     }
4403 
dumpTopResumedActivityLocked(PrintWriter pw)4404     void dumpTopResumedActivityLocked(PrintWriter pw) {
4405         pw.println("ACTIVITY MANAGER TOP-RESUMED (dumpsys activity top-resumed)");
4406         ActivityRecord topRecord = mRootWindowContainer.getTopResumedActivity();
4407         if (topRecord != null) {
4408             topRecord.dump(pw, "", true);
4409         }
4410     }
4411 
dumpVisibleActivitiesLocked(PrintWriter pw, int displayIdFilter)4412     void dumpVisibleActivitiesLocked(PrintWriter pw, int displayIdFilter) {
4413         pw.println("ACTIVITY MANAGER VISIBLE ACTIVITIES (dumpsys activity visible)");
4414         ArrayList<ActivityRecord> activities =
4415                 mRootWindowContainer.getDumpActivities("all", /* dumpVisibleRootTasksOnly */ true,
4416                         /* dumpFocusedRootTaskOnly */ false, UserHandle.USER_ALL);
4417         boolean needSeparator = false;
4418         boolean printedAnything = false;
4419         for (int i = activities.size() - 1; i >= 0; i--) {
4420             ActivityRecord activity = activities.get(i);
4421             if (!activity.isVisible() || (displayIdFilter != INVALID_DISPLAY
4422                     && activity.getDisplayId() != displayIdFilter)) {
4423                 continue;
4424             }
4425             if (needSeparator) {
4426                 pw.println();
4427             }
4428             printedAnything = true;
4429             activity.dump(pw, "", true);
4430             needSeparator = true;
4431         }
4432         if (!printedAnything) {
4433             pw.println("(nothing)");
4434         }
4435     }
4436 
dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter)4437     void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4438             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage,
4439             int displayIdFilter) {
4440         dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage, displayIdFilter,
4441                 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4442     }
4443 
dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter, String header)4444     void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4445             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter,
4446             String header) {
4447         pw.println(header);
4448 
4449         boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
4450                 dumpPackage, displayIdFilter);
4451         boolean needSep = printedAnything;
4452 
4453         boolean printed = ActivityTaskSupervisor.printThisActivity(pw,
4454                 mRootWindowContainer.getTopResumedActivity(), dumpPackage, displayIdFilter, needSep,
4455                 "  ResumedActivity: ", /* header= */ null);
4456         if (printed) {
4457             printedAnything = true;
4458             needSep = false;
4459         }
4460 
4461         if (dumpPackage == null) {
4462             if (needSep) {
4463                 pw.println();
4464             }
4465             printedAnything = true;
4466             mTaskSupervisor.dump(pw, "  ");
4467             mTaskOrganizerController.dump(pw, "  ");
4468             mVisibleActivityProcessTracker.dump(pw, "  ");
4469             mActiveUids.dump(pw, "  ");
4470             pw.println("  SleepTokens=" + mRootWindowContainer.mSleepTokens);
4471             if (mDemoteTopAppReasons != 0) {
4472                 pw.println("  mDemoteTopAppReasons=" + mDemoteTopAppReasons);
4473             }
4474             if (!mStartingProcessActivities.isEmpty()) {
4475                 pw.println("  mStartingProcessActivities=" + mStartingProcessActivities);
4476             }
4477         }
4478 
4479         if (!printedAnything) {
4480             pw.println("  (nothing)");
4481         }
4482     }
4483 
dumpActivityContainersLocked(PrintWriter pw)4484     void dumpActivityContainersLocked(PrintWriter pw) {
4485         pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
4486         mRootWindowContainer.dumpChildrenNames(pw, "");
4487         pw.println(" ");
4488     }
4489 
dumpActivityStarterLocked(PrintWriter pw, String dumpPackage)4490     void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4491         pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4492         getActivityStartController().dump(pw, "", dumpPackage);
4493     }
4494 
4495     /** Dumps installed packages having app-specific config. */
dumpInstalledPackagesConfig(PrintWriter pw)4496     void dumpInstalledPackagesConfig(PrintWriter pw) {
4497         mPackageConfigPersister.dump(pw, getCurrentUserId());
4498     }
4499 
4500     /**
4501      * There are three things that cmd can be:
4502      * - a flattened component name that matches an existing activity
4503      * - the cmd arg isn't the flattened component name of an existing activity:
4504      * dump all activity whose component contains the cmd as a substring
4505      * - A hex number of the ActivityRecord object instance.
4506      * <p>
4507      * The caller should not hold lock when calling this method because it will wait for the
4508      * activities to complete the dump.
4509      *
4510      * @param dumpVisibleRootTasksOnly dump activity with {@param name} only if in a visible root
4511      *                                 task
4512      * @param dumpFocusedRootTaskOnly  dump activity with {@param name} only if in the focused
4513      *                                 root task
4514      */
dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly, boolean dumpFocusedRootTaskOnly, int displayIdFilter, @UserIdInt int userId, long timeout)4515     protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4516             int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly,
4517             boolean dumpFocusedRootTaskOnly, int displayIdFilter, @UserIdInt int userId,
4518             long timeout) {
4519         ArrayList<ActivityRecord> activities;
4520 
4521         synchronized (mGlobalLock) {
4522             activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleRootTasksOnly,
4523                     dumpFocusedRootTaskOnly, userId);
4524         }
4525 
4526         if (activities.size() <= 0) {
4527             return false;
4528         }
4529 
4530         String[] newArgs = new String[args.length - opti];
4531         System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4532 
4533         Task lastTask = null;
4534         boolean needSep = false;
4535         boolean printedAnything = false;
4536         for (int i = activities.size() - 1; i >= 0; i--) {
4537             ActivityRecord r = activities.get(i);
4538             if (needSep) {
4539                 pw.println();
4540             }
4541             needSep = true;
4542             synchronized (mGlobalLock) {
4543                 Task task = r.getTask();
4544                 int displayId = task.getDisplayId();
4545                 if (displayIdFilter != INVALID_DISPLAY && displayId != displayIdFilter) {
4546                     continue;
4547                 }
4548                 if (lastTask != task) {
4549                     printedAnything = true;
4550                     lastTask = task;
4551                     pw.print("TASK ");
4552                     pw.print(lastTask.affinity);
4553                     pw.print(" id=");
4554                     pw.print(lastTask.mTaskId);
4555                     pw.print(" userId=");
4556                     pw.print(lastTask.mUserId);
4557                     printDisplayInfoAndNewLine(pw, r);
4558                     if (dumpAll) {
4559                         lastTask.dump(pw, "  ");
4560                     }
4561                 }
4562             }
4563             dumpActivity("  ", fd, pw, activities.get(i), newArgs, dumpAll, timeout);
4564         }
4565         if (!printedAnything) {
4566             // Typically happpens when no task matches displayIdFilter
4567             pw.println("(nothing)");
4568         }
4569         return true;
4570     }
4571 
4572     /**
4573      * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4574      * there is a thread associated with the activity.
4575      */
dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw, ActivityRecord r, String[] args, boolean dumpAll, long timeout)4576     private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4577             ActivityRecord r, String[] args, boolean dumpAll, long timeout) {
4578         String innerPrefix = prefix + "  ";
4579         IApplicationThread appThread = null;
4580         synchronized (mGlobalLock) {
4581             pw.print(prefix);
4582             pw.print("ACTIVITY ");
4583             pw.print(r.shortComponentName);
4584             pw.print(" ");
4585             pw.print(Integer.toHexString(System.identityHashCode(r)));
4586             pw.print(" pid=");
4587             if (r.hasProcess()) {
4588                 pw.print(r.app.getPid());
4589                 appThread = r.app.getThread();
4590             } else {
4591                 pw.print("(not running)");
4592             }
4593             pw.print(" userId=");
4594             pw.print(r.mUserId);
4595             pw.print(" uid=");
4596             pw.print(r.getUid());
4597             printDisplayInfoAndNewLine(pw, r);
4598             if (dumpAll) {
4599                 r.dump(pw, innerPrefix, /* dumpAll= */ true);
4600             }
4601         }
4602         if (appThread != null) {
4603             // flush anything that is already in the PrintWriter since the thread is going
4604             // to write to the file descriptor directly
4605             pw.flush();
4606             try (TransferPipe tp = new TransferPipe()) {
4607                 appThread.dumpActivity(tp.getWriteFd(), r.token, innerPrefix, args);
4608                 tp.go(fd, timeout);
4609             } catch (IOException e) {
4610                 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4611             } catch (RemoteException e) {
4612                 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4613             }
4614         }
4615     }
4616 
printDisplayInfoAndNewLine(PrintWriter pw, ActivityRecord r)4617     private void printDisplayInfoAndNewLine(PrintWriter pw, ActivityRecord r) {
4618         pw.print(" displayId=");
4619         DisplayContent displayContent = r.getDisplayContent();
4620         if (displayContent == null) {
4621             pw.println("N/A");
4622             return;
4623         }
4624         Display display = displayContent.getDisplay();
4625         pw.print(display.getDisplayId());
4626         pw.print("(type=");
4627         pw.print(Display.typeToString(display.getType()));
4628         pw.println(")");
4629     }
4630 
writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness, boolean testPssMode)4631     private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4632             boolean testPssMode) {
4633         final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4634         proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4635                 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
4636         final int tokenSize = mRootWindowContainer.mSleepTokens.size();
4637         for (int i = 0; i < tokenSize; i++) {
4638             final RootWindowContainer.SleepToken st =
4639                     mRootWindowContainer.mSleepTokens.valueAt(i);
4640             proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4641                     st.toString());
4642         }
4643         proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4644         proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4645                 mShuttingDown);
4646         proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4647                 testPssMode);
4648         proto.end(sleepToken);
4649     }
4650 
getCurrentUserId()4651     int getCurrentUserId() {
4652         return mAmInternal.getCurrentUserId();
4653     }
4654 
enforceNotIsolatedCaller(String caller)4655     static void enforceNotIsolatedCaller(String caller) {
4656         if (UserHandle.isIsolated(Binder.getCallingUid())) {
4657             throw new SecurityException("Isolated process not allowed to call " + caller);
4658         }
4659     }
4660 
getConfiguration()4661     public Configuration getConfiguration() {
4662         Configuration ci;
4663         synchronized (mGlobalLock) {
4664             ci = new Configuration(getGlobalConfigurationForCallingPid());
4665             ci.userSetLocale = false;
4666         }
4667         return ci;
4668     }
4669 
4670     /**
4671      * Current global configuration information. Contains general settings for the entire system,
4672      * also corresponds to the merged configuration of the default display.
4673      */
getGlobalConfiguration()4674     Configuration getGlobalConfiguration() {
4675         // Return default configuration before mRootWindowContainer initialized, which happens
4676         // while initializing process record for system, see {@link
4677         // ActivityManagerService#setSystemProcess}.
4678         return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
4679                 : new Configuration();
4680     }
4681 
updateConfigurationLocked(Configuration values, ActivityRecord starting, boolean initLocale)4682     boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4683             boolean initLocale) {
4684         return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4685     }
4686 
updateConfigurationLocked(Configuration values, ActivityRecord starting, boolean initLocale, boolean deferResume)4687     boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4688             boolean initLocale, boolean deferResume) {
4689         // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4690         return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4691                 UserHandle.USER_NULL, deferResume);
4692     }
4693 
updatePersistentConfiguration(Configuration values, @UserIdInt int userId)4694     public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
4695         final long origId = Binder.clearCallingIdentity();
4696         try {
4697             synchronized (mGlobalLock) {
4698                 // Window configuration is unrelated to persistent configuration (e.g. font scale,
4699                 // locale). Unset it to avoid affecting the current display configuration.
4700                 values.windowConfiguration.setToDefaults();
4701                 updateConfigurationLocked(values, null, false, true, userId,
4702                         false /* deferResume */);
4703             }
4704         } finally {
4705             Binder.restoreCallingIdentity(origId);
4706         }
4707     }
4708 
4709     /**
4710      * Do either or both things: (1) change the current configuration, and (2)
4711      * make sure the given activity is running with the (now) current
4712      * configuration.  Returns true if the activity has been left running, or
4713      * false if <var>starting</var> is being destroyed to match the new
4714      * configuration.
4715      *
4716      * @param userId is only used when persistent parameter is set to true to persist configuration
4717      *               for that particular user
4718      */
updateConfigurationLocked(Configuration values, ActivityRecord starting, boolean initLocale, boolean persistent, int userId, boolean deferResume)4719     boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4720             boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4721         int changes = 0;
4722         boolean kept = true;
4723 
4724         deferWindowLayout();
4725         try {
4726             if (values != null) {
4727                 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId);
4728                 mTmpUpdateConfigurationResult.changes = changes;
4729             }
4730 
4731             if (!deferResume) {
4732                 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4733             }
4734         } finally {
4735             continueWindowLayout();
4736         }
4737         mTmpUpdateConfigurationResult.activityRelaunched = !kept;
4738         return kept;
4739     }
4740 
4741     /**
4742      * Updates default (global) configuration and notifies listeners about changes.
4743      *
4744      * @param values The new configuration. It must always be a new instance from the caller, and
4745      *               it won't be modified after calling this method.
4746      */
updateGlobalConfigurationLocked(@onNull Configuration values, boolean initLocale, boolean persistent, int userId)4747     int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4748             boolean persistent, int userId) {
4749 
4750         mTempConfig.setTo(getGlobalConfiguration());
4751         final int changes = mTempConfig.updateFrom(values);
4752         if (changes == 0) {
4753             return 0;
4754         }
4755 
4756         Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "updateGlobalConfiguration");
4757         ProtoLog.i(WM_DEBUG_CONFIGURATION, "Updating global configuration "
4758                 + "to: %s", values);
4759         writeConfigurationChanged(changes);
4760 
4761         // Note: certain tests currently run as platform_app which is not allowed
4762         // to set debug system properties. To ensure that system properties are set
4763         // only when allowed, we check the current UID.
4764         if (Process.myUid() == Process.SYSTEM_UID) {
4765             if (values.mcc != 0) {
4766                 SystemProperties.set("debug.tracing.mcc", Integer.toString(values.mcc));
4767             }
4768             if (values.mnc != 0) {
4769                 SystemProperties.set("debug.tracing.mnc", Integer.toString(values.mnc));
4770             }
4771         }
4772 
4773         if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4774             final LocaleList locales = values.getLocales();
4775             int bestLocaleIndex = 0;
4776             if (locales.size() > 1) {
4777                 if (mSupportedSystemLocales == null) {
4778                     mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4779                 }
4780                 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4781             }
4782             SystemProperties.set("persist.sys.locale",
4783                     locales.get(bestLocaleIndex).toLanguageTag());
4784             LocaleList.setDefault(locales, bestLocaleIndex);
4785         }
4786 
4787         mTempConfig.seq = increaseConfigurationSeqLocked();
4788 
4789         Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4790         // TODO(multi-display): Update UsageEvents#Event to include displayId.
4791         mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
4792 
4793         // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
4794         updateShouldShowDialogsLocked(mTempConfig);
4795 
4796         AttributeCache ac = AttributeCache.instance();
4797         if (ac != null) {
4798             ac.updateConfiguration(mTempConfig);
4799         }
4800 
4801         // Make sure all resources in our process are updated right now, so that anyone who is going
4802         // to retrieve resource values after we return will be sure to get the new ones. This is
4803         // especially important during boot, where the first config change needs to guarantee all
4804         // resources have that config before following boot code is executed.
4805         mSystemThread.applyConfigurationToResources(mTempConfig);
4806 
4807         SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
4808         for (int i = pidMap.size() - 1; i >= 0; i--) {
4809             final int pid = pidMap.keyAt(i);
4810             final WindowProcessController app = pidMap.get(pid);
4811             ProtoLog.v(WM_DEBUG_CONFIGURATION, "Update process config of %s to new "
4812                     + "config %s", app.mName, mTempConfig);
4813             app.onConfigurationChanged(mTempConfig);
4814         }
4815 
4816         final Configuration configurationForSettings =
4817                 persistent && Settings.System.hasInterestingConfigurationChanges(changes)
4818                         ? new Configuration(mTempConfig) : null;
4819         mH.post(() -> {
4820             FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
4821                     values.colorMode, values.densityDpi, values.fontScale,
4822                     values.hardKeyboardHidden, values.keyboard, values.keyboardHidden,
4823                     values.mcc, values.mnc, values.navigation, values.navigationHidden,
4824                     values.orientation, values.screenHeightDp, values.screenLayout,
4825                     values.screenWidthDp, values.smallestScreenWidthDp, values.touchscreen,
4826                     values.uiMode);
4827             if ((changes & ActivityInfo.CONFIG_ORIENTATION) != 0) {
4828                 FrameworkStatsLog.write(FrameworkStatsLog.DEVICE_ORIENTATION_CHANGED,
4829                         values.orientation);
4830             }
4831             if (configurationForSettings != null) {
4832                 Settings.System.putConfigurationForUser(mContext.getContentResolver(),
4833                         configurationForSettings, userId);
4834             }
4835             mAmInternal.broadcastGlobalConfigurationChanged(changes, initLocale);
4836         });
4837 
4838         Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "RootConfigChange");
4839         // Update stored global config and notify everyone about the change.
4840         mRootWindowContainer.onConfigurationChanged(mTempConfig);
4841         Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
4842 
4843         Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
4844         return changes;
4845     }
4846 
increaseAssetConfigurationSeq()4847     private int increaseAssetConfigurationSeq() {
4848         mGlobalAssetsSeq = Math.max(++mGlobalAssetsSeq, 1);
4849         return mGlobalAssetsSeq;
4850     }
4851 
4852     /**
4853      * Updates the {@link ApplicationInfo}s of the package activities th that are attached in the
4854      * WM hierarchy.
4855      */
updateActivityApplicationInfo(int userId, ArrayMap<String, ApplicationInfo> applicationInfoByPackage)4856     public void updateActivityApplicationInfo(int userId,
4857             ArrayMap<String, ApplicationInfo> applicationInfoByPackage) {
4858         synchronized (mGlobalLock) {
4859             if (mRootWindowContainer != null) {
4860                 mRootWindowContainer.updateActivityApplicationInfo(userId,
4861                         applicationInfoByPackage);
4862             }
4863         }
4864     }
4865 
4866     /**
4867      * Update the asset configuration and increase the assets sequence number.
4868      * @param processes the processes that needs to update the asset configuration
4869      */
updateAssetConfiguration(List<WindowProcessController> processes, boolean updateFrameworkRes)4870     public void updateAssetConfiguration(List<WindowProcessController> processes,
4871             boolean updateFrameworkRes) {
4872         synchronized (mGlobalLock) {
4873             final int assetSeq = increaseAssetConfigurationSeq();
4874 
4875             if (updateFrameworkRes) {
4876                 Configuration newConfig = new Configuration();
4877                 newConfig.assetsSeq = assetSeq;
4878                 updateConfiguration(newConfig);
4879             }
4880 
4881             // Always update the override of every process so the asset sequence of the process is
4882             // always greater than or equal to the global configuration.
4883             for (int i = processes.size() - 1; i >= 0; i--) {
4884                 final WindowProcessController wpc = processes.get(i);
4885                 wpc.updateAssetConfiguration(assetSeq);
4886             }
4887         }
4888     }
4889 
mayBeLaunchingApp()4890     boolean mayBeLaunchingApp() {
4891         return (mPowerModeReasons & POWER_MODE_REASON_START_ACTIVITY) != 0;
4892     }
4893 
startPowerMode(@owerModeReason int reason)4894     void startPowerMode(@PowerModeReason int reason) {
4895         final int prevReasons = mPowerModeReasons;
4896         mPowerModeReasons |= reason;
4897         if ((reason & POWER_MODE_REASON_UNKNOWN_VISIBILITY) != 0) {
4898             if (mRetainPowerModeAndTopProcessState) {
4899                 mH.removeMessages(H.END_POWER_MODE_UNKNOWN_VISIBILITY_MSG);
4900             }
4901             mRetainPowerModeAndTopProcessState = true;
4902             mH.sendEmptyMessageDelayed(H.END_POWER_MODE_UNKNOWN_VISIBILITY_MSG,
4903                     POWER_MODE_UNKNOWN_VISIBILITY_TIMEOUT_MS);
4904             Slog.d(TAG, "Temporarily retain top process state for launching app");
4905         }
4906         if (mPowerManagerInternal == null) {
4907             return;
4908         }
4909 
4910         // START_ACTIVITY can be used with UNKNOWN_VISIBILITY. CHANGE_DISPLAY should be used alone.
4911         if ((reason & POWER_MODE_REASON_START_ACTIVITY) != 0
4912                 && (prevReasons & POWER_MODE_REASON_START_ACTIVITY) == 0) {
4913             Trace.instant(Trace.TRACE_TAG_WINDOW_MANAGER, "StartModeLaunch");
4914             mPowerManagerInternal.setPowerMode(PowerManagerInternal.MODE_LAUNCH, true);
4915         } else if (reason == POWER_MODE_REASON_CHANGE_DISPLAY
4916                 && (prevReasons & POWER_MODE_REASON_CHANGE_DISPLAY) == 0) {
4917             Trace.instant(Trace.TRACE_TAG_WINDOW_MANAGER, "StartModeDisplayChange");
4918             mPowerManagerInternal.setPowerMode(PowerManagerInternal.MODE_DISPLAY_CHANGE, true);
4919         }
4920     }
4921 
endPowerMode(@owerModeReason int reason)4922     void endPowerMode(@PowerModeReason int reason) {
4923         if (mPowerModeReasons == 0) return;
4924         final int prevReasons = mPowerModeReasons;
4925         mPowerModeReasons &= ~reason;
4926 
4927         if ((mPowerModeReasons & POWER_MODE_REASON_UNKNOWN_VISIBILITY) != 0) {
4928             boolean allResolved = true;
4929             for (int i = mRootWindowContainer.getChildCount() - 1; i >= 0; i--) {
4930                 allResolved &= mRootWindowContainer.getChildAt(i).mUnknownAppVisibilityController
4931                         .allResolved();
4932             }
4933             if (allResolved) {
4934                 mPowerModeReasons &= ~POWER_MODE_REASON_UNKNOWN_VISIBILITY;
4935                 mRetainPowerModeAndTopProcessState = false;
4936                 mH.removeMessages(H.END_POWER_MODE_UNKNOWN_VISIBILITY_MSG);
4937             }
4938         }
4939         if (mPowerManagerInternal == null) {
4940             return;
4941         }
4942 
4943         // If the launching apps have unknown visibility, only end launch power mode until the
4944         // states are resolved.
4945         final int endLaunchModeReasons = POWER_MODE_REASON_START_ACTIVITY
4946                 | POWER_MODE_REASON_UNKNOWN_VISIBILITY;
4947         if ((prevReasons & endLaunchModeReasons) != 0
4948                 && (mPowerModeReasons & endLaunchModeReasons) == 0) {
4949             Trace.instant(Trace.TRACE_TAG_WINDOW_MANAGER, "EndModeLaunch");
4950             mPowerManagerInternal.setPowerMode(PowerManagerInternal.MODE_LAUNCH, false);
4951         }
4952         if ((prevReasons & POWER_MODE_REASON_CHANGE_DISPLAY) != 0
4953                 && (mPowerModeReasons & POWER_MODE_REASON_CHANGE_DISPLAY) == 0) {
4954             Trace.instant(Trace.TRACE_TAG_WINDOW_MANAGER, "EndModeDisplayChange");
4955             mPowerManagerInternal.setPowerMode(PowerManagerInternal.MODE_DISPLAY_CHANGE, false);
4956         }
4957     }
4958 
4959     /** @see WindowSurfacePlacer#deferLayout */
deferWindowLayout()4960     void deferWindowLayout() {
4961         if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
4962             // Reset the reasons at the first entrance because we only care about the changes in the
4963             // deferred scope.
4964             mLayoutReasons = 0;
4965         }
4966 
4967         mWindowManager.mWindowPlacerLocked.deferLayout();
4968     }
4969 
4970     /** @see WindowSurfacePlacer#continueLayout */
continueWindowLayout()4971     void continueWindowLayout() {
4972         mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
4973         if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
4974             Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
4975         }
4976 
4977         // ClientTransactions is queued during #deferWindowLayout() for performance.
4978         // Notify to continue.
4979         mLifecycleManager.onLayoutContinued();
4980     }
4981 
4982     /**
4983      * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
4984      * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
4985      * defer count is gone.
4986      */
addWindowLayoutReasons(@ayoutReason int reasons)4987     void addWindowLayoutReasons(@LayoutReason int reasons) {
4988         mLayoutReasons |= reasons;
4989     }
4990 
updateEventDispatchingLocked(boolean booted)4991     private void updateEventDispatchingLocked(boolean booted) {
4992         mWindowManager.setEventDispatching(booted && !mShuttingDown);
4993     }
4994 
isActivityStartsLoggingEnabled()4995     boolean isActivityStartsLoggingEnabled() {
4996         return mAmInternal.isActivityStartsLoggingEnabled();
4997     }
4998 
isBackgroundActivityStartsEnabled()4999     boolean isBackgroundActivityStartsEnabled() {
5000         return mAmInternal.isBackgroundActivityStartsEnabled();
5001     }
5002 
getInputDispatchingTimeoutMillisLocked(ActivityRecord r)5003     static long getInputDispatchingTimeoutMillisLocked(ActivityRecord r) {
5004         if (r == null || !r.hasProcess()) {
5005             return DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
5006         }
5007         return getInputDispatchingTimeoutMillisLocked(r.app);
5008     }
5009 
getInputDispatchingTimeoutMillisLocked(WindowProcessController r)5010     private static long getInputDispatchingTimeoutMillisLocked(WindowProcessController r) {
5011         if (r == null) {
5012             return DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
5013         }
5014         return r.getInputDispatchingTimeoutMillis();
5015     }
5016 
5017     /**
5018      * Decide based on the configuration whether we should show the ANR,
5019      * crash, etc dialogs.  The idea is that if there is no affordance to
5020      * press the on-screen buttons, or the user experience would be more
5021      * greatly impacted than the crash itself, we shouldn't show the dialog.
5022      *
5023      * A thought: SystemUI might also want to get told about this, the Power
5024      * dialog / global actions also might want different behaviors.
5025      */
updateShouldShowDialogsLocked(Configuration config)5026     private void updateShouldShowDialogsLocked(Configuration config) {
5027         mShowDialogs = shouldShowDialogs(config, /* checkUiMode= */ true);
5028     }
5029 
shouldShowDialogs(Configuration config, boolean checkUiMode)5030     private boolean shouldShowDialogs(Configuration config, boolean checkUiMode) {
5031         final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5032                 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5033                 && config.navigation == Configuration.NAVIGATION_NONAV);
5034         final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5035                 HIDE_ERROR_DIALOGS, 0) != 0;
5036         boolean showDialogs = inputMethodExists && !hideDialogsSet;
5037         if (checkUiMode) {
5038             showDialogs = showDialogs
5039                     && ActivityTaskManager.currentUiModeSupportsErrorDialogs(config);
5040         }
5041         return showDialogs;
5042     }
5043 
updateFontScaleIfNeeded(@serIdInt int userId)5044     void updateFontScaleIfNeeded(@UserIdInt int userId) {
5045         if (userId != getCurrentUserId()) {
5046             return;
5047         }
5048 
5049         final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5050                 FONT_SCALE, 1.0f, userId);
5051 
5052         synchronized (mGlobalLock) {
5053             if (getGlobalConfiguration().fontScale == scaleFactor) {
5054                 return;
5055             }
5056 
5057             final Configuration configuration
5058                     = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5059             configuration.fontScale = scaleFactor;
5060             updatePersistentConfiguration(configuration, userId);
5061         }
5062     }
5063 
updateFontWeightAdjustmentIfNeeded(@serIdInt int userId)5064     private void updateFontWeightAdjustmentIfNeeded(@UserIdInt int userId) {
5065         if (userId != getCurrentUserId()) {
5066             return;
5067         }
5068 
5069         final int fontWeightAdjustment =
5070                 Settings.Secure.getIntForUser(
5071                         mContext.getContentResolver(),
5072                         Settings.Secure.FONT_WEIGHT_ADJUSTMENT,
5073                         Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED,
5074                         userId);
5075 
5076         synchronized (mGlobalLock) {
5077             if (getGlobalConfiguration().fontWeightAdjustment == fontWeightAdjustment) {
5078                 return;
5079             }
5080 
5081             final Configuration configuration =
5082                     mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5083             configuration.fontWeightAdjustment = fontWeightAdjustment;
5084             updatePersistentConfiguration(configuration, userId);
5085         }
5086     }
5087 
5088     // Actually is sleeping or shutting down or whatever else in the future
5089     // is an inactive state.
isSleepingOrShuttingDownLocked()5090     boolean isSleepingOrShuttingDownLocked() {
5091         return isSleepingLocked() || mShuttingDown;
5092     }
5093 
isSleepingLocked()5094     boolean isSleepingLocked() {
5095         return mSleeping;
5096     }
5097 
5098     /** Update AMS states when an activity is resumed. */
setLastResumedActivityUncheckLocked(ActivityRecord r, String reason)5099     void setLastResumedActivityUncheckLocked(ActivityRecord r, String reason) {
5100         final Task task = r.getTask();
5101         if (task.isActivityTypeStandard()) {
5102             if (mCurAppTimeTracker != r.appTimeTracker) {
5103                 // We are switching app tracking.  Complete the current one.
5104                 if (mCurAppTimeTracker != null) {
5105                     mCurAppTimeTracker.stop();
5106                     mH.obtainMessage(
5107                             REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
5108                     mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
5109                     mCurAppTimeTracker = null;
5110                 }
5111                 if (r.appTimeTracker != null) {
5112                     mCurAppTimeTracker = r.appTimeTracker;
5113                     startTimeTrackingFocusedActivityLocked();
5114                 }
5115             } else {
5116                 startTimeTrackingFocusedActivityLocked();
5117             }
5118         } else {
5119             r.appTimeTracker = null;
5120         }
5121         // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5122         // TODO: Probably not, because we don't want to resume voice on switching
5123         // back to this activity
5124         if (task.voiceInteractor != null) {
5125             startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5126         } else {
5127             finishRunningVoiceLocked();
5128 
5129             if (mLastResumedActivity != null) {
5130                 final IVoiceInteractionSession session;
5131 
5132                 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
5133                 if (lastResumedActivityTask != null
5134                         && lastResumedActivityTask.voiceSession != null) {
5135                     session = lastResumedActivityTask.voiceSession;
5136                 } else {
5137                     session = mLastResumedActivity.voiceSession;
5138                 }
5139 
5140                 if (session != null) {
5141                     // We had been in a voice interaction session, but now focused has
5142                     // move to something different.  Just finish the session, we can't
5143                     // return to it and retain the proper state and synchronization with
5144                     // the voice interaction service.
5145                     finishVoiceTask(session);
5146                 }
5147             }
5148         }
5149 
5150         if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5151             mAmInternal.sendForegroundProfileChanged(r.mUserId);
5152         }
5153         final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5154 
5155         updateResumedAppTrace(r);
5156         mLastResumedActivity = r;
5157 
5158         // Don't take focus when transient launching. We don't want the app to know anything
5159         // until we've committed to the gesture. The focus will be transferred at the end of
5160         // the transition (if the transient launch is committed) or early if explicitly requested
5161         // via `setFocused*`.
5162         boolean focusedAppChanged = false;
5163         if (!getTransitionController().isTransientCollect(r)) {
5164             focusedAppChanged = r.mDisplayContent.setFocusedApp(r);
5165             if (focusedAppChanged) {
5166                 mWindowManager.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL,
5167                         true /*updateInputWindows*/);
5168             }
5169         }
5170         if (task != prevTask) {
5171             mTaskSupervisor.mRecentTasks.add(task);
5172         }
5173 
5174         if (focusedAppChanged) {
5175             applyUpdateLockStateLocked(r);
5176         }
5177         if (mVrController.mVrService != null) {
5178             applyUpdateVrModeLocked(r);
5179         }
5180 
5181         EventLogTags.writeWmSetResumedActivity(r.mUserId, r.shortComponentName, reason);
5182     }
5183 
5184     final class SleepTokenAcquirer {
5185         private final String mTag;
5186         private final SparseArray<RootWindowContainer.SleepToken> mSleepTokens =
5187                 new SparseArray<>();
5188 
SleepTokenAcquirer(@onNull String tag)5189         SleepTokenAcquirer(@NonNull String tag) {
5190             mTag = tag;
5191         }
5192 
acquire(int displayId)5193         void acquire(int displayId) {
5194             synchronized (mGlobalLock) {
5195                 if (!mSleepTokens.contains(displayId)) {
5196                     mSleepTokens.append(displayId,
5197                             mRootWindowContainer.createSleepToken(mTag, displayId));
5198                     updateSleepIfNeededLocked();
5199                 }
5200             }
5201         }
5202 
release(int displayId)5203         void release(int displayId) {
5204             synchronized (mGlobalLock) {
5205                 final RootWindowContainer.SleepToken token = mSleepTokens.get(displayId);
5206                 if (token != null) {
5207                     mRootWindowContainer.removeSleepToken(token);
5208                     mSleepTokens.remove(displayId);
5209                 }
5210             }
5211         }
5212     }
5213 
updateSleepIfNeededLocked()5214     void updateSleepIfNeededLocked() {
5215         final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
5216         final boolean wasSleeping = mSleeping;
5217         boolean updateOomAdj = false;
5218 
5219         if (!shouldSleep) {
5220             // If wasSleeping is true, we need to wake up activity manager state from when
5221             // we started sleeping. In either case, we need to apply the sleep tokens, which
5222             // will wake up root tasks or put them to sleep as appropriate.
5223             if (wasSleeping) {
5224                 mSleeping = false;
5225                 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5226                         FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
5227                 startTimeTrackingFocusedActivityLocked();
5228                 if (mTopApp != null) {
5229                     mTopApp.addToPendingTop();
5230                 }
5231                 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5232                 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
5233                 mTaskSupervisor.comeOutOfSleepIfNeededLocked();
5234             }
5235             mRootWindowContainer.applySleepTokens(true /* applyToRootTasks */);
5236             if (wasSleeping) {
5237                 updateOomAdj = true;
5238             }
5239         } else if (!mSleeping && shouldSleep) {
5240             mSleeping = true;
5241             FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5242                     FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
5243             if (mCurAppTimeTracker != null) {
5244                 mCurAppTimeTracker.stop();
5245             }
5246             mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5247             Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
5248             mTaskSupervisor.goingToSleepLocked();
5249             updateResumedAppTrace(null /* resumed */);
5250             updateOomAdj = true;
5251         }
5252         if (updateOomAdj) {
5253             updateOomAdj();
5254         }
5255     }
5256 
updateOomAdj()5257     void updateOomAdj() {
5258         mH.removeCallbacks(mUpdateOomAdjRunnable);
5259         mH.post(mUpdateOomAdjRunnable);
5260     }
5261 
updateCpuStats()5262     void updateCpuStats() {
5263         mH.post(mAmInternal::updateCpuStats);
5264     }
5265 
updateBatteryStats(ActivityRecord component, boolean resumed)5266     void updateBatteryStats(ActivityRecord component, boolean resumed) {
5267         final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
5268                 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5269                 resumed);
5270         mH.sendMessage(m);
5271     }
5272 
updateTopApp(ActivityRecord topResumedActivity)5273     void updateTopApp(ActivityRecord topResumedActivity) {
5274         final ActivityRecord top = topResumedActivity != null ? topResumedActivity
5275                 // If there is no resumed activity, it will choose the pausing or focused activity.
5276                 : mRootWindowContainer.getTopResumedActivity();
5277         mTopApp = top != null ? top.app : null;
5278         if (mTopApp == mPreviousProcess) mPreviousProcess = null;
5279 
5280         final int demoteReasons = mDemoteTopAppReasons;
5281         if ((demoteReasons & DEMOTE_TOP_REASON_EXPANDED_NOTIFICATION_SHADE) != 0) {
5282             Trace.instant(TRACE_TAG_WINDOW_MANAGER, "cancel-demote-top-for-ns-switch");
5283             mDemoteTopAppReasons = demoteReasons & ~DEMOTE_TOP_REASON_EXPANDED_NOTIFICATION_SHADE;
5284         }
5285     }
5286 
5287     /**
5288      * The process state of previous activity is more important than the regular background to keep
5289      * around in case the user wants to return to it.
5290      */
updatePreviousProcess(ActivityRecord stoppedActivity)5291     void updatePreviousProcess(ActivityRecord stoppedActivity) {
5292         if (stoppedActivity.app != null && mTopApp != null
5293                 // Don't replace the previous process if the stopped one is the top, e.g. sleeping.
5294                 && stoppedActivity.app != mTopApp
5295                 // The stopped activity must have been visible later than the previous.
5296                 && stoppedActivity.lastVisibleTime > mPreviousProcessVisibleTime
5297                 // Home has its own retained state, so don't let it occupy the previous.
5298                 && stoppedActivity.app != mHomeProcess) {
5299             mPreviousProcess = stoppedActivity.app;
5300             mPreviousProcessVisibleTime = stoppedActivity.lastVisibleTime;
5301         }
5302     }
5303 
updateActivityUsageStats(ActivityRecord activity, int event)5304     void updateActivityUsageStats(ActivityRecord activity, int event) {
5305         ComponentName taskRoot = null;
5306         int taskId = INVALID_TASK_ID;
5307         final Task task = activity.getTask();
5308         if (task != null) {
5309             final ActivityRecord rootActivity = task.getRootActivity();
5310             if (rootActivity != null) {
5311                 taskRoot = rootActivity.mActivityComponent;
5312             }
5313             taskId = task.mTaskId;
5314         }
5315         final Message m = PooledLambda.obtainMessage(
5316                 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
5317                 activity.mActivityComponent, activity.mUserId, event, activity.token, taskRoot,
5318                 new ActivityId(taskId, activity.shareableActivityToken));
5319         mH.sendMessage(m);
5320     }
5321 
startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop, String hostingType)5322     void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5323             String hostingType) {
5324         if (!mStartingProcessActivities.contains(activity)) {
5325             mStartingProcessActivities.add(activity);
5326             // Let the activity with higher z-order be started first.
5327             if (mStartingProcessActivities.size() > 1) {
5328                 mStartingProcessActivities.sort(null /* by WindowContainer#compareTo */);
5329             }
5330         } else if (mProcessNames.get(
5331                 activity.processName, activity.info.applicationInfo.uid) != null) {
5332             // The process is already starting. Wait for it to attach.
5333             return;
5334         }
5335         try {
5336             if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5337                 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
5338                         + activity.processName);
5339             }
5340             // Post message to start process to avoid possible deadlock of calling into AMS with the
5341             // ATMS lock held.
5342             final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5343                     mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5344                     isTop, hostingType, activity.intent.getComponent());
5345             mH.sendMessage(m);
5346         } finally {
5347             Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
5348         }
5349     }
5350 
setBooting(boolean booting)5351     void setBooting(boolean booting) {
5352         mAmInternal.setBooting(booting);
5353     }
5354 
isBooting()5355     boolean isBooting() {
5356         return mAmInternal.isBooting();
5357     }
5358 
setBooted(boolean booted)5359     void setBooted(boolean booted) {
5360         mAmInternal.setBooted(booted);
5361     }
5362 
isBooted()5363     boolean isBooted() {
5364         return mAmInternal.isBooted();
5365     }
5366 
postFinishBooting(boolean finishBooting, boolean enableScreen)5367     void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5368         mH.post(() -> {
5369             if (finishBooting) {
5370                 mAmInternal.finishBooting();
5371             }
5372             if (enableScreen) {
5373                 mInternal.enableScreenAfterBoot(isBooted());
5374             }
5375         });
5376     }
5377 
setHeavyWeightProcess(ActivityRecord root)5378     void setHeavyWeightProcess(ActivityRecord root) {
5379         mHeavyWeightProcess = root.app;
5380         final Message m = PooledLambda.obtainMessage(
5381                 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5382                 root.app, root.intent, root.mUserId);
5383         mH.sendMessage(m);
5384     }
5385 
clearHeavyWeightProcessIfEquals(WindowProcessController proc)5386     void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5387         if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5388             return;
5389         }
5390 
5391         mHeavyWeightProcess = null;
5392         final Message m = PooledLambda.obtainMessage(
5393                 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5394                 proc.mUserId);
5395         mH.sendMessage(m);
5396     }
5397 
cancelHeavyWeightProcessNotification(int userId)5398     private void cancelHeavyWeightProcessNotification(int userId) {
5399         final INotificationManager inm = NotificationManager.getService();
5400         if (inm == null) {
5401             return;
5402         }
5403         try {
5404             inm.cancelNotificationWithTag("android", "android", null,
5405                     SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5406         } catch (RuntimeException e) {
5407             Slog.w(TAG, "Error canceling notification for service", e);
5408         } catch (RemoteException e) {
5409         }
5410 
5411     }
5412 
postHeavyWeightProcessNotification( WindowProcessController proc, Intent intent, int userId)5413     private void postHeavyWeightProcessNotification(
5414             WindowProcessController proc, Intent intent, int userId) {
5415         if (proc == null) {
5416             return;
5417         }
5418 
5419         final INotificationManager inm = NotificationManager.getService();
5420         if (inm == null) {
5421             return;
5422         }
5423 
5424         try {
5425             Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5426             String text = mContext.getString(R.string.heavy_weight_notification,
5427                     context.getApplicationInfo().loadLabel(context.getPackageManager()));
5428             Notification notification =
5429                     new Notification.Builder(context,
5430                             SystemNotificationChannels.HEAVY_WEIGHT_APP)
5431                             .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5432                             .setWhen(0)
5433                             .setOngoing(true)
5434                             .setTicker(text)
5435                             .setColor(mContext.getColor(
5436                                     com.android.internal.R.color.system_notification_accent_color))
5437                             .setContentTitle(text)
5438                             .setContentText(
5439                                     mContext.getText(R.string.heavy_weight_notification_detail))
5440                             .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5441                                     intent, PendingIntent.FLAG_CANCEL_CURRENT
5442                                             | PendingIntent.FLAG_IMMUTABLE, null,
5443                                     new UserHandle(userId)))
5444                             .build();
5445             try {
5446                 inm.enqueueNotificationWithTag("android", "android", null,
5447                         SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5448             } catch (RuntimeException e) {
5449                 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5450             } catch (RemoteException e) {
5451             }
5452         } catch (PackageManager.NameNotFoundException e) {
5453             Slog.w(TAG, "Unable to create context for heavy notification", e);
5454         }
5455 
5456     }
5457 
getIntentSenderLocked(int type, String packageName, String featureId, int callingUid, int userId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions)5458     IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5459             int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5460             Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
5461 
5462         ActivityRecord activity = null;
5463         if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5464             activity = ActivityRecord.isInRootTaskLocked(token);
5465             if (activity == null) {
5466                 Slog.w(TAG, "Failed createPendingResult: activity " + token
5467                         + " not in any root task");
5468                 return null;
5469             }
5470             if (activity.finishing) {
5471                 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5472                 return null;
5473             }
5474         }
5475 
5476         final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5477                 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5478                 resolvedTypes, flags, bOptions);
5479         final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5480         if (noCreate) {
5481             return rec;
5482         }
5483         if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5484             if (activity.pendingResults == null) {
5485                 activity.pendingResults = new HashSet<>();
5486             }
5487             activity.pendingResults.add(rec.ref);
5488         }
5489         return rec;
5490     }
5491 
5492     // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
startTimeTrackingFocusedActivityLocked()5493     private void startTimeTrackingFocusedActivityLocked() {
5494         final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
5495         if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5496             mCurAppTimeTracker.start(resumedActivity.packageName);
5497         }
5498     }
5499 
updateResumedAppTrace(@ullable ActivityRecord resumed)5500     private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5501         if (Trace.isTagEnabled(Trace.TRACE_TAG_WINDOW_MANAGER)) {
5502             if (mTracedResumedActivity != null) {
5503                 Trace.asyncTraceForTrackEnd(TRACE_TAG_WINDOW_MANAGER,
5504                         "Focused app", System.identityHashCode(mTracedResumedActivity));
5505             }
5506             if (resumed != null) {
5507                 Trace.asyncTraceForTrackBegin(TRACE_TAG_WINDOW_MANAGER,
5508                         "Focused app", resumed.mActivityComponent.flattenToShortString(),
5509                         System.identityHashCode(resumed));
5510             }
5511         }
5512         mTracedResumedActivity = resumed;
5513     }
5514 
5515     /** Applies latest configuration and/or visibility updates if needed. */
ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes)5516     boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5517         if (starting == null && mTaskSupervisor.isRootVisibilityUpdateDeferred()) {
5518             return true;
5519         }
5520         boolean kept = true;
5521         final Task mainRootTask = mRootWindowContainer.getTopDisplayFocusedRootTask();
5522         // mainRootTask is null during startup.
5523         if (mainRootTask != null) {
5524             if (changes != 0 && starting == null) {
5525                 // If the configuration changed, and the caller is not already
5526                 // in the process of starting an activity, then find the top
5527                 // activity to check if its configuration needs to change.
5528                 starting = mainRootTask.topRunningActivity();
5529             }
5530 
5531             if (starting != null) {
5532                 kept = starting.ensureActivityConfiguration();
5533                 // And we need to make sure at this point that all other activities
5534                 // are made visible with the correct configuration.
5535                 mRootWindowContainer.ensureActivitiesVisible(starting);
5536             }
5537         }
5538 
5539         return kept;
5540     }
5541 
scheduleAppGcsLocked()5542     void scheduleAppGcsLocked() {
5543         mH.post(() -> mAmInternal.scheduleAppGcs());
5544     }
5545 
compatibilityInfoForPackageLocked(ApplicationInfo ai)5546     CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5547         return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5548     }
5549 
5550     /**
5551      * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5552      * PackageManager could be unavailable at construction time and therefore needs to be accessed
5553      * on demand.
5554      */
getPackageManager()5555     IPackageManager getPackageManager() {
5556         return AppGlobals.getPackageManager();
5557     }
5558 
getPackageManagerInternalLocked()5559     PackageManagerInternal getPackageManagerInternalLocked() {
5560         if (mPmInternal == null) {
5561             mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5562         }
5563         return mPmInternal;
5564     }
5565 
getSysUiServiceComponentLocked()5566     ComponentName getSysUiServiceComponentLocked() {
5567         if (mSysUiServiceComponent == null) {
5568             final PackageManagerInternal pm = getPackageManagerInternalLocked();
5569             mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5570         }
5571         return mSysUiServiceComponent;
5572     }
5573 
getPermissionPolicyInternal()5574     PermissionPolicyInternal getPermissionPolicyInternal() {
5575         if (mPermissionPolicyInternal == null) {
5576             mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5577         }
5578         return mPermissionPolicyInternal;
5579     }
5580 
getStatusBarManagerInternal()5581     StatusBarManagerInternal getStatusBarManagerInternal() {
5582         if (mStatusBarManagerInternal == null) {
5583             mStatusBarManagerInternal = LocalServices.getService(StatusBarManagerInternal.class);
5584         }
5585         return mStatusBarManagerInternal;
5586     }
5587 
getUserManagerInternal()5588     UserManagerInternal getUserManagerInternal() {
5589         if (mUserManagerInternal == null) {
5590             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
5591         }
5592         return mUserManagerInternal;
5593     }
5594 
5595     @Nullable
getWindowStyle(String packageName, int theme, int userId)5596     ActivityRecord.WindowStyle getWindowStyle(String packageName, int theme, int userId) {
5597         if (!com.android.window.flags.Flags.cacheWindowStyle()) {
5598             final AttributeCache.Entry ent = AttributeCache.instance().get(packageName,
5599                     theme, com.android.internal.R.styleable.Window, userId);
5600             return ent != null ? new ActivityRecord.WindowStyle(ent.array) : null;
5601         }
5602         return mWindowStyleCache.get(packageName, theme, userId);
5603     }
5604 
getAppWarningsLocked()5605     AppWarnings getAppWarningsLocked() {
5606         return mAppWarnings;
5607     }
5608 
getHomeIntent()5609     Intent getHomeIntent() {
5610         Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5611         intent.setComponent(mTopComponent);
5612         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5613         if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5614             intent.addCategory(Intent.CATEGORY_HOME);
5615         }
5616         return intent;
5617     }
5618 
5619     /**
5620      * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5621      * activities.
5622      *
5623      * @param preferredPackage Specify a preferred package name, otherwise use the package name
5624      *                         defined in config_secondaryHomePackage.
5625      * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5626      */
getSecondaryHomeIntent(String preferredPackage)5627     Intent getSecondaryHomeIntent(String preferredPackage) {
5628         final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5629         final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5630                 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5631         if (preferredPackage == null || useSystemProvidedLauncher) {
5632             // Using the package name stored in config if no preferred package name or forced.
5633             final String secondaryHomePackage = mContext.getResources().getString(
5634                     com.android.internal.R.string.config_secondaryHomePackage);
5635             intent.setPackage(secondaryHomePackage);
5636         } else {
5637             intent.setPackage(preferredPackage);
5638         }
5639         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5640         if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5641             intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5642         }
5643         return intent;
5644     }
5645 
getAppInfoForUser(ApplicationInfo info, int userId)5646     ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5647         if (info == null) return null;
5648         ApplicationInfo newInfo = new ApplicationInfo(info);
5649         newInfo.initForUser(userId);
5650         return newInfo;
5651     }
5652 
getProcessController(String processName, int uid)5653     WindowProcessController getProcessController(String processName, int uid) {
5654         if (uid == SYSTEM_UID) {
5655             // The system gets to run in any process. If there are multiple processes with the same
5656             // uid, just pick the first (this should never happen).
5657             final SparseArray<WindowProcessController> procs =
5658                     mProcessNames.getMap().get(processName);
5659             if (procs == null) return null;
5660             final int procCount = procs.size();
5661             for (int i = 0; i < procCount; i++) {
5662                 final int procUid = procs.keyAt(i);
5663                 if (!UserHandle.isCore(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5664                     // Don't use an app process or different user process for system component.
5665                     continue;
5666                 }
5667                 return procs.valueAt(i);
5668             }
5669         }
5670 
5671         return mProcessNames.get(processName, uid);
5672     }
5673 
getProcessController(IApplicationThread thread)5674     WindowProcessController getProcessController(IApplicationThread thread) {
5675         if (thread == null) {
5676             return null;
5677         }
5678 
5679         final IBinder threadBinder = thread.asBinder();
5680         final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5681         for (int i = pmap.size() - 1; i >= 0; i--) {
5682             final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5683             for (int j = procs.size() - 1; j >= 0; j--) {
5684                 final WindowProcessController proc = procs.valueAt(j);
5685                 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5686                     return proc;
5687                 }
5688             }
5689         }
5690 
5691         return null;
5692     }
5693 
5694     /**
5695      * Returns the {@link WindowProcessController} for the app process for the given uid and pid.
5696      *
5697      * If no such {@link WindowProcessController} is found, it does not belong to an app, or the
5698      * pid does not match the uid {@code null} is returned.
5699      */
getProcessController(int pid, int uid)5700     WindowProcessController getProcessController(int pid, int uid) {
5701         final WindowProcessController proc = mProcessMap.getProcess(pid);
5702         if (proc == null) return null;
5703         if (UserHandle.isApp(uid) && proc.mUid == uid) {
5704             return proc;
5705         }
5706         return null;
5707     }
5708 
5709     /**
5710      * Returns the package name if (and only if) the package name can be uniquely determined.
5711      * Otherwise returns {@code null}.
5712      *
5713      * The provided pid must match the provided uid, otherwise this also returns null.
5714      */
getPackageNameIfUnique(int uid, int pid)5715     @Nullable String getPackageNameIfUnique(int uid, int pid) {
5716         final WindowProcessController proc = mProcessMap.getProcess(pid);
5717         if (proc == null || proc.mUid != uid) {
5718             Slog.w(TAG, "callingPackage for (uid=" + uid + ", pid=" + pid + ") has no WPC");
5719             return null;
5720         }
5721         List<String> realCallingPackages = proc.getPackageList();
5722         if (realCallingPackages.size() != 1) {
5723             Slog.w(TAG, "callingPackage for (uid=" + uid + ", pid=" + pid + ") is ambiguous: "
5724                     + realCallingPackages);
5725             return null;
5726         }
5727         return realCallingPackages.get(0);
5728     }
5729 
5730     /** A uid is considered to be foreground if it has a visible non-toast window. */
5731     @HotPath(caller = HotPath.START_SERVICE)
hasActiveVisibleWindow(int uid)5732     boolean hasActiveVisibleWindow(int uid) {
5733         if (mVisibleActivityProcessTracker.hasVisibleActivity(uid)) {
5734             return true;
5735         }
5736         return mActiveUids.hasNonAppVisibleWindow(uid);
5737     }
5738 
isDeviceOwner(int uid)5739     boolean isDeviceOwner(int uid) {
5740         return uid >= 0 && mDeviceOwnerUid == uid;
5741     }
5742 
setDeviceOwnerUid(int uid)5743     void setDeviceOwnerUid(int uid) {
5744         mDeviceOwnerUid = uid;
5745     }
5746 
isAffiliatedProfileOwner(int uid)5747     boolean isAffiliatedProfileOwner(int uid) {
5748         return uid >= 0 && mProfileOwnerUids.contains(uid)
5749             && DeviceStateCache.getInstance().hasAffiliationWithDevice(UserHandle.getUserId(uid));
5750     }
5751 
setProfileOwnerUids(Set<Integer> uids)5752     void setProfileOwnerUids(Set<Integer> uids) {
5753         mProfileOwnerUids = uids;
5754     }
5755 
5756     /**
5757      * Saves the current activity manager state and includes the saved state in the next dump of
5758      * activity manager.
5759      */
saveANRState(ActivityRecord activity, String reason)5760     void saveANRState(ActivityRecord activity, String reason) {
5761         final StringWriter sw = new StringWriter();
5762         final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
5763         pw.println("  ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
5764         if (reason != null) {
5765             pw.println("  Reason: " + reason);
5766         }
5767         pw.println();
5768         if (activity != null) {
5769             final Task rootTask = activity.getRootTask();
5770             if (rootTask != null) {
5771                 rootTask.forAllTaskFragments(
5772                         tf -> tf.dumpInner("  ", pw, true /* dumpAll */, null /* dumpPackage */));
5773                 pw.println();
5774             }
5775             mActivityStartController.dump(pw, "  ", activity.packageName);
5776             if (mActivityStartController.getLastStartActivity() != activity) {
5777                 activity.dump(pw, "  ", true /* dumpAll */);
5778             }
5779         }
5780         ActivityTaskSupervisor.printThisActivity(pw, mRootWindowContainer.getTopResumedActivity(),
5781                 null /* dumpPackage */, INVALID_DISPLAY, true /* needSep */,
5782                 "  ResumedActivity: ", /* header= */ null /* header */);
5783         mLockTaskController.dump(pw, "  ");
5784         mKeyguardController.dump(pw, "  ");
5785         pw.println("-------------------------------------------------------------------"
5786                 + "------------");
5787         pw.close();
5788 
5789         mLastANRState = sw.toString();
5790     }
5791 
isAssociatedCompanionApp(int userId, int uid)5792     boolean isAssociatedCompanionApp(int userId, int uid) {
5793         final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5794         if (allUids == null) {
5795             return false;
5796         }
5797         return allUids.contains(uid);
5798     }
5799 
5800     @Override
onTransact(int code, Parcel data, Parcel reply, int flags)5801     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
5802             throws RemoteException {
5803         try {
5804             return super.onTransact(code, data, reply, flags);
5805         } catch (RuntimeException e) {
5806             throw logAndRethrowRuntimeExceptionOnTransact(TAG, e);
5807         }
5808     }
5809 
5810     /** Provides the full stack traces of non-security exception that occurs in onTransact. */
logAndRethrowRuntimeExceptionOnTransact(String name, RuntimeException e)5811     static RuntimeException logAndRethrowRuntimeExceptionOnTransact(String name,
5812             RuntimeException e) {
5813         if (!(e instanceof SecurityException)) {
5814             Slog.w(TAG, name + " onTransact aborts"
5815                     + " UID:" + Binder.getCallingUid()
5816                     + " PID:" + Binder.getCallingPid(), e);
5817         }
5818         throw e;
5819     }
5820 
5821     @Override
setRunningRemoteTransitionDelegate(IApplicationThread delegate)5822     public void setRunningRemoteTransitionDelegate(IApplicationThread delegate) {
5823         final TransitionController controller = getTransitionController();
5824         // A quick path without entering WM lock.
5825         if (delegate != null && controller.mRemotePlayer.reportRunning(delegate)) {
5826             // The delegate was known as running remote transition.
5827             return;
5828         }
5829         mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
5830                 "setRunningRemoteTransition");
5831         final int callingPid = Binder.getCallingPid();
5832         final int callingUid = Binder.getCallingUid();
5833         synchronized (mGlobalLock) {
5834             // Also only allow a process which is already runningRemoteAnimation to mark another
5835             // process.
5836             final WindowProcessController callingProc = getProcessController(callingPid,
5837                     callingUid);
5838             if (callingProc == null || !callingProc.isRunningRemoteTransition()) {
5839                 final String msg = "Can't call setRunningRemoteTransition from a process (pid="
5840                         + callingPid + " uid=" + callingUid + ") which isn't itself running a "
5841                         + "remote transition.";
5842                 Slog.e(TAG, msg);
5843                 throw new SecurityException(msg);
5844             }
5845             final WindowProcessController wpc = getProcessController(delegate);
5846             if (wpc == null) {
5847                 Slog.w(TAG, "setRunningRemoteTransition: no process for " + delegate);
5848                 return;
5849             }
5850             controller.mRemotePlayer.update(wpc, true /* running */, false /* predict */);
5851         }
5852     }
5853 
5854     @Override
registerScreenCaptureObserver(IBinder activityToken, IScreenCaptureObserver observer)5855     public void registerScreenCaptureObserver(IBinder activityToken,
5856             IScreenCaptureObserver observer) {
5857         mAmInternal.enforceCallingPermission(DETECT_SCREEN_CAPTURE,
5858                 "registerScreenCaptureObserver");
5859         synchronized (mGlobalLock) {
5860             ActivityRecord activityRecord = ActivityRecord.forTokenLocked(activityToken);
5861             if (activityRecord != null) {
5862                 activityRecord.registerCaptureObserver(observer);
5863             }
5864         }
5865     }
5866 
5867     @Override
unregisterScreenCaptureObserver(IBinder activityToken, IScreenCaptureObserver observer)5868     public void unregisterScreenCaptureObserver(IBinder activityToken,
5869             IScreenCaptureObserver observer) {
5870         mAmInternal.enforceCallingPermission(DETECT_SCREEN_CAPTURE,
5871                 "unregisterScreenCaptureObserver");
5872         synchronized (mGlobalLock) {
5873             ActivityRecord activityRecord = ActivityRecord.forTokenLocked(activityToken);
5874             if (activityRecord != null) {
5875                 activityRecord.unregisterCaptureObserver(observer);
5876             }
5877         }
5878     }
5879 
registerCompatScaleProvider(@ompatScaleProvider.CompatScaleModeOrderId int id, @NonNull CompatScaleProvider provider)5880     void registerCompatScaleProvider(@CompatScaleProvider.CompatScaleModeOrderId int id,
5881             @NonNull CompatScaleProvider provider) {
5882         mCompatModePackages.registerCompatScaleProvider(id, provider);
5883     }
5884 
unregisterCompatScaleProvider(@ompatScaleProvider.CompatScaleModeOrderId int id)5885     void unregisterCompatScaleProvider(@CompatScaleProvider.CompatScaleModeOrderId int id) {
5886         mCompatModePackages.unregisterCompatScaleProvider(id);
5887     }
5888 
5889     /**
5890      * Returns {@code true} if the process represented by the pid passed as argument is
5891      * instrumented and the instrumentation source was granted with the permission also
5892      * passed as argument.
5893      */
instrumentationSourceHasPermission(int pid, String permission)5894     boolean instrumentationSourceHasPermission(int pid, String permission) {
5895         final WindowProcessController process;
5896         synchronized (mGlobalLock) {
5897             process = mProcessMap.getProcess(pid);
5898         }
5899         if (process == null || !process.isInstrumenting()) {
5900             return false;
5901         }
5902         final int sourceUid = process.getInstrumentationSourceUid();
5903         return checkPermission(permission, -1, sourceUid) == PackageManager.PERMISSION_GRANTED;
5904     }
5905 
5906     /**
5907      * Registers an app that uses the Strict Mode for detecting BAL.
5908      *
5909      * @param callback the callback to register
5910      * @return {@code true} if the callback was registered successfully.
5911      */
5912     @Override
registerBackgroundActivityStartCallback(IBinder callback)5913     public boolean registerBackgroundActivityStartCallback(IBinder callback) {
5914         return mTaskSupervisor.getBackgroundActivityLaunchController()
5915                 .addStrictModeCallback(Binder.getCallingUid(), callback);
5916     }
5917 
5918     /**
5919      * Unregisters an app that uses the Strict Mode for detecting BAL.
5920      *
5921      * @param callback the callback to unregister
5922      */
5923     @Override
unregisterBackgroundActivityStartCallback(IBinder callback)5924     public void unregisterBackgroundActivityStartCallback(IBinder callback) {
5925         mTaskSupervisor.getBackgroundActivityLaunchController()
5926                 .removeStrictModeCallback(Binder.getCallingUid(), callback);
5927     }
5928 
5929     /**
5930      * Wrap the {@link ActivityOptions} in {@link SafeActivityOptions} and attach caller options
5931      * that allow using the callers permissions to start background activities.
5932      */
createSafeActivityOptionsWithBalAllowed( @ullable ActivityOptions options)5933     private SafeActivityOptions createSafeActivityOptionsWithBalAllowed(
5934             @Nullable ActivityOptions options) {
5935         if (options == null) {
5936             options = ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode(
5937                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
5938         } else if (options.getPendingIntentBackgroundActivityStartMode()
5939                 == ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED) {
5940             options.setPendingIntentBackgroundActivityStartMode(
5941                     ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
5942         }
5943         return new SafeActivityOptions(options, Binder.getCallingPid(), Binder.getCallingUid());
5944     }
5945 
5946     /**
5947      * Wrap the options {@link Bundle} in {@link SafeActivityOptions} and attach caller options
5948      * that allow using the callers permissions to start background activities.
5949      */
createSafeActivityOptionsWithBalAllowed(@ullable Bundle bOptions)5950     private SafeActivityOptions createSafeActivityOptionsWithBalAllowed(@Nullable Bundle bOptions) {
5951         return createSafeActivityOptionsWithBalAllowed(ActivityOptions.fromBundle(bOptions));
5952     }
5953 
5954     final class H extends Handler {
5955         static final int REPORT_TIME_TRACKER_MSG = 1;
5956         static final int END_POWER_MODE_UNKNOWN_VISIBILITY_MSG = 3;
5957         static final int RESUME_FG_APP_SWITCH_MSG = 4;
5958         static final int ADD_WAKEFULNESS_ANIMATING_REASON = 5;
5959         static final int REMOVE_WAKEFULNESS_ANIMATING_REASON = 6;
5960 
5961         static final int FIRST_ACTIVITY_TASK_MSG = 100;
5962         static final int FIRST_SUPERVISOR_TASK_MSG = 200;
5963 
H(Looper looper)5964         H(Looper looper) {
5965             super(looper);
5966         }
5967 
5968         @Override
handleMessage(Message msg)5969         public void handleMessage(Message msg) {
5970             switch (msg.what) {
5971                 case REPORT_TIME_TRACKER_MSG: {
5972                     AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5973                     tracker.deliverResult(mContext);
5974                 }
5975                 break;
5976                 case ADD_WAKEFULNESS_ANIMATING_REASON: {
5977                     final WindowProcessController proc = (WindowProcessController) msg.obj;
5978                     synchronized (mGlobalLock) {
5979                         proc.addAnimatingReason(
5980                                 WindowProcessController.ANIMATING_REASON_WAKEFULNESS_CHANGE);
5981                     }
5982                 }
5983                 break;
5984                 case REMOVE_WAKEFULNESS_ANIMATING_REASON: {
5985                     final WindowProcessController proc = (WindowProcessController) msg.obj;
5986                     synchronized (mGlobalLock) {
5987                         proc.removeAnimatingReason(
5988                                 WindowProcessController.ANIMATING_REASON_WAKEFULNESS_CHANGE);
5989                     }
5990                     Trace.instant(TRACE_TAG_WINDOW_MANAGER, "finishWakefulnessAnimating");
5991                 }
5992                 break;
5993                 case END_POWER_MODE_UNKNOWN_VISIBILITY_MSG: {
5994                     synchronized (mGlobalLock) {
5995                         mRetainPowerModeAndTopProcessState = false;
5996                         endPowerMode(POWER_MODE_REASON_UNKNOWN_VISIBILITY);
5997                         if (mTopApp != null
5998                                 && mTopProcessState == ActivityManager.PROCESS_STATE_TOP_SLEEPING) {
5999                             // Restore the scheduling group for sleeping.
6000                             mTopApp.updateProcessInfo(false /* updateServiceConnection */,
6001                                     false /* activityChange */, true /* updateOomAdj */,
6002                                     false /* addPendingTopUid */);
6003                         }
6004                     }
6005                 }
6006                 break;
6007                 case RESUME_FG_APP_SWITCH_MSG: {
6008                     synchronized (mGlobalLock) {
6009                         if (mAppSwitchesState == APP_SWITCH_DISALLOW) {
6010                             mAppSwitchesState = APP_SWITCH_FG_ONLY;
6011                         }
6012                     }
6013                 }
6014                 break;
6015             }
6016         }
6017     }
6018 
6019     final class UiHandler extends Handler {
6020         static final int DISMISS_DIALOG_UI_MSG = 1;
6021 
UiHandler()6022         public UiHandler() {
6023             super(UiThread.get().getLooper(), null, true);
6024         }
6025 
6026         @Override
handleMessage(Message msg)6027         public void handleMessage(Message msg) {
6028             switch (msg.what) {
6029                 case DISMISS_DIALOG_UI_MSG: {
6030                     final Dialog d = (Dialog) msg.obj;
6031                     d.dismiss();
6032                     break;
6033                 }
6034             }
6035         }
6036     }
6037 
6038     final class LocalService extends ActivityTaskManagerInternal {
6039 
6040         @Override
getHomeActivityForUser(int userId)6041         public ComponentName getHomeActivityForUser(int userId) {
6042             synchronized (mGlobalLock) {
6043                 final ActivityRecord homeActivity =
6044                         mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
6045                 return homeActivity == null ? null : homeActivity.mActivityComponent;
6046             }
6047         }
6048 
6049         @Override
onLocalVoiceInteractionStarted(IBinder activity, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor)6050         public void onLocalVoiceInteractionStarted(IBinder activity,
6051                 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6052             synchronized (mGlobalLock) {
6053                 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
6054             }
6055         }
6056 
6057         @Override
getTopVisibleActivities()6058         public List<ActivityAssistInfo> getTopVisibleActivities() {
6059             synchronized (mGlobalLock) {
6060                 return mRootWindowContainer.getTopVisibleActivities();
6061             }
6062         }
6063 
6064         @Override
hasResumedActivity(int uid)6065         public boolean hasResumedActivity(int uid) {
6066             return mVisibleActivityProcessTracker.hasResumedActivity(uid);
6067         }
6068 
6069         @Override
setBackgroundActivityStartCallback( @ullable BackgroundActivityStartCallback backgroundActivityStartCallback)6070         public void setBackgroundActivityStartCallback(
6071                 @Nullable BackgroundActivityStartCallback backgroundActivityStartCallback) {
6072             mBackgroundActivityStartCallback = backgroundActivityStartCallback;
6073         }
6074 
6075         @Override
setAccessibilityServiceUids(IntArray uids)6076         public void setAccessibilityServiceUids(IntArray uids) {
6077             synchronized (mGlobalLock) {
6078                 mAccessibilityServiceUids = uids.toArray();
6079             }
6080         }
6081 
6082         @Override
startActivitiesAsPackage(String packageName, @Nullable String featureId, int userId, Intent[] intents, Bundle bOptions)6083         public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6084                 int userId, Intent[] intents, Bundle bOptions) {
6085             Objects.requireNonNull(intents, "intents");
6086             final String[] resolvedTypes = new String[intents.length];
6087 
6088             // UID of the package on user userId.
6089             // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6090             // packageUid may not be initialized.
6091             int packageUid = 0;
6092             final long ident = Binder.clearCallingIdentity();
6093 
6094             try {
6095                 for (int i = 0; i < intents.length; i++) {
6096                     resolvedTypes[i] =
6097                             intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6098                 }
6099 
6100                 packageUid = AppGlobals.getPackageManager().getPackageUid(
6101                         packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6102             } catch (RemoteException e) {
6103                 // Shouldn't happen.
6104             } finally {
6105                 Binder.restoreCallingIdentity(ident);
6106             }
6107 
6108             final int callingPid = Binder.getCallingPid();
6109             final int callingUid = Binder.getCallingUid();
6110             return getActivityStartController().startActivitiesInPackage(
6111                     packageUid, packageName, featureId,
6112                     intents, resolvedTypes, null /* resultTo */,
6113                     SafeActivityOptions.fromBundle(bOptions, callingPid, callingUid), userId,
6114                     false /* validateIncomingUser */, null /* originatingPendingIntent */,
6115                     false);
6116         }
6117 
6118         @Override
startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, @Nullable String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, boolean allowBalExemptionForSystemProcess)6119         public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6120                 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6121                 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6122                 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
6123                 boolean allowBalExemptionForSystemProcess) {
6124             assertPackageMatchesCallingUid(callingPackage);
6125             return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6126                     realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6127                     resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
6128                     allowBalExemptionForSystemProcess);
6129         }
6130 
6131         @Override
startActivityInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, boolean allowBalExemptionForSystemProcess)6132         public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6133                 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6134                 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6135                 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6136                 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
6137                 boolean allowBalExemptionForSystemProcess) {
6138             assertPackageMatchesCallingUid(callingPackage);
6139             return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6140                     realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6141                     resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6142                     reason, validateIncomingUser, originatingPendingIntent,
6143                     allowBalExemptionForSystemProcess);
6144         }
6145 
6146         @Override
startActivityAsUser(IApplicationThread caller, String callerPackage, @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo, int startFlags, Bundle options, int userId)6147         public int startActivityAsUser(IApplicationThread caller, String callerPackage,
6148                 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6149                 int startFlags, Bundle options, int userId) {
6150             return ActivityTaskManagerService.this.startActivityAsUser(
6151                     caller, callerPackage, callerFeatureId, intent,
6152                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6153                     resultTo, null, 0, startFlags, null, options, userId,
6154                     false /*validateIncomingUser*/);
6155         }
6156 
6157         @Override
startActivityWithScreenshot(@onNull Intent intent, @NonNull String callingPackage, int callingUid, int callingPid, @Nullable IBinder resultTo, @Nullable Bundle options, int userId)6158         public int startActivityWithScreenshot(@NonNull Intent intent,
6159                 @NonNull String callingPackage, int callingUid, int callingPid,
6160                 @Nullable IBinder resultTo, @Nullable Bundle options, int userId) {
6161             userId = getActivityStartController().checkTargetUser(userId,
6162                     false /* validateIncomingUser */, Binder.getCallingPid(),
6163                     Binder.getCallingUid(), "startActivityWithScreenshot");
6164 
6165             return getActivityStartController()
6166                     .obtainStarter(intent, "startActivityWithScreenshot")
6167                     .setCallingUid(callingUid)
6168                     .setCallingPid(callingPid)
6169                     .setCallingPackage(callingPackage)
6170                     .setResultTo(resultTo)
6171                     .setActivityOptions(createSafeActivityOptionsWithBalAllowed(options))
6172                     .setRealCallingUid(Binder.getCallingUid())
6173                     .setUserId(userId)
6174                     .setAllowBalExemptionForSystemProcess(true)
6175                     .setFreezeScreen(true)
6176                     .execute();
6177         }
6178 
6179         /**
6180          * Called after virtual display Id is updated by
6181          * {@link com.android.server.vr.Vr2dDisplay} with a specific
6182          * {@param vrVr2dDisplayId}.
6183          */
6184         @Override
setVr2dDisplayId(int vr2dDisplayId)6185         public void setVr2dDisplayId(int vr2dDisplayId) {
6186             ProtoLog.d(WM_DEBUG_TASKS, "setVr2dDisplayId called for: %d", vr2dDisplayId);
6187             synchronized (mGlobalLock) {
6188                 mVr2dDisplayId = vr2dDisplayId;
6189             }
6190         }
6191 
6192         @Override
getDisplayId(IBinder token)6193         public int getDisplayId(IBinder token) {
6194             synchronized (mGlobalLock) {
6195                 ActivityRecord r = ActivityRecord.forTokenLocked(token);
6196                 if (r == null) {
6197                     throw new IllegalArgumentException(
6198                             "getDisplayId: No activity record matching token=" + token);
6199                 }
6200                 return r.getDisplayId();
6201             }
6202         }
6203 
6204         @Override
registerScreenObserver(ScreenObserver observer)6205         public void registerScreenObserver(ScreenObserver observer) {
6206             mScreenObservers.add(observer);
6207         }
6208 
6209         @Override
unregisterScreenObserver(ScreenObserver observer)6210         public void unregisterScreenObserver(ScreenObserver observer) {
6211             mScreenObservers.remove(observer);
6212         }
6213 
6214         @Override
isCallerRecents(int callingUid)6215         public boolean isCallerRecents(int callingUid) {
6216             return ActivityTaskManagerService.this.isCallerRecents(callingUid);
6217         }
6218 
6219         @Override
isRecentsComponentHomeActivity(int userId)6220         public boolean isRecentsComponentHomeActivity(int userId) {
6221             return getRecentTasks().isRecentsComponentHomeActivity(userId);
6222         }
6223 
6224         @Override
checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName)6225         public boolean checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName) {
6226             return ActivityTaskManagerService.this.checkCanCloseSystemDialogs(pid, uid,
6227                     packageName);
6228         }
6229 
6230         @Override
canCloseSystemDialogs(int pid, int uid)6231         public boolean canCloseSystemDialogs(int pid, int uid) {
6232             return ActivityTaskManagerService.this.canCloseSystemDialogs(pid, uid);
6233         }
6234 
6235         @Override
notifyActiveVoiceInteractionServiceChanged(ComponentName component)6236         public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6237             synchronized (mGlobalLock) {
6238                 mActiveVoiceInteractionServiceComponent = component;
6239             }
6240         }
6241 
6242         @Override
notifyActiveDreamChanged(@ullable ComponentName dreamComponent)6243         public void notifyActiveDreamChanged(@Nullable ComponentName dreamComponent) {
6244             synchronized (mGlobalLock) {
6245                 mActiveDreamComponent = dreamComponent;
6246             }
6247         }
6248 
6249         @Override
startDreamActivity(@onNull Intent intent, int callingUid, int callingPid)6250         public IAppTask startDreamActivity(@NonNull Intent intent, int callingUid, int callingPid) {
6251             return startDreamActivityInternal(intent, callingUid, callingPid);
6252         }
6253 
6254         @Override
setAllowAppSwitches(@onNull String type, int uid, int userId)6255         public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6256             if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6257                 return;
6258             }
6259             synchronized (mGlobalLock) {
6260                 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6261                 if (types == null) {
6262                     if (uid < 0) {
6263                         return;
6264                     }
6265                     types = new ArrayMap<>();
6266                     mAllowAppSwitchUids.put(userId, types);
6267                 }
6268                 if (uid < 0) {
6269                     types.remove(type);
6270                 } else {
6271                     types.put(type, uid);
6272                 }
6273             }
6274         }
6275 
6276         @Override
onUserStopped(int userId)6277         public void onUserStopped(int userId) {
6278             synchronized (mGlobalLock) {
6279                 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6280                 mAllowAppSwitchUids.remove(userId);
6281             }
6282         }
6283 
6284         @Override
isGetTasksAllowed(String caller, int callingPid, int callingUid)6285         public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6286             return ActivityTaskManagerService.this.isGetTasksAllowed(
6287                     caller, callingPid, callingUid);
6288         }
6289 
6290         @HotPath(caller = HotPath.PROCESS_CHANGE)
6291         @Override
onProcessAdded(WindowProcessController proc)6292         public void onProcessAdded(WindowProcessController proc) {
6293             synchronized (mGlobalLockWithoutBoost) {
6294                 mPackageConfigPersister.updateConfigIfNeeded(
6295                         proc, proc.mUserId, proc.mInfo.packageName);
6296                 mProcessNames.put(proc.mName, proc.mUid, proc);
6297             }
6298         }
6299 
6300         @HotPath(caller = HotPath.PROCESS_CHANGE)
6301         @Override
onProcessRemoved(String name, int uid)6302         public void onProcessRemoved(String name, int uid) {
6303             synchronized (mGlobalLockWithoutBoost) {
6304                 final WindowProcessController proc = mProcessNames.remove(name, uid);
6305                 if (proc != null && !proc.mHasEverAttached
6306                         && !mStartingProcessActivities.isEmpty()) {
6307                     // Use a copy in case finishIfPossible changes the list indirectly.
6308                     final ArrayList<ActivityRecord> activities =
6309                             new ArrayList<>(mStartingProcessActivities);
6310                     for (int i = activities.size() - 1; i >= 0; i--) {
6311                         final ActivityRecord r = activities.get(i);
6312                         if (uid == r.info.applicationInfo.uid && name.equals(r.processName)) {
6313                             Slog.w(TAG, proc + " is removed with pending start " + r);
6314                             mStartingProcessActivities.remove(r);
6315                             // If visible, finish it to avoid getting stuck on screen.
6316                             if (r.isVisibleRequested()) {
6317                                 r.finishIfPossible("starting-proc-removed", false /* oomAdj */);
6318                             }
6319                         }
6320                     }
6321                 }
6322             }
6323         }
6324 
6325         @HotPath(caller = HotPath.PROCESS_CHANGE)
6326         @Override
onCleanUpApplicationRecord(WindowProcessController proc)6327         public void onCleanUpApplicationRecord(WindowProcessController proc) {
6328             synchronized (mGlobalLockWithoutBoost) {
6329                 if (proc == mHomeProcess) {
6330                     mHomeProcess = null;
6331                 }
6332                 if (proc == mPreviousProcess) {
6333                     mPreviousProcess = null;
6334                 }
6335             }
6336         }
6337 
6338         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
6339         @Override
getTopProcessState()6340         public int getTopProcessState() {
6341             if (mRetainPowerModeAndTopProcessState) {
6342                 // There is a launching app while device may be sleeping, force the top state so
6343                 // the launching process can have top-app scheduling group.
6344                 return ActivityManager.PROCESS_STATE_TOP;
6345             }
6346             return mTopProcessState;
6347         }
6348 
6349         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
6350         @Override
useTopSchedGroupForTopProcess()6351         public boolean useTopSchedGroupForTopProcess() {
6352             // If it is non-zero, there may be a more important UI/animation than the top app.
6353             return mDemoteTopAppReasons == 0;
6354         }
6355 
6356         @HotPath(caller = HotPath.PROCESS_CHANGE)
6357         @Override
clearHeavyWeightProcessIfEquals(WindowProcessController proc)6358         public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6359             synchronized (mGlobalLockWithoutBoost) {
6360                 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6361             }
6362         }
6363 
6364         @Override
finishHeavyWeightApp()6365         public void finishHeavyWeightApp() {
6366             synchronized (mGlobalLock) {
6367                 if (mHeavyWeightProcess != null) {
6368                     mHeavyWeightProcess.finishActivities();
6369                 }
6370                 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6371                         mHeavyWeightProcess);
6372             }
6373         }
6374 
6375         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
6376         @Override
isSleeping()6377         public boolean isSleeping() {
6378             return mSleeping;
6379         }
6380 
6381         @Override
isShuttingDown()6382         public boolean isShuttingDown() {
6383             return mShuttingDown;
6384         }
6385 
6386         @Override
shuttingDown(boolean booted, int timeout)6387         public boolean shuttingDown(boolean booted, int timeout) {
6388             mShuttingDown = true;
6389             mWindowManager.mSnapshotController.mTaskSnapshotController.prepareShutdown();
6390             synchronized (mGlobalLock) {
6391                 mRootWindowContainer.prepareForShutdown();
6392                 updateEventDispatchingLocked(booted);
6393                 notifyTaskPersisterLocked(null, true);
6394                 return mTaskSupervisor.shutdownLocked(timeout);
6395             }
6396         }
6397 
6398         @Override
enableScreenAfterBoot(boolean booted)6399         public void enableScreenAfterBoot(boolean booted) {
6400             writeBootProgressEnableScreen(SystemClock.uptimeMillis());
6401             mWindowManager.enableScreenAfterBoot();
6402             synchronized (mGlobalLock) {
6403                 updateEventDispatchingLocked(booted);
6404             }
6405         }
6406 
6407         @Override
showStrictModeViolationDialog()6408         public boolean showStrictModeViolationDialog() {
6409             synchronized (mGlobalLock) {
6410                 return mShowDialogs && !mSleeping && !mShuttingDown;
6411             }
6412         }
6413 
6414         @Override
showSystemReadyErrorDialogsIfNeeded()6415         public void showSystemReadyErrorDialogsIfNeeded() {
6416             if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6417                 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "showSystemReadyErrorDialogs");
6418             }
6419             // Pull the check for build consistency outside the lock, to avoid holding the lock for
6420             // too long, given that `Build.isBuildConsistent()` takes relatively long.
6421             boolean isBuildConsistent = Build.isBuildConsistent();
6422             synchronized (mGlobalLock) {
6423                 try {
6424                     if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6425                         Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6426                                 + " data partition or your device will be unstable.");
6427                         mUiHandler.post(() -> {
6428                             if (mShowDialogs) {
6429                                 AlertDialog d = new BaseErrorDialog(mUiContext);
6430                                 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6431                                 d.setCancelable(false);
6432                                 d.setTitle(mUiContext.getText(R.string.android_system_label));
6433                                 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6434                                 d.setButton(DialogInterface.BUTTON_POSITIVE,
6435                                         mUiContext.getText(R.string.ok),
6436                                         mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6437                                 d.show();
6438                             }
6439                         });
6440                     }
6441                 } catch (RemoteException e) {
6442                 }
6443 
6444                 if (!isBuildConsistent) {
6445                     Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6446                     mUiHandler.post(() -> {
6447                         if (mShowDialogs) {
6448                             AlertDialog d = new BaseErrorDialog(mUiContext);
6449                             d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6450                             d.setCancelable(false);
6451                             d.setTitle(mUiContext.getText(R.string.android_system_label));
6452                             d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6453                             d.setButton(DialogInterface.BUTTON_POSITIVE,
6454                                     mUiContext.getText(R.string.ok),
6455                                     mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6456                             d.show();
6457                         }
6458                     });
6459                 }
6460             }
6461             Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6462         }
6463 
6464         @Override
onProcessMapped(int pid, WindowProcessController proc)6465         public void onProcessMapped(int pid, WindowProcessController proc) {
6466             synchronized (mGlobalLock) {
6467                 mProcessMap.put(pid, proc);
6468             }
6469         }
6470 
6471         @Override
onProcessUnMapped(int pid)6472         public void onProcessUnMapped(int pid) {
6473             synchronized (mGlobalLock) {
6474                 mProcessMap.remove(pid);
6475             }
6476         }
6477 
6478         @Override
onPackageDataCleared(String name, int userId)6479         public void onPackageDataCleared(String name, int userId) {
6480             synchronized (mGlobalLock) {
6481                 mCompatModePackages.handlePackageDataClearedLocked(name);
6482                 mAppWarnings.onPackageDataCleared(name, userId);
6483                 mPackageConfigPersister.onPackageDataCleared(name, userId);
6484             }
6485         }
6486 
6487         @Override
onPackageUninstalled(String name, int userId)6488         public void onPackageUninstalled(String name, int userId) {
6489             synchronized (mGlobalLock) {
6490                 mAppWarnings.onPackageUninstalled(name, userId);
6491                 mCompatModePackages.handlePackageUninstalledLocked(name);
6492                 mPackageConfigPersister.onPackageUninstall(name, userId);
6493             }
6494             mWindowStyleCache.invalidatePackage(name);
6495         }
6496 
6497         @Override
onPackageAdded(String name, boolean replacing)6498         public void onPackageAdded(String name, boolean replacing) {
6499             synchronized (mGlobalLock) {
6500                 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6501             }
6502         }
6503 
6504         @Override
onPackageReplaced(ApplicationInfo aInfo)6505         public void onPackageReplaced(ApplicationInfo aInfo) {
6506             synchronized (mGlobalLock) {
6507                 // In case if setWindowManager hasn't been called yet when booting.
6508                 if (mRootWindowContainer == null) return;
6509                 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
6510             }
6511             mWindowStyleCache.invalidatePackage(aInfo.packageName);
6512         }
6513 
6514         @Override
sendActivityResult(int callingUid, IBinder activityToken, String resultWho, int requestCode, int resultCode, Intent data)6515         public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6516                 int requestCode, int resultCode, Intent data) {
6517             final ActivityRecord r;
6518             synchronized (mGlobalLock) {
6519                 r = ActivityRecord.isInRootTaskLocked(activityToken);
6520                 if (r == null || r.getRootTask() == null) {
6521                     return;
6522                 }
6523             }
6524 
6525             // Carefully collect grants without holding lock
6526             final NeededUriGrants dataGrants = collectGrants(data, r);
6527 
6528             synchronized (mGlobalLock) {
6529                 r.sendResult(callingUid, resultWho, requestCode, resultCode, data, new Binder(),
6530                         dataGrants);
6531             }
6532         }
6533 
6534         @Override
clearPendingResultForActivity(IBinder activityToken, WeakReference<PendingIntentRecord> pir)6535         public void clearPendingResultForActivity(IBinder activityToken,
6536                 WeakReference<PendingIntentRecord> pir) {
6537             synchronized (mGlobalLock) {
6538                 final ActivityRecord r = ActivityRecord.isInRootTaskLocked(activityToken);
6539                 if (r != null && r.pendingResults != null) {
6540                     r.pendingResults.remove(pir);
6541                 }
6542             }
6543         }
6544 
6545         @Override
getActivityName(IBinder activityToken)6546         public ComponentName getActivityName(IBinder activityToken) {
6547             synchronized (mGlobalLock) {
6548                 final ActivityRecord r = ActivityRecord.isInRootTaskLocked(activityToken);
6549                 return r != null ? r.intent.getComponent() : null;
6550             }
6551         }
6552 
6553         @Override
getAttachedNonFinishingActivityForTask(int taskId, IBinder token)6554         public ActivityTokens getAttachedNonFinishingActivityForTask(int taskId,
6555                 IBinder token) {
6556             synchronized (mGlobalLock) {
6557                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
6558                         MATCH_ATTACHED_TASK_ONLY);
6559                 if (task == null) {
6560                     Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6561                             + " Requested task not found");
6562                     return null;
6563                 }
6564                 final List<ActivityRecord> list = new ArrayList<>();
6565                 task.forAllActivities(r -> {
6566                     if (!r.finishing) {
6567                         list.add(r);
6568                     }
6569                 });
6570                 if (list.size() <= 0) {
6571                     return null;
6572                 }
6573                 // pass null, get top Activity
6574                 if (token == null && list.get(0).attachedToProcess()) {
6575                     ActivityRecord topRecord = list.get(0);
6576                     return new ActivityTokens(topRecord.token, topRecord.assistToken,
6577                             topRecord.app.getThread(), topRecord.shareableActivityToken,
6578                             topRecord.getUid());
6579                 }
6580                 // find the expected Activity
6581                 for (int i = 0; i < list.size(); i++) {
6582                     ActivityRecord record = list.get(i);
6583                     if (record.shareableActivityToken == token && record.attachedToProcess()) {
6584                         return new ActivityTokens(record.token, record.assistToken,
6585                                 record.app.getThread(), record.shareableActivityToken,
6586                                 record.getUid());
6587                     }
6588                 }
6589                 return null;
6590             }
6591         }
6592 
6593         @Override
getIntentSender(int type, String packageName, @Nullable String featureId, int callingUid, int userId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions)6594         public IIntentSender getIntentSender(int type, String packageName,
6595                 @Nullable String featureId, int callingUid, int userId, IBinder token,
6596                 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6597                 int flags, Bundle bOptions) {
6598             synchronized (mGlobalLock) {
6599                 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6600                         token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6601             }
6602         }
6603 
6604         @Override
getServiceConnectionsHolder(IBinder token)6605         public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6606             final ActivityRecord r = ActivityRecord.forToken(token);
6607             if (r == null || !r.inHistory) {
6608                 return null;
6609             }
6610             return r.getOrCreateServiceConnectionsHolder();
6611         }
6612 
6613         @Override
getHomeIntent()6614         public Intent getHomeIntent() {
6615             synchronized (mGlobalLock) {
6616                 return ActivityTaskManagerService.this.getHomeIntent();
6617             }
6618         }
6619 
6620         @Override
startHomeActivity(int userId, String reason)6621         public boolean startHomeActivity(int userId, String reason) {
6622             synchronized (mGlobalLock) {
6623                 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6624             }
6625         }
6626 
6627         @Override
startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting, boolean fromHomeKey)6628         public boolean startHomeOnDisplay(int userId, String reason, int displayId,
6629                 boolean allowInstrumenting, boolean fromHomeKey) {
6630             synchronized (mGlobalLock) {
6631                 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
6632                         allowInstrumenting, fromHomeKey);
6633             }
6634         }
6635 
6636         @Override
startHomeOnAllDisplays(int userId, String reason)6637         public boolean startHomeOnAllDisplays(int userId, String reason) {
6638             synchronized (mGlobalLock) {
6639                 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
6640             }
6641         }
6642 
6643         @Override
updateTopComponentForFactoryTest()6644         public void updateTopComponentForFactoryTest() {
6645             synchronized (mGlobalLock) {
6646                 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6647                     return;
6648                 }
6649                 final ResolveInfo ri = mContext.getPackageManager()
6650                         .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6651                 final CharSequence errorMsg;
6652                 if (ri != null) {
6653                     final ActivityInfo ai = ri.activityInfo;
6654                     final ApplicationInfo app = ai.applicationInfo;
6655                     if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6656                         mTopAction = Intent.ACTION_FACTORY_TEST;
6657                         mTopData = null;
6658                         mTopComponent = new ComponentName(app.packageName, ai.name);
6659                         errorMsg = null;
6660                     } else {
6661                         errorMsg = mContext.getResources().getText(
6662                                 com.android.internal.R.string.factorytest_not_system);
6663                     }
6664                 } else {
6665                     errorMsg = mContext.getResources().getText(
6666                             com.android.internal.R.string.factorytest_no_action);
6667                 }
6668                 if (errorMsg == null) {
6669                     return;
6670                 }
6671 
6672                 mTopAction = null;
6673                 mTopData = null;
6674                 mTopComponent = null;
6675                 mUiHandler.post(() -> {
6676                     Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6677                     d.show();
6678                     mAmInternal.ensureBootCompleted();
6679                 });
6680             }
6681         }
6682 
6683         @HotPath(caller = HotPath.PROCESS_CHANGE)
6684         @Override
handleAppDied(WindowProcessController wpc, boolean restarting, Runnable finishInstrumentationCallback)6685         public void handleAppDied(WindowProcessController wpc, boolean restarting,
6686                 Runnable finishInstrumentationCallback) {
6687             synchronized (mGlobalLockWithoutBoost) {
6688                 mTaskSupervisor.beginDeferResume();
6689                 final boolean hasVisibleActivities;
6690                 try {
6691                     // Remove this application's activities from active lists.
6692                     hasVisibleActivities = wpc.handleAppDied();
6693                 } finally {
6694                     mTaskSupervisor.endDeferResume();
6695                 }
6696 
6697                 if (!restarting && hasVisibleActivities) {
6698                     deferWindowLayout();
6699                     try {
6700                         mRootWindowContainer.ensureVisibilityOnVisibleActivityDiedOrCrashed(
6701                                 "handleAppDied");
6702                     } finally {
6703                         continueWindowLayout();
6704                     }
6705                 }
6706             }
6707             if (wpc.isInstrumenting()) {
6708                 finishInstrumentationCallback.run();
6709             }
6710         }
6711 
6712         @Override
closeSystemDialogs(String reason)6713         public void closeSystemDialogs(String reason) {
6714             enforceNotIsolatedCaller("closeSystemDialogs");
6715             final int pid = Binder.getCallingPid();
6716             final int uid = Binder.getCallingUid();
6717             if (!checkCanCloseSystemDialogs(pid, uid, null)) {
6718                 return;
6719             }
6720 
6721             final long origId = Binder.clearCallingIdentity();
6722             try {
6723                 synchronized (mGlobalLock) {
6724                     // Only allow this from foreground processes, so that background
6725                     // applications can't abuse it to prevent system UI from being shown.
6726                     if (uid >= FIRST_APPLICATION_UID) {
6727                         final WindowProcessController proc = mProcessMap.getProcess(pid);
6728                         if (!proc.isPerceptible()) {
6729                             Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6730                                     + " from background process " + proc);
6731                             return;
6732                         }
6733                     }
6734                     mWindowManager.closeSystemDialogs(reason);
6735 
6736                     mRootWindowContainer.closeSystemDialogActivities(reason);
6737                 }
6738                 // Call into AM outside the synchronized block.
6739                 mAmInternal.broadcastCloseSystemDialogs(reason);
6740             } finally {
6741                 Binder.restoreCallingIdentity(origId);
6742             }
6743         }
6744 
6745         @Override
cleanupDisabledPackageComponents( String packageName, Set<String> disabledClasses, int userId, boolean booted)6746         public void cleanupDisabledPackageComponents(
6747                 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6748             synchronized (mGlobalLock) {
6749                 // In case if setWindowManager hasn't been called yet when booting.
6750                 if (mRootWindowContainer == null) return;
6751                 // Clean-up disabled activities.
6752                 if (mRootWindowContainer.finishDisabledPackageActivities(
6753                         packageName, disabledClasses, true /* doit */, false /* evenPersistent */,
6754                         userId, false /* onlyRemoveNoProcess */) && booted) {
6755                     mRootWindowContainer.resumeFocusedTasksTopActivities();
6756                     mTaskSupervisor.scheduleIdle();
6757                 }
6758 
6759                 // Clean-up disabled tasks
6760                 getRecentTasks().cleanupDisabledPackageTasksLocked(
6761                         packageName, disabledClasses, userId);
6762             }
6763         }
6764 
6765         @Override
onForceStopPackage(String packageName, boolean doit, boolean evenPersistent, int userId)6766         public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6767                 int userId) {
6768             synchronized (mGlobalLock) {
6769                 // In case if setWindowManager hasn't been called yet when booting.
6770                 if (mRootWindowContainer == null) return false;
6771                 return mRootWindowContainer.finishDisabledPackageActivities(packageName,
6772                         null /* filterByClasses */, doit, evenPersistent, userId,
6773                         // Only remove the activities without process because the activities with
6774                         // attached process will be removed when handling process died with
6775                         // WindowProcessController#isRemoved == true.
6776                         true /* onlyRemoveNoProcess */);
6777             }
6778         }
6779 
6780         @Override
resumeTopActivities(boolean scheduleIdle)6781         public void resumeTopActivities(boolean scheduleIdle) {
6782             synchronized (mGlobalLock) {
6783                 mRootWindowContainer.resumeFocusedTasksTopActivities();
6784                 if (scheduleIdle) {
6785                     mTaskSupervisor.scheduleIdle();
6786                 }
6787             }
6788         }
6789 
6790         @HotPath(caller = HotPath.PROCESS_CHANGE)
6791         @Override
preBindApplication(WindowProcessController wpc, ApplicationInfo info)6792         public PreBindInfo preBindApplication(WindowProcessController wpc, ApplicationInfo info) {
6793             synchronized (mGlobalLockWithoutBoost) {
6794                 mTaskSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6795                 wpc.onConfigurationChanged(getGlobalConfiguration());
6796                 // Let the application initialize with consistent configuration as its activity.
6797                 for (int i = mStartingProcessActivities.size() - 1; i >= 0; i--) {
6798                     final ActivityRecord r = mStartingProcessActivities.get(i);
6799                     if (wpc.mUid == r.info.applicationInfo.uid && wpc.mName.equals(r.processName)) {
6800                         wpc.registerActivityConfigurationListener(r);
6801                         break;
6802                     }
6803                 }
6804                 ProtoLog.v(WM_DEBUG_CONFIGURATION, "Binding proc %s with config %s",
6805                         wpc.mName, wpc.getConfiguration());
6806                 // The "info" can be the target of instrumentation.
6807                 return new PreBindInfo(compatibilityInfoForPackageLocked(info),
6808                         new Configuration(wpc.getConfiguration()));
6809             }
6810         }
6811 
6812         @HotPath(caller = HotPath.PROCESS_CHANGE)
6813         @Override
attachApplication(WindowProcessController wpc)6814         public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6815             synchronized (mGlobalLockWithoutBoost) {
6816                 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6817                     Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6818                 }
6819                 try {
6820                     return mRootWindowContainer.attachApplication(wpc);
6821                 } finally {
6822                     Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6823                 }
6824             }
6825         }
6826 
6827         @Override
notifyLockedProfile(@serIdInt int userId)6828         public void notifyLockedProfile(@UserIdInt int userId) {
6829             try {
6830                 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6831                     throw new SecurityException("Only privileged app can call notifyLockedProfile");
6832                 }
6833             } catch (RemoteException ex) {
6834                 throw new SecurityException("Fail to check is caller a privileged app", ex);
6835             }
6836 
6837             synchronized (mGlobalLock) {
6838                 final long ident = Binder.clearCallingIdentity();
6839                 try {
6840                     if (mAmInternal.shouldConfirmCredentials(userId)) {
6841                         maybeHideLockedProfileActivityLocked();
6842                         mRootWindowContainer.lockAllProfileTasks(userId);
6843                     }
6844                 } finally {
6845                     Binder.restoreCallingIdentity(ident);
6846                 }
6847             }
6848         }
6849 
6850         @Override
startConfirmDeviceCredentialIntent(Intent intent, Bundle options)6851         public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6852             enforceTaskPermission("startConfirmDeviceCredentialIntent");
6853 
6854             synchronized (mGlobalLock) {
6855                 final long ident = Binder.clearCallingIdentity();
6856                 try {
6857                     intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6858                     final ActivityOptions activityOptions = options != null
6859                             ? new ActivityOptions(options) : ActivityOptions.makeBasic();
6860                     mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6861                             UserHandle.CURRENT);
6862                 } finally {
6863                     Binder.restoreCallingIdentity(ident);
6864                 }
6865             }
6866         }
6867 
6868         @Override
writeActivitiesToProto(ProtoOutputStream proto)6869         public void writeActivitiesToProto(ProtoOutputStream proto) {
6870             synchronized (mGlobalLock) {
6871                 // The output proto of "activity --proto activities"
6872                 mRootWindowContainer.dumpDebug(
6873                         proto, ROOT_WINDOW_CONTAINER, WindowTracingLogLevel.ALL);
6874             }
6875         }
6876 
6877         @Override
dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter)6878         public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6879                 boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter) {
6880             synchronized (mGlobalLock) {
6881                 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6882                     dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
6883                             displayIdFilter);
6884                 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6885                     dumpLastANRLocked(pw);
6886                 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6887                     dumpLastANRTracesLocked(pw);
6888                 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6889                     dumpActivityStarterLocked(pw, dumpPackage);
6890                 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6891                     dumpActivityContainersLocked(pw);
6892                 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6893                     if (getRecentTasks() != null) {
6894                         getRecentTasks().dump(pw, dumpAll, dumpPackage);
6895                     }
6896                 } else if (DUMP_TOP_RESUMED_ACTIVITY.equals(cmd)) {
6897                     dumpTopResumedActivityLocked(pw);
6898                 } else if (DUMP_VISIBLE_ACTIVITIES.equals(cmd)) {
6899                     dumpVisibleActivitiesLocked(pw, displayIdFilter);
6900                 }
6901             }
6902         }
6903 
6904         @Override
dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode, int wakefulness)6905         public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6906                 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6907                 int wakefulness) {
6908             synchronized (mGlobalLock) {
6909                 if (mHomeProcess != null && (dumpPackage == null
6910                         || mHomeProcess.containsPackage(dumpPackage))) {
6911                     if (needSep) {
6912                         pw.println();
6913                         needSep = false;
6914                     }
6915                     pw.println("  mHomeProcess: " + mHomeProcess);
6916                 }
6917                 if (mPreviousProcess != null && (dumpPackage == null
6918                         || mPreviousProcess.containsPackage(dumpPackage))) {
6919                     if (needSep) {
6920                         pw.println();
6921                         needSep = false;
6922                     }
6923                     pw.println("  mPreviousProcess: " + mPreviousProcess);
6924                 }
6925                 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6926                         || mPreviousProcess.containsPackage(dumpPackage))) {
6927                     StringBuilder sb = new StringBuilder(128);
6928                     sb.append("  mPreviousProcessVisibleTime: ");
6929                     TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6930                     pw.println(sb);
6931                 }
6932                 if (mHeavyWeightProcess != null && (dumpPackage == null
6933                         || mHeavyWeightProcess.containsPackage(dumpPackage))) {
6934                     if (needSep) {
6935                         pw.println();
6936                         needSep = false;
6937                     }
6938                     pw.println("  mHeavyWeightProcess: " + mHeavyWeightProcess);
6939                 }
6940                 if (dumpPackage == null) {
6941                     pw.println("  mGlobalConfiguration: " + getGlobalConfiguration());
6942                     mRootWindowContainer.dumpDisplayConfigs(pw, "  ");
6943                 }
6944                 if (dumpAll) {
6945                     final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
6946                     if (dumpPackage == null && topFocusedRootTask != null) {
6947                         pw.println("  mConfigWillChange: " + topFocusedRootTask.mConfigWillChange);
6948                     }
6949                     if (mCompatModePackages.getPackages().size() > 0) {
6950                         boolean printed = false;
6951                         for (Map.Entry<String, Integer> entry
6952                                 : mCompatModePackages.getPackages().entrySet()) {
6953                             String pkg = entry.getKey();
6954                             int mode = entry.getValue();
6955                             if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6956                                 continue;
6957                             }
6958                             if (!printed) {
6959                                 pw.println("  mScreenCompatPackages:");
6960                                 printed = true;
6961                             }
6962                             pw.println("    " + pkg + ": " + mode);
6963                         }
6964                     }
6965                 }
6966 
6967                 if (dumpPackage == null) {
6968                     pw.println("  mWakefulness="
6969                             + PowerManagerInternal.wakefulnessToString(wakefulness));
6970                     pw.println("  mSleepTokens=" + mRootWindowContainer.mSleepTokens);
6971                     if (mRunningVoice != null) {
6972                         pw.println("  mRunningVoice=" + mRunningVoice);
6973                         pw.println("  mVoiceWakeLock" + mVoiceWakeLock);
6974                     }
6975                     pw.println("  mSleeping=" + mSleeping);
6976                     pw.println("  mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6977                     pw.println("  mVrController=" + mVrController);
6978                 }
6979                 if (mCurAppTimeTracker != null) {
6980                     mCurAppTimeTracker.dumpWithHeader(pw, "  ", true);
6981                 }
6982                 if (mAllowAppSwitchUids.size() > 0) {
6983                     boolean printed = false;
6984                     for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6985                         ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6986                         for (int j = 0; j < types.size(); j++) {
6987                             if (dumpPackage == null ||
6988                                     UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6989                                 if (needSep) {
6990                                     pw.println();
6991                                     needSep = false;
6992                                 }
6993                                 if (!printed) {
6994                                     pw.println("  mAllowAppSwitchUids:");
6995                                     printed = true;
6996                                 }
6997                                 pw.print("    User ");
6998                                 pw.print(mAllowAppSwitchUids.keyAt(i));
6999                                 pw.print(": Type ");
7000                                 pw.print(types.keyAt(j));
7001                                 pw.print(" = ");
7002                                 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7003                                 pw.println();
7004                             }
7005                         }
7006                     }
7007                 }
7008                 if (dumpPackage == null) {
7009                     if (mController != null) {
7010                         pw.println("  mController=" + mController
7011                                 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7012                     }
7013                     pw.println("  mGoingToSleepWakeLock=" + mTaskSupervisor.mGoingToSleepWakeLock);
7014                     pw.println("  mLaunchingActivityWakeLock="
7015                             + mTaskSupervisor.mLaunchingActivityWakeLock);
7016                 }
7017 
7018                 return needSep;
7019             }
7020         }
7021 
7022         @Override
writeProcessesToProto(ProtoOutputStream proto, String dumpPackage, int wakeFullness, boolean testPssMode)7023         public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7024                 int wakeFullness, boolean testPssMode) {
7025             synchronized (mGlobalLock) {
7026                 if (dumpPackage == null) {
7027                     getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
7028                     final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
7029                     if (topFocusedRootTask != null) {
7030                         proto.write(CONFIG_WILL_CHANGE, topFocusedRootTask.mConfigWillChange);
7031                     }
7032                     writeSleepStateToProto(proto, wakeFullness, testPssMode);
7033                     if (mRunningVoice != null) {
7034                         final long vrToken = proto.start(
7035                                 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7036                         proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7037                                 mRunningVoice.toString());
7038                         mVoiceWakeLock.dumpDebug(
7039                                 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7040                         proto.end(vrToken);
7041                     }
7042                     mVrController.dumpDebug(proto,
7043                             ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
7044                     if (mController != null) {
7045                         final long token = proto.start(CONTROLLER);
7046                         proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7047                                 mController.toString());
7048                         proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7049                         proto.end(token);
7050                     }
7051                     mTaskSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7052                     mTaskSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
7053                             LAUNCHING_ACTIVITY);
7054                 }
7055 
7056                 if (mHomeProcess != null && (dumpPackage == null
7057                         || mHomeProcess.containsPackage(dumpPackage))) {
7058                     mHomeProcess.dumpDebug(proto, HOME_PROC);
7059                 }
7060 
7061                 if (mPreviousProcess != null && (dumpPackage == null
7062                         || mPreviousProcess.containsPackage(dumpPackage))) {
7063                     mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
7064                     proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7065                 }
7066 
7067                 if (mHeavyWeightProcess != null && (dumpPackage == null
7068                         || mHeavyWeightProcess.containsPackage(dumpPackage))) {
7069                     mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
7070                 }
7071 
7072                 for (Map.Entry<String, Integer> entry
7073                         : mCompatModePackages.getPackages().entrySet()) {
7074                     String pkg = entry.getKey();
7075                     int mode = entry.getValue();
7076                     if (dumpPackage == null || dumpPackage.equals(pkg)) {
7077                         long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7078                         proto.write(PACKAGE, pkg);
7079                         proto.write(MODE, mode);
7080                         proto.end(compatToken);
7081                     }
7082                 }
7083 
7084                 if (mCurAppTimeTracker != null) {
7085                     mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
7086                 }
7087 
7088             }
7089         }
7090 
7091         @Override
dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly, boolean dumpFocusedRootTaskOnly, int displayIdFilter, @UserIdInt int userId)7092         public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7093                 String[] args, int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly,
7094                 boolean dumpFocusedRootTaskOnly, int displayIdFilter,
7095                 @UserIdInt int userId) {
7096             return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7097                     dumpVisibleRootTasksOnly, dumpFocusedRootTaskOnly, displayIdFilter, userId,
7098                     /* timeout= */ 5000);
7099         }
7100 
7101         @Override
dumpForOom(PrintWriter pw)7102         public void dumpForOom(PrintWriter pw) {
7103             synchronized (mGlobalLock) {
7104                 pw.println("  mHomeProcess: " + mHomeProcess);
7105                 pw.println("  mPreviousProcess: " + mPreviousProcess);
7106                 if (mHeavyWeightProcess != null) {
7107                     pw.println("  mHeavyWeightProcess: " + mHeavyWeightProcess);
7108                 }
7109             }
7110         }
7111 
7112         @Override
canGcNow()7113         public boolean canGcNow() {
7114             synchronized (mGlobalLock) {
7115                 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
7116             }
7117         }
7118 
7119         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
7120         @Override
getTopApp()7121         public WindowProcessController getTopApp() {
7122             return mTopApp;
7123         }
7124 
7125         @Override
scheduleDestroyAllActivities(String reason)7126         public void scheduleDestroyAllActivities(String reason) {
7127             synchronized (mGlobalLock) {
7128                 mRootWindowContainer.scheduleDestroyAllActivities(reason);
7129             }
7130         }
7131 
7132         @Override
removeUser(int userId)7133         public void removeUser(int userId) {
7134             synchronized (mGlobalLock) {
7135                 mRootWindowContainer.removeUser(userId);
7136                 mPackageConfigPersister.removeUser(userId);
7137             }
7138         }
7139 
7140         @Override
switchUser(int userId, UserState userState)7141         public boolean switchUser(int userId, UserState userState) {
7142             synchronized (mGlobalLock) {
7143                 return mRootWindowContainer.switchUser(userId, userState);
7144             }
7145         }
7146 
7147         @Override
onHandleAppCrash(@onNull WindowProcessController wpc)7148         public void onHandleAppCrash(@NonNull WindowProcessController wpc) {
7149             synchronized (mGlobalLock) {
7150                 final boolean hasVisibleActivity;
7151                 mTaskSupervisor.beginDeferResume();
7152                 try {
7153                     hasVisibleActivity = wpc.handleAppCrash();
7154                 } finally {
7155                     mTaskSupervisor.endDeferResume();
7156                 }
7157 
7158                 if (hasVisibleActivity) {
7159                     deferWindowLayout();
7160                     try {
7161                         mRootWindowContainer.ensureVisibilityOnVisibleActivityDiedOrCrashed(
7162                                 "onHandleAppCrash");
7163                     } finally {
7164                         continueWindowLayout();
7165                     }
7166                 }
7167             }
7168         }
7169 
7170         @Override
finishTopCrashedActivities(WindowProcessController crashedApp, String reason)7171         public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7172             synchronized (mGlobalLock) {
7173                 deferWindowLayout();
7174                 try {
7175                     final Task finishedTask = mRootWindowContainer.finishTopCrashedActivities(
7176                             crashedApp, reason);
7177                     if (finishedTask != null) {
7178                         mRootWindowContainer.ensureVisibilityOnVisibleActivityDiedOrCrashed(reason);
7179                         return finishedTask.mTaskId;
7180                     }
7181                     return INVALID_TASK_ID;
7182                 } finally {
7183                     continueWindowLayout();
7184                 }
7185             }
7186         }
7187 
7188         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
7189         @Override
onUidActive(int uid, int procState)7190         public void onUidActive(int uid, int procState) {
7191             mActiveUids.onUidActive(uid, procState);
7192         }
7193 
7194         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
7195         @Override
onUidInactive(int uid)7196         public void onUidInactive(int uid) {
7197             mActiveUids.onUidInactive(uid);
7198         }
7199 
7200         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
7201         @Override
onUidProcStateChanged(int uid, int procState)7202         public void onUidProcStateChanged(int uid, int procState) {
7203             mActiveUids.onUidProcStateChanged(uid, procState);
7204         }
7205 
7206         @Override
handleAppCrashInActivityController(String processName, int pid, String shortMsg, String longMsg, long timeMillis, String stackTrace, Runnable killCrashingAppCallback)7207         public boolean handleAppCrashInActivityController(String processName, int pid,
7208                 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7209                 Runnable killCrashingAppCallback) {
7210             Runnable targetRunnable = null;
7211             synchronized (mGlobalLock) {
7212                 if (mController == null) {
7213                     return false;
7214                 }
7215 
7216                 try {
7217                     if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7218                             stackTrace)) {
7219                         targetRunnable = killCrashingAppCallback;
7220                     }
7221                 } catch (RemoteException e) {
7222                     mController = null;
7223                     Watchdog.getInstance().setActivityController(null);
7224                 }
7225             }
7226             if (targetRunnable != null) {
7227                 targetRunnable.run();
7228                 return true;
7229             }
7230             return false;
7231         }
7232 
7233         @Override
removeRecentTasksByPackageName(String packageName, int userId)7234         public void removeRecentTasksByPackageName(String packageName, int userId) {
7235             synchronized (mGlobalLock) {
7236                 mRecentTasks.removeTasksByPackageName(packageName, userId);
7237             }
7238         }
7239 
7240         @Override
cleanupRecentTasksForUser(int userId)7241         public void cleanupRecentTasksForUser(int userId) {
7242             synchronized (mGlobalLock) {
7243                 mRecentTasks.cleanupLocked(userId);
7244             }
7245         }
7246 
7247         @Override
loadRecentTasksForUser(int userId)7248         public void loadRecentTasksForUser(int userId) {
7249             // This runs on android.fg thread when the user is unlocking.
7250             mRecentTasks.loadRecentTasksIfNeeded(userId);
7251             mPackageConfigPersister.loadUserPackages(userId);
7252         }
7253 
7254         @Override
onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId)7255         public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7256             synchronized (mGlobalLock) {
7257                 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7258             }
7259         }
7260 
7261         @Override
flushRecentTasks()7262         public void flushRecentTasks() {
7263             mRecentTasks.flush();
7264         }
7265 
7266         @Override
clearLockedTasks(String reason)7267         public void clearLockedTasks(String reason) {
7268             synchronized (mGlobalLock) {
7269                 getLockTaskController().clearLockedTasks(reason);
7270             }
7271         }
7272 
7273         @Override
updateUserConfiguration()7274         public void updateUserConfiguration() {
7275             synchronized (mGlobalLock) {
7276                 final Configuration configuration = new Configuration(getGlobalConfiguration());
7277                 final int currentUserId = mAmInternal.getCurrentUserId();
7278                 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7279                         configuration, currentUserId, Settings.System.canWrite(mContext));
7280                 updateConfigurationLocked(configuration, null /* starting */,
7281                         false /* initLocale */, false /* persistent */, currentUserId,
7282                         false /* deferResume */);
7283             }
7284         }
7285 
7286         @Override
canShowErrorDialogs(int userId)7287         public boolean canShowErrorDialogs(int userId) {
7288             synchronized (mGlobalLock) {
7289                 final boolean showDialogs = mShowDialogs
7290                         || shouldShowDialogsForVisibleBackgroundUserLocked(userId);
7291                 final UserInfo userInfo = getUserManager().getUserInfo(userId);
7292                 if (userInfo == null) {
7293                     // Unable to retrieve user information. Returning false, assuming there is
7294                     // no valid user with the given id.
7295                     return false;
7296                 }
7297                 return showDialogs && !mSleeping && !mShuttingDown
7298                         && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7299                         && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS, userId)
7300                         && !(UserManager.isDeviceInDemoMode(mContext)
7301                         && userInfo.isDemo());
7302             }
7303         }
7304 
7305         /**
7306          * In a car environment, {@link ActivityTaskManagerService#mShowDialogs} is always set to
7307          * {@code false} from {@link ActivityTaskManagerService#updateShouldShowDialogsLocked}
7308          * because its UI mode is {@link Configuration#UI_MODE_TYPE_CAR}. Thus, error dialogs are
7309          * not displayed when an ANR or a crash occurs. However, in the automotive multi-user
7310          * multi-display environment, this can confuse the passenger users and leave them
7311          * uninformed when an app is terminated by the ANR or crash without any notification.
7312          * To address this, error dialogs are allowed for the passenger users who have UI access
7313          * on assigned displays (a.k.a. visible background users) on devices that have
7314          * config_multiuserVisibleBackgroundUsers enabled even though the UI mode is
7315          * {@link Configuration#UI_MODE_TYPE_CAR}.
7316          *
7317          * @see ActivityTaskManagerService#updateShouldShowDialogsLocked
7318          */
shouldShowDialogsForVisibleBackgroundUserLocked(int userId)7319         private boolean shouldShowDialogsForVisibleBackgroundUserLocked(int userId) {
7320             if (!mWindowManager.mUmInternal.isVisibleBackgroundFullUser(userId)) {
7321                 return false;
7322             }
7323             final int displayId = mWindowManager.mUmInternal.getMainDisplayAssignedToUser(userId);
7324             final DisplayContent dc = mRootWindowContainer.getDisplayContent(displayId);
7325             if (dc == null) {
7326                 return false;
7327             }
7328             return shouldShowDialogs(dc.getConfiguration(), /* checkUiMode= */ false);
7329         }
7330 
7331         @Override
setProfileApp(String profileApp)7332         public void setProfileApp(String profileApp) {
7333             synchronized (mGlobalLock) {
7334                 mProfileApp = profileApp;
7335             }
7336         }
7337 
7338         @Override
setProfileProc(WindowProcessController wpc)7339         public void setProfileProc(WindowProcessController wpc) {
7340             synchronized (mGlobalLock) {
7341                 mProfileProc = wpc;
7342             }
7343         }
7344 
7345         @Override
setProfilerInfo(ProfilerInfo profilerInfo)7346         public void setProfilerInfo(ProfilerInfo profilerInfo) {
7347             synchronized (mGlobalLock) {
7348                 mProfilerInfo = profilerInfo;
7349             }
7350         }
7351 
7352         @Override
getLaunchObserverRegistry()7353         public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7354             synchronized (mGlobalLock) {
7355                 return mTaskSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7356             }
7357         }
7358 
7359         @Nullable
7360         @Override
getUriPermissionOwnerForActivity(@onNull IBinder activityToken)7361         public IBinder getUriPermissionOwnerForActivity(@NonNull IBinder activityToken) {
7362             ActivityTaskManagerService.enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
7363             synchronized (mGlobalLock) {
7364                 ActivityRecord r = ActivityRecord.isInRootTaskLocked(activityToken);
7365                 return (r == null) ? null : r.getUriPermissionsLocked().getExternalToken();
7366             }
7367         }
7368 
7369         @Override
getTaskSnapshotBlocking( int taskId, boolean isLowResolution, @TaskSnapshot.ReferenceFlags int usage)7370         public TaskSnapshot getTaskSnapshotBlocking(
7371                 int taskId, boolean isLowResolution, @TaskSnapshot.ReferenceFlags int usage) {
7372             return ActivityTaskManagerService.this.getTaskSnapshotInner(
7373                     taskId, isLowResolution, usage);
7374         }
7375 
7376         @Override
isUidForeground(int uid)7377         public boolean isUidForeground(int uid) {
7378             return ActivityTaskManagerService.this.hasActiveVisibleWindow(uid);
7379         }
7380 
7381         @Override
setDeviceOwnerUid(int uid)7382         public void setDeviceOwnerUid(int uid) {
7383             synchronized (mGlobalLock) {
7384                 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
7385             }
7386         }
7387 
7388         @Override
setProfileOwnerUids(Set<Integer> uids)7389         public void setProfileOwnerUids(Set<Integer> uids) {
7390             synchronized (mGlobalLock) {
7391                 ActivityTaskManagerService.this.setProfileOwnerUids(uids);
7392             }
7393         }
7394 
7395         @Override
setCompanionAppUids(int userId, Set<Integer> companionAppUids)7396         public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) {
7397             synchronized (mGlobalLock) {
7398                 mCompanionAppUidsMap.put(userId, companionAppUids);
7399             }
7400         }
7401 
7402 
7403         @Override
isBaseOfLockedTask(String packageName)7404         public boolean isBaseOfLockedTask(String packageName) {
7405             synchronized (mGlobalLock) {
7406                 return getLockTaskController().isBaseOfLockedTask(packageName);
7407             }
7408         }
7409 
7410         @Override
isNoDisplay(String packageName, int theme, int userId)7411         public boolean isNoDisplay(String packageName, int theme, int userId) {
7412             if (!com.android.window.flags.Flags.cacheWindowStyle()) {
7413                 final AttributeCache.Entry ent = AttributeCache.instance()
7414                         .get(packageName, theme, R.styleable.Window, userId);
7415                 return ent != null
7416                         && ent.array.getBoolean(R.styleable.Window_windowNoDisplay, false);
7417             }
7418             final ActivityRecord.WindowStyle style = getWindowStyle(packageName, theme, userId);
7419             return style != null && style.noDisplay();
7420         }
7421 
7422         @Override
createPackageConfigurationUpdater()7423         public PackageConfigurationUpdater createPackageConfigurationUpdater() {
7424             return new PackageConfigurationUpdaterImpl(Binder.getCallingPid(),
7425                     ActivityTaskManagerService.this);
7426         }
7427 
7428         @Override
createPackageConfigurationUpdater( String packageName , int userId)7429         public PackageConfigurationUpdater createPackageConfigurationUpdater(
7430                 String packageName , int userId) {
7431             return new PackageConfigurationUpdaterImpl(packageName, userId,
7432                     ActivityTaskManagerService.this);
7433         }
7434 
7435         @Override
7436         @Nullable
getApplicationConfig(String packageName, int userId)7437         public ActivityTaskManagerInternal.PackageConfig getApplicationConfig(String packageName,
7438                 int userId) {
7439             return mPackageConfigPersister.findPackageConfiguration(packageName, userId);
7440         }
7441 
7442         @Override
hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage)7443         public boolean hasSystemAlertWindowPermission(int callingUid, int callingPid,
7444                 String callingPackage) {
7445             return ActivityTaskManagerService.this.hasSystemAlertWindowPermission(callingUid,
7446                     callingPid, callingPackage);
7447         }
7448 
7449         @Override
registerActivityStartInterceptor( @ctivityInterceptorCallback.OrderedId int id, ActivityInterceptorCallback callback)7450         public void registerActivityStartInterceptor(
7451                 @ActivityInterceptorCallback.OrderedId int id,
7452                 ActivityInterceptorCallback callback) {
7453             synchronized (mGlobalLock) {
7454                 if (mActivityInterceptorCallbacks.contains(id)) {
7455                     throw new IllegalArgumentException("Duplicate id provided: " + id);
7456                 }
7457                 if (callback == null) {
7458                     throw new IllegalArgumentException("The passed ActivityInterceptorCallback "
7459                             + "can not be null");
7460                 }
7461                 if (!ActivityInterceptorCallback.isValidOrderId(id)) {
7462                     throw new IllegalArgumentException(
7463                             "Provided id " + id + " is not in range of valid ids for system "
7464                                     + "services [" + SYSTEM_FIRST_ORDERED_ID + ","
7465                                     + SYSTEM_LAST_ORDERED_ID + "] nor in range of valid ids for "
7466                                     + "mainline module services [" + MAINLINE_FIRST_ORDERED_ID + ","
7467                                     + MAINLINE_LAST_ORDERED_ID + "]");
7468                 }
7469                 mActivityInterceptorCallbacks.put(id, callback);
7470             }
7471         }
7472 
7473         @Override
unregisterActivityStartInterceptor( @ctivityInterceptorCallback.OrderedId int id)7474         public void unregisterActivityStartInterceptor(
7475                 @ActivityInterceptorCallback.OrderedId int id) {
7476             synchronized (mGlobalLock) {
7477                 if (!mActivityInterceptorCallbacks.contains(id)) {
7478                     throw new IllegalArgumentException(
7479                             "ActivityInterceptorCallback with id (" + id + ") is not registered");
7480                 }
7481                 mActivityInterceptorCallbacks.remove(id);
7482             }
7483         }
7484 
7485         @Override
getMostRecentTaskFromBackground()7486         public ActivityManager.RecentTaskInfo getMostRecentTaskFromBackground() {
7487             List<ActivityManager.RunningTaskInfo> runningTaskInfoList = getTasks(1);
7488             ActivityManager.RunningTaskInfo runningTaskInfo;
7489             if (runningTaskInfoList.size() > 0) {
7490                 runningTaskInfo = runningTaskInfoList.get(0);
7491             } else {
7492                 Slog.i(TAG, "No running task found!");
7493                 return null;
7494             }
7495             // Get 2 most recent tasks.
7496             List<ActivityManager.RecentTaskInfo> recentTaskInfoList =
7497                     getRecentTasks(
7498                                     2,
7499                                     ActivityManager.RECENT_IGNORE_UNAVAILABLE,
7500                                     mContext.getUserId())
7501                             .getList();
7502             ActivityManager.RecentTaskInfo targetTask = null;
7503             for (ActivityManager.RecentTaskInfo info : recentTaskInfoList) {
7504                 // Find a recent task that is not the current running task on screen.
7505                 if (info.id != runningTaskInfo.id) {
7506                     targetTask = info;
7507                     break;
7508                 }
7509             }
7510             return targetTask;
7511         }
7512 
7513         @Override
getAppTasks(String pkgName, int uid)7514         public List<ActivityManager.AppTask> getAppTasks(String pkgName, int uid) {
7515             ArrayList<ActivityManager.AppTask> tasks = new ArrayList<>();
7516             List<IBinder> appTasks = ActivityTaskManagerService.this.getAppTasks(pkgName, uid);
7517             int numAppTasks = appTasks.size();
7518             for (int i = 0; i < numAppTasks; i++) {
7519                 tasks.add(new ActivityManager.AppTask(IAppTask.Stub.asInterface(appTasks.get(i))));
7520             }
7521             return tasks;
7522         }
7523 
7524         @Override
getTaskToShowPermissionDialogOn(String pkgName, int uid)7525         public int getTaskToShowPermissionDialogOn(String pkgName, int uid) {
7526             synchronized (ActivityTaskManagerService.this.mGlobalLock) {
7527                 return ActivityTaskManagerService.this.mRootWindowContainer
7528                         .getTaskToShowPermissionDialogOn(pkgName, uid);
7529             }
7530         }
7531 
7532         @Override
restartTaskActivityProcessIfVisible(int taskId, String packageName)7533         public void restartTaskActivityProcessIfVisible(int taskId, String packageName) {
7534             synchronized (ActivityTaskManagerService.this.mGlobalLock) {
7535                 final Task task =
7536                         ActivityTaskManagerService.this.mRootWindowContainer
7537                                 .anyTaskForId(taskId, MATCH_ATTACHED_TASK_ONLY);
7538                 if (task == null) {
7539                     Slog.w(TAG, "Failed to restart Activity. No task found for id: " + taskId);
7540                     return;
7541                 }
7542 
7543                 final ActivityRecord activity = task.getActivity(activityRecord -> {
7544                     return packageName.equals(activityRecord.packageName)
7545                             && !activityRecord.finishing;
7546                 });
7547 
7548                 if (activity == null) {
7549                     Slog.w(TAG, "Failed to restart Activity. No Activity found for package name: "
7550                             + packageName + " in task: " + taskId);
7551                     return;
7552                 }
7553 
7554                 activity.restartProcessIfVisible();
7555             }
7556         }
7557 
7558         /** Sets the task stack listener that gets callbacks when a task stack changes. */
7559         @Override
registerTaskStackListener(ITaskStackListener listener)7560         public void registerTaskStackListener(ITaskStackListener listener) {
7561             ActivityTaskManagerService.this.registerTaskStackListener(listener);
7562         }
7563 
7564         /** Unregister a task stack listener so that it stops receiving callbacks. */
7565         @Override
unregisterTaskStackListener(ITaskStackListener listener)7566         public void unregisterTaskStackListener(ITaskStackListener listener) {
7567             ActivityTaskManagerService.this.unregisterTaskStackListener(listener);
7568         }
7569 
7570         @Override
registerCompatScaleProvider(@ompatScaleProvider.CompatScaleModeOrderId int id, @NonNull CompatScaleProvider provider)7571         public void registerCompatScaleProvider(@CompatScaleProvider.CompatScaleModeOrderId int id,
7572                 @NonNull CompatScaleProvider provider) {
7573             ActivityTaskManagerService.this.registerCompatScaleProvider(id, provider);
7574         }
7575 
7576         @Override
unregisterCompatScaleProvider( @ompatScaleProvider.CompatScaleModeOrderId int id)7577         public void unregisterCompatScaleProvider(
7578                 @CompatScaleProvider.CompatScaleModeOrderId int id) {
7579             ActivityTaskManagerService.this.unregisterCompatScaleProvider(id);
7580         }
7581 
7582         @Override
isAssistDataAllowed()7583         public boolean isAssistDataAllowed() {
7584             return ActivityTaskManagerService.this.isAssistDataAllowed();
7585         }
7586 
7587         @Override
requestBackGesture()7588         public boolean requestBackGesture() {
7589             return mBackNavigationController.requestBackGesture();
7590         }
7591     }
7592 
7593     /** Cache the return value for {@link #isPip2ExperimentEnabled()} */
7594     private static Boolean sIsPip2ExperimentEnabled = null;
7595 
7596     /**
7597      * @return {@code true} if PiP2 implementation should be used. Besides the trunk stable flag,
7598      * system property can be used to override this read only flag during development.
7599      * It's currently limited to phone form factor, i.e., not enabled on ARC / TV.
7600      */
isPip2ExperimentEnabled()7601     static boolean isPip2ExperimentEnabled() {
7602         if (sIsPip2ExperimentEnabled == null) {
7603             final FeatureInfo arcFeature = SystemConfig.getInstance().getAvailableFeatures().get(
7604                     "org.chromium.arc");
7605             final FeatureInfo tvFeature = SystemConfig.getInstance().getAvailableFeatures().get(
7606                     FEATURE_LEANBACK);
7607             final boolean isArc = arcFeature != null && arcFeature.version >= 0;
7608             final boolean isTv = tvFeature != null && tvFeature.version >= 0;
7609             sIsPip2ExperimentEnabled = Flags.enablePip2() && !isArc && !isTv;
7610         }
7611         return sIsPip2ExperimentEnabled;
7612     }
7613 }
7614