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