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