1 /*
2  * Copyright (C) 2006-2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.am;
18 
19 import static android.Manifest.permission.CHANGE_CONFIGURATION;
20 import static android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST;
21 import static android.Manifest.permission.FILTER_EVENTS;
22 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
24 import static android.Manifest.permission.MANAGE_ACTIVITY_TASKS;
25 import static android.Manifest.permission.MANAGE_USERS;
26 import static android.Manifest.permission.REQUEST_COMPANION_RUN_IN_BACKGROUND;
27 import static android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
28 import static android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND;
29 import static android.app.ActivityManager.INSTR_FLAG_ALWAYS_CHECK_SIGNATURE;
30 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS;
31 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_ISOLATED_STORAGE;
32 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_TEST_API_CHECKS;
33 import static android.app.ActivityManager.INSTR_FLAG_NO_RESTART;
34 import static android.app.ActivityManager.INTENT_SENDER_ACTIVITY;
35 import static android.app.ActivityManager.PROCESS_CAPABILITY_ALL;
36 import static android.app.ActivityManager.PROCESS_STATE_BOUND_TOP;
37 import static android.app.ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
38 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
39 import static android.app.ActivityManager.PROCESS_STATE_TOP;
40 import static android.app.ActivityManager.StopUserOnSwitch;
41 import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
42 import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_UNFROZEN;
43 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
44 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
45 import static android.app.ActivityManagerInternal.MEDIA_PROJECTION_TOKEN_EVENT_CREATED;
46 import static android.app.ActivityManagerInternal.MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED;
47 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_BACKUP;
48 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_FINISH_RECEIVER;
49 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_PROCESS_BEGIN;
50 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_PROCESS_END;
51 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_SHELL;
52 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_SYSTEM_INIT;
53 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_UI_VISIBILITY;
54 import static android.app.AppOpsManager.MODE_ALLOWED;
55 import static android.app.AppOpsManager.OP_NONE;
56 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_BACKUP;
57 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_INSTRUMENTATION;
58 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_PERSISTENT;
59 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_SYSTEM;
60 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
61 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES;
62 import static android.content.pm.PackageManager.MATCH_ALL;
63 import static android.content.pm.PackageManager.MATCH_ANY_USER;
64 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
65 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
66 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
67 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
70 import static android.content.pm.PackageManager.SIGNATURE_NO_MATCH;
71 import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
72 import static android.os.FactoryTest.FACTORY_TEST_OFF;
73 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
74 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH;
75 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
76 import static android.os.IServiceManager.DUMP_FLAG_PROTO;
77 import static android.os.InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
78 import static android.os.PowerExemptionManager.REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD;
79 import static android.os.PowerExemptionManager.REASON_BACKGROUND_ACTIVITY_PERMISSION;
80 import static android.os.PowerExemptionManager.REASON_COMPANION_DEVICE_MANAGER;
81 import static android.os.PowerExemptionManager.REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION;
82 import static android.os.PowerExemptionManager.REASON_PROC_STATE_BTOP;
83 import static android.os.PowerExemptionManager.REASON_PROC_STATE_PERSISTENT;
84 import static android.os.PowerExemptionManager.REASON_PROC_STATE_PERSISTENT_UI;
85 import static android.os.PowerExemptionManager.REASON_PROC_STATE_TOP;
86 import static android.os.PowerExemptionManager.REASON_START_ACTIVITY_FLAG;
87 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALERT_WINDOW_PERMISSION;
88 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALLOW_LISTED;
89 import static android.os.PowerExemptionManager.REASON_SYSTEM_UID;
90 import static android.os.PowerExemptionManager.REASON_UID_VISIBLE;
91 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
92 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_NONE;
93 import static android.os.PowerExemptionManager.getReasonCodeFromProcState;
94 import static android.os.Process.BLUETOOTH_UID;
95 import static android.os.Process.FIRST_APPLICATION_UID;
96 import static android.os.Process.INVALID_UID;
97 import static android.os.Process.NETWORK_STACK_UID;
98 import static android.os.Process.NFC_UID;
99 import static android.os.Process.PHONE_UID;
100 import static android.os.Process.PROC_OUT_LONG;
101 import static android.os.Process.PROC_SPACE_TERM;
102 import static android.os.Process.ROOT_UID;
103 import static android.os.Process.SCHED_FIFO;
104 import static android.os.Process.SCHED_RESET_ON_FORK;
105 import static android.os.Process.SE_UID;
106 import static android.os.Process.SHELL_UID;
107 import static android.os.Process.SIGNAL_USR1;
108 import static android.os.Process.SYSTEM_UID;
109 import static android.os.Process.THREAD_PRIORITY_FOREGROUND;
110 import static android.os.Process.THREAD_PRIORITY_TOP_APP_BOOST;
111 import static android.os.Process.ZYGOTE_POLICY_FLAG_BATCH_LAUNCH;
112 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
113 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
114 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS;
115 import static android.os.Process.ZYGOTE_PROCESS;
116 import static android.os.Process.getTotalMemory;
117 import static android.os.Process.isThreadInProcess;
118 import static android.os.Process.killProcess;
119 import static android.os.Process.killProcessGroup;
120 import static android.os.Process.killProcessQuiet;
121 import static android.os.Process.myPid;
122 import static android.os.Process.myUid;
123 import static android.os.Process.readProcFile;
124 import static android.os.Process.sendSignal;
125 import static android.os.Process.setThreadPriority;
126 import static android.os.Process.setThreadScheduler;
127 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
128 import static android.provider.Settings.Global.DEBUG_APP;
129 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER;
130 import static android.util.FeatureFlagUtils.SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS;
131 import static android.view.Display.INVALID_DISPLAY;
132 
133 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_CONFIGURATION;
134 import static com.android.internal.util.FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__INTERNAL_NON_EXPORTED_COMPONENT_MATCH;
135 import static com.android.internal.util.FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__NEW_MUTABLE_IMPLICIT_PENDING_INTENT_RETRIEVED;
136 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
137 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALLOWLISTS;
138 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
139 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP;
140 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
141 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND;
142 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
143 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
144 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK;
145 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
146 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER;
147 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES;
148 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
149 import static com.android.server.am.ActivityManagerDebugConfig.LOG_WRITER_INFO;
150 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP;
151 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
152 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
153 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU;
154 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
155 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK;
156 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ;
157 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER;
158 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES;
159 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
160 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS;
161 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
162 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
163 import static com.android.server.am.MemoryStatUtil.hasMemcg;
164 import static com.android.server.am.ProcessList.ProcStartHandler;
165 import static com.android.server.net.NetworkPolicyManagerInternal.updateBlockedReasonsWithProcState;
166 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
167 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND;
168 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND;
169 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
170 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
171 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
172 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
173 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
174 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD;
175 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD;
176 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD;
177 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD;
178 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD;
179 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD;
180 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD;
181 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD;
182 import static com.android.server.wm.ActivityTaskManagerService.DUMP_TOP_RESUMED_ACTIVITY;
183 import static com.android.server.wm.ActivityTaskManagerService.DUMP_VISIBLE_ACTIVITIES;
184 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
185 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString;
186 
187 import android.Manifest;
188 import android.Manifest.permission;
189 import android.annotation.NonNull;
190 import android.annotation.Nullable;
191 import android.annotation.PermissionMethod;
192 import android.annotation.PermissionName;
193 import android.annotation.RequiresPermission;
194 import android.annotation.UserIdInt;
195 import android.app.Activity;
196 import android.app.ActivityClient;
197 import android.app.ActivityManager;
198 import android.app.ActivityManager.ForegroundServiceApiType;
199 import android.app.ActivityManager.PendingIntentInfo;
200 import android.app.ActivityManager.ProcessCapability;
201 import android.app.ActivityManager.RestrictionLevel;
202 import android.app.ActivityManager.RunningTaskInfo;
203 import android.app.ActivityManager.UidFrozenStateChangedCallback.UidFrozenState;
204 import android.app.ActivityManagerInternal;
205 import android.app.ActivityManagerInternal.BindServiceEventListener;
206 import android.app.ActivityManagerInternal.BroadcastEventListener;
207 import android.app.ActivityManagerInternal.ForegroundServiceStateListener;
208 import android.app.ActivityManagerInternal.MediaProjectionTokenEvent;
209 import android.app.ActivityManagerInternal.OomAdjReason;
210 import android.app.ActivityTaskManager.RootTaskInfo;
211 import android.app.ActivityThread;
212 import android.app.AnrController;
213 import android.app.AppGlobals;
214 import android.app.AppOpsManager;
215 import android.app.AppOpsManager.AttributionFlags;
216 import android.app.AppOpsManagerInternal.CheckOpsDelegate;
217 import android.app.ApplicationErrorReport;
218 import android.app.ApplicationExitInfo;
219 import android.app.ApplicationStartInfo;
220 import android.app.ApplicationThreadConstants;
221 import android.app.BackgroundStartPrivileges;
222 import android.app.BroadcastOptions;
223 import android.app.ContentProviderHolder;
224 import android.app.ForegroundServiceDelegationOptions;
225 import android.app.IActivityController;
226 import android.app.IActivityManager;
227 import android.app.IApplicationStartInfoCompleteListener;
228 import android.app.IApplicationThread;
229 import android.app.IForegroundServiceObserver;
230 import android.app.IInstrumentationWatcher;
231 import android.app.INotificationManager;
232 import android.app.IProcessObserver;
233 import android.app.IServiceConnection;
234 import android.app.IStopUserCallback;
235 import android.app.ITaskStackListener;
236 import android.app.IUiAutomationConnection;
237 import android.app.IUidFrozenStateChangedCallback;
238 import android.app.IUidObserver;
239 import android.app.IUnsafeIntentStrictModeCallback;
240 import android.app.IUserSwitchObserver;
241 import android.app.Instrumentation;
242 import android.app.Notification;
243 import android.app.NotificationManager;
244 import android.app.PendingIntent;
245 import android.app.PendingIntentStats;
246 import android.app.ProcessMemoryState;
247 import android.app.ProfilerInfo;
248 import android.app.ServiceStartNotAllowedException;
249 import android.app.SyncNotedAppOp;
250 import android.app.WaitResult;
251 import android.app.assist.ActivityId;
252 import android.app.backup.BackupAnnotations.BackupDestination;
253 import android.app.backup.IBackupManager;
254 import android.app.compat.CompatChanges;
255 import android.app.job.JobParameters;
256 import android.app.usage.UsageEvents;
257 import android.app.usage.UsageEvents.Event;
258 import android.app.usage.UsageStatsManager;
259 import android.app.usage.UsageStatsManagerInternal;
260 import android.appwidget.AppWidgetManager;
261 import android.appwidget.AppWidgetManagerInternal;
262 import android.compat.annotation.ChangeId;
263 import android.compat.annotation.EnabledAfter;
264 import android.compat.annotation.EnabledSince;
265 import android.compat.annotation.Overridable;
266 import android.content.AttributionSource;
267 import android.content.AutofillOptions;
268 import android.content.BroadcastReceiver;
269 import android.content.ComponentCallbacks2;
270 import android.content.ComponentName;
271 import android.content.ContentCaptureOptions;
272 import android.content.ContentProvider;
273 import android.content.ContentResolver;
274 import android.content.Context;
275 import android.content.Context.BindServiceFlags;
276 import android.content.IIntentReceiver;
277 import android.content.IIntentSender;
278 import android.content.Intent;
279 import android.content.IntentFilter;
280 import android.content.LocusId;
281 import android.content.ServiceConnection;
282 import android.content.pm.ActivityInfo;
283 import android.content.pm.ActivityPresentationInfo;
284 import android.content.pm.ApplicationInfo;
285 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy;
286 import android.content.pm.IPackageDataObserver;
287 import android.content.pm.IPackageManager;
288 import android.content.pm.IncrementalStatesInfo;
289 import android.content.pm.InstrumentationInfo;
290 import android.content.pm.PackageInfo;
291 import android.content.pm.PackageManager;
292 import android.content.pm.PackageManager.NameNotFoundException;
293 import android.content.pm.PackageManagerInternal;
294 import android.content.pm.ParceledListSlice;
295 import android.content.pm.PermissionInfo;
296 import android.content.pm.ProcessInfo;
297 import android.content.pm.ProviderInfo;
298 import android.content.pm.ProviderInfoList;
299 import android.content.pm.ResolveInfo;
300 import android.content.pm.ServiceInfo;
301 import android.content.pm.SharedLibraryInfo;
302 import android.content.pm.TestUtilityService;
303 import android.content.pm.UserInfo;
304 import android.content.pm.VersionedPackage;
305 import android.content.res.CompatibilityInfo;
306 import android.content.res.Configuration;
307 import android.content.res.Resources;
308 import android.database.ContentObserver;
309 import android.graphics.Rect;
310 import android.hardware.display.DisplayManager;
311 import android.hardware.display.DisplayManagerInternal;
312 import android.media.audiofx.AudioEffect;
313 import android.net.ConnectivityManager;
314 import android.net.Proxy;
315 import android.net.Uri;
316 import android.os.AppZygote;
317 import android.os.BatteryStats;
318 import android.os.Binder;
319 import android.os.BinderProxy;
320 import android.os.BugreportParams;
321 import android.os.Build;
322 import android.os.Bundle;
323 import android.os.Debug;
324 import android.os.DropBoxManager;
325 import android.os.FactoryTest;
326 import android.os.FileUtils;
327 import android.os.Handler;
328 import android.os.IBinder;
329 import android.os.IDeviceIdentifiersPolicyService;
330 import android.os.IPermissionController;
331 import android.os.IProcessInfoService;
332 import android.os.IProgressListener;
333 import android.os.InputConstants;
334 import android.os.Looper;
335 import android.os.Message;
336 import android.os.Parcel;
337 import android.os.ParcelFileDescriptor;
338 import android.os.PowerExemptionManager;
339 import android.os.PowerExemptionManager.ReasonCode;
340 import android.os.PowerExemptionManager.TempAllowListType;
341 import android.os.PowerManager;
342 import android.os.PowerManager.ServiceType;
343 import android.os.PowerManagerInternal;
344 import android.os.Process;
345 import android.os.RemoteCallback;
346 import android.os.RemoteCallbackList;
347 import android.os.RemoteException;
348 import android.os.ResultReceiver;
349 import android.os.ServiceManager;
350 import android.os.SharedMemory;
351 import android.os.ShellCallback;
352 import android.os.StrictMode;
353 import android.os.SystemClock;
354 import android.os.SystemProperties;
355 import android.os.Trace;
356 import android.os.TransactionTooLargeException;
357 import android.os.UserHandle;
358 import android.os.UserManager;
359 import android.os.WorkSource;
360 import android.os.incremental.IIncrementalService;
361 import android.os.incremental.IncrementalManager;
362 import android.os.incremental.IncrementalMetrics;
363 import android.os.storage.IStorageManager;
364 import android.os.storage.StorageManager;
365 import android.provider.DeviceConfig;
366 import android.provider.Settings;
367 import android.server.ServerProtoEnums;
368 import android.sysprop.InitProperties;
369 import android.telephony.TelephonyManager;
370 import android.text.TextUtils;
371 import android.text.style.SuggestionSpan;
372 import android.util.ArrayMap;
373 import android.util.ArraySet;
374 import android.util.EventLog;
375 import android.util.FeatureFlagUtils;
376 import android.util.IndentingPrintWriter;
377 import android.util.IntArray;
378 import android.util.Log;
379 import android.util.Pair;
380 import android.util.PrintWriterPrinter;
381 import android.util.Slog;
382 import android.util.SparseArray;
383 import android.util.SparseIntArray;
384 import android.util.StatsEvent;
385 import android.util.TimeUtils;
386 import android.util.proto.ProtoOutputStream;
387 import android.util.proto.ProtoUtils;
388 import android.view.Display;
389 import android.view.Gravity;
390 import android.view.LayoutInflater;
391 import android.view.View;
392 import android.view.WindowManager;
393 import android.view.autofill.AutofillManagerInternal;
394 
395 import com.android.internal.annotations.CompositeRWLock;
396 import com.android.internal.annotations.GuardedBy;
397 import com.android.internal.annotations.VisibleForTesting;
398 import com.android.internal.app.IAppOpsActiveCallback;
399 import com.android.internal.app.IAppOpsCallback;
400 import com.android.internal.app.IAppOpsService;
401 import com.android.internal.app.ProcessMap;
402 import com.android.internal.app.SystemUserHomeActivity;
403 import com.android.internal.app.procstats.ProcessState;
404 import com.android.internal.app.procstats.ProcessStats;
405 import com.android.internal.content.InstallLocationUtils;
406 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
407 import com.android.internal.notification.SystemNotificationChannels;
408 import com.android.internal.os.BackgroundThread;
409 import com.android.internal.os.BinderCallHeavyHitterWatcher.BinderCallHeavyHitterListener;
410 import com.android.internal.os.BinderCallHeavyHitterWatcher.HeavyHitterContainer;
411 import com.android.internal.os.BinderInternal;
412 import com.android.internal.os.BinderTransactionNameResolver;
413 import com.android.internal.os.ByteTransferPipe;
414 import com.android.internal.os.IResultReceiver;
415 import com.android.internal.os.ProcessCpuTracker;
416 import com.android.internal.os.SomeArgs;
417 import com.android.internal.os.TimeoutRecord;
418 import com.android.internal.os.TransferPipe;
419 import com.android.internal.os.Zygote;
420 import com.android.internal.policy.AttributeCache;
421 import com.android.internal.protolog.common.ProtoLog;
422 import com.android.internal.util.ArrayUtils;
423 import com.android.internal.util.DumpUtils;
424 import com.android.internal.util.FastPrintWriter;
425 import com.android.internal.util.FrameworkStatsLog;
426 import com.android.internal.util.MemInfoReader;
427 import com.android.internal.util.Preconditions;
428 import com.android.internal.util.function.HeptFunction;
429 import com.android.internal.util.function.HexFunction;
430 import com.android.internal.util.function.QuadFunction;
431 import com.android.internal.util.function.QuintFunction;
432 import com.android.internal.util.function.UndecFunction;
433 import com.android.server.AlarmManagerInternal;
434 import com.android.server.BootReceiver;
435 import com.android.server.DeviceIdleInternal;
436 import com.android.server.DisplayThread;
437 import com.android.server.IntentResolver;
438 import com.android.server.IoThread;
439 import com.android.server.LocalManagerRegistry;
440 import com.android.server.LocalServices;
441 import com.android.server.LockGuard;
442 import com.android.server.PackageWatchdog;
443 import com.android.server.ServiceThread;
444 import com.android.server.SystemConfig;
445 import com.android.server.SystemService;
446 import com.android.server.SystemServiceManager;
447 import com.android.server.ThreadPriorityBooster;
448 import com.android.server.UserspaceRebootLogger;
449 import com.android.server.Watchdog;
450 import com.android.server.am.ComponentAliasResolver.Resolution;
451 import com.android.server.am.LowMemDetector.MemFactor;
452 import com.android.server.appop.AppOpsService;
453 import com.android.server.compat.PlatformCompat;
454 import com.android.server.contentcapture.ContentCaptureManagerInternal;
455 import com.android.server.criticalevents.CriticalEventLog;
456 import com.android.server.firewall.IntentFirewall;
457 import com.android.server.graphics.fonts.FontManagerInternal;
458 import com.android.server.job.JobSchedulerInternal;
459 import com.android.server.net.NetworkManagementInternal;
460 import com.android.server.os.NativeTombstoneManager;
461 import com.android.server.pm.Computer;
462 import com.android.server.pm.Installer;
463 import com.android.server.pm.UserManagerInternal;
464 import com.android.server.pm.permission.PermissionManagerServiceInternal;
465 import com.android.server.pm.pkg.AndroidPackage;
466 import com.android.server.pm.pkg.SELinuxUtil;
467 import com.android.server.pm.pkg.parsing.ParsingPackageUtils;
468 import com.android.server.pm.snapshot.PackageDataSnapshot;
469 import com.android.server.power.stats.BatteryStatsImpl;
470 import com.android.server.sdksandbox.SdkSandboxManagerLocal;
471 import com.android.server.uri.GrantUri;
472 import com.android.server.uri.NeededUriGrants;
473 import com.android.server.uri.UriGrantsManagerInternal;
474 import com.android.server.utils.PriorityDump;
475 import com.android.server.utils.Slogf;
476 import com.android.server.utils.TimingsTraceAndSlog;
477 import com.android.server.vr.VrManagerInternal;
478 import com.android.server.wm.ActivityMetricsLaunchObserver;
479 import com.android.server.wm.ActivityServiceConnectionsHolder;
480 import com.android.server.wm.ActivityTaskManagerInternal;
481 import com.android.server.wm.ActivityTaskManagerService;
482 import com.android.server.wm.WindowManagerInternal;
483 import com.android.server.wm.WindowManagerService;
484 import com.android.server.wm.WindowProcessController;
485 
486 import dalvik.annotation.optimization.NeverCompile;
487 import dalvik.system.VMRuntime;
488 
489 import libcore.util.EmptyArray;
490 
491 import java.io.File;
492 import java.io.FileDescriptor;
493 import java.io.FileNotFoundException;
494 import java.io.FileOutputStream;
495 import java.io.IOException;
496 import java.io.InputStreamReader;
497 import java.io.PrintWriter;
498 import java.util.ArrayList;
499 import java.util.Arrays;
500 import java.util.Collections;
501 import java.util.Comparator;
502 import java.util.HashMap;
503 import java.util.HashSet;
504 import java.util.Iterator;
505 import java.util.LinkedList;
506 import java.util.List;
507 import java.util.Locale;
508 import java.util.Map;
509 import java.util.Objects;
510 import java.util.Set;
511 import java.util.UUID;
512 import java.util.concurrent.CopyOnWriteArrayList;
513 import java.util.concurrent.CountDownLatch;
514 import java.util.concurrent.Executor;
515 import java.util.concurrent.TimeUnit;
516 import java.util.concurrent.atomic.AtomicBoolean;
517 import java.util.concurrent.atomic.AtomicInteger;
518 import java.util.function.BiFunction;
519 import java.util.function.Consumer;
520 
521 public class ActivityManagerService extends IActivityManager.Stub
522         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
523 
524     private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED =
525             "persist.sys.device_provisioned";
526 
527     static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
528     static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
529     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
530     private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
531     private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
532     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
533     static final String TAG_LRU = TAG + POSTFIX_LRU;
534     static final String TAG_MU = TAG + POSTFIX_MU;
535     static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
536     static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
537     private static final String TAG_POWER = TAG + POSTFIX_POWER;
538     static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
539     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
540     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
541     static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
542 
543     // Mock "pretend we're idle now" broadcast action to the job scheduler; declared
544     // here so that while the job scheduler can depend on AMS, the other way around
545     // need not be the case.
546     public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";
547 
548     private static final String INTENT_BUGREPORT_REQUESTED =
549             "com.android.internal.intent.action.BUGREPORT_REQUESTED";
550     private static final String SHELL_APP_PACKAGE = "com.android.shell";
551 
552     // The flags that are set for all calls we make to the package manager.
553     public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
554 
555     static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed";
556 
557     // Maximum number of receivers an app can register.
558     private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000;
559 
560     // How long we wait for a launched process to attach to the activity manager
561     // before we decide it's never going to come up for real.
562     static final int PROC_START_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
563 
564     // How long we wait for a launched process to complete its app startup before we ANR.
565     static final int BIND_APPLICATION_TIMEOUT = 20 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
566 
567     // How long we wait to kill an application zygote, after the last process using
568     // it has gone away.
569     static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000;
570 
571     // How long we wait for a launched process to attach to the activity manager
572     // before we decide it's never going to come up for real, when the process was
573     // started with a wrapper for instrumentation (such as Valgrind) because it
574     // could take much longer than usual.
575     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
576 
577     // How long we allow a receiver to run before giving up on it.
578     static final int BROADCAST_FG_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
579     static final int BROADCAST_BG_TIMEOUT = 60 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
580 
581     public static final int MY_PID = myPid();
582 
583     static final String[] EMPTY_STRING_ARRAY = new String[0];
584 
585     // How many bytes to write into the dropbox log before truncating
586     static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024;
587     // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
588     // as one line, but close enough for now.
589     static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
590 
591     // Necessary ApplicationInfo flags to mark an app as persistent
592     static final int PERSISTENT_MASK =
593             ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
594 
595     // Intent sent when remote bugreport collection has been completed
596     private static final String INTENT_REMOTE_BUGREPORT_FINISHED =
597             "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED";
598 
599     // If set, we will push process association information in to procstats.
600     static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true;
601 
602     // The minimum memory growth threshold (in KB) for low RAM devices.
603     private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB
604 
605     /**
606      * The number of binder proxies we need to have before we start warning and
607      * dumping debug info.
608      */
609     private static final int BINDER_PROXY_HIGH_WATERMARK = 6000;
610 
611     /**
612      * Low watermark that needs to be met before we consider dumping info again,
613      * after already hitting the high watermark.
614      */
615     private static final int BINDER_PROXY_LOW_WATERMARK = 5500;
616 
617     // Max character limit for a notification title. If the notification title is larger than this
618     // the notification will not be legible to the user.
619     private static final int MAX_BUGREPORT_TITLE_SIZE = 100;
620     private static final int MAX_BUGREPORT_DESCRIPTION_SIZE = 150;
621 
622     OomAdjuster mOomAdjuster;
623 
624     static final String EXTRA_TITLE = "android.intent.extra.TITLE";
625     static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION";
626     static final String EXTRA_BUGREPORT_TYPE = "android.intent.extra.BUGREPORT_TYPE";
627     static final String EXTRA_BUGREPORT_NONCE = "android.intent.extra.BUGREPORT_NONCE";
628 
629     /**
630      * It is now required for apps to explicitly set either
631      * {@link android.content.Context#RECEIVER_EXPORTED} or
632      * {@link android.content.Context#RECEIVER_NOT_EXPORTED} when registering a receiver for an
633      * unprotected broadcast in code.
634      */
635     @ChangeId
636     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
637     private static final long DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED = 161145287L;
638 
639     /**
640      * Apps targeting Android U and above will need to export components in order to invoke them
641      * through implicit intents.
642      *
643      * If a component is not exported and invoked, it will be removed from the list of receivers.
644      * This applies specifically to activities and broadcasts.
645      */
646     @ChangeId
647     @Overridable
648     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.TIRAMISU)
649     public static final long IMPLICIT_INTENTS_ONLY_MATCH_EXPORTED_COMPONENTS = 229362273;
650 
651     /**
652      * The maximum number of bytes that {@link #setProcessStateSummary} accepts.
653      *
654      * @see {@link android.app.ActivityManager#setProcessStateSummary(byte[])}
655      */
656     static final int MAX_STATE_DATA_SIZE = 128;
657 
658     /** All system services */
659     SystemServiceManager mSystemServiceManager;
660 
661     private Installer mInstaller;
662 
663     final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter();
664 
665     @CompositeRWLock({"this", "mProcLock"})
666     final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>();
667 
668     public final IntentFirewall mIntentFirewall;
669 
670     public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler();
671 
672     /**
673      * The global lock for AMS, it's de-facto the ActivityManagerService object as of now.
674      */
675     final ActivityManagerGlobalLock mGlobalLock = ActivityManagerService.this;
676 
677     /**
678      * Whether or not to enable the {@link #mProcLock}. If {@code false}, the {@link #mProcLock}
679      * will be equivalent to the {@link #mGlobalLock}.
680      */
681     private static final boolean ENABLE_PROC_LOCK = true;
682 
683     /**
684      * The lock for process management.
685      *
686      * <p>
687      * This lock is widely used in conjunction with the {@link #mGlobalLock} at present,
688      * where it'll require any of the locks to read from a data class, and both of the locks
689      * to write into that data class.
690      *
691      * For the naming convention of function suffixes:
692      * <ul>
693      *    <li>-LOSP:    Locked with any Of global am Service or Process lock</li>
694      *    <li>-LSP:     Locked with both of global am Service and Process lock</li>
695      *    <li>-Locked:  Locked with global am service lock alone</li>
696      *    <li>-LPr:     Locked with Process lock alone</li>
697      * </ul>
698      * For the simplicity, the getters/setters of the fields in data classes usually don't end with
699      * the above suffixes even if they're guarded by the locks here.
700      * </p>
701      *
702      * <p>
703      * In terms of locking order, it should be right below to the {@link #mGlobalLock},
704      * and above everything else which used to be underneath the {@link #mGlobalLock}.
705      * As of today, the core components(services/providers/broadcasts) are still guarded by
706      * the {@link #mGlobalLock} alone, so be cautious, avoid from acquiring the {@link #mGlobalLock}
707      * while holding this lock.
708      * </p>
709      *
710      */
711     final ActivityManagerGlobalLock mProcLock = ENABLE_PROC_LOCK
712             ? new ActivityManagerProcLock() : mGlobalLock;
713 
714     // Whether we should use SCHED_FIFO for UI and RenderThreads.
715     final boolean mUseFifoUiScheduling;
716 
717     // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED.
718     // For simplicity, since we statically declare the size of the array of BroadcastQueues,
719     // we still create this new offload queue, but never ever put anything on it.
720     final boolean mEnableOffloadQueue;
721 
722     /**
723      * Flag indicating if we should use {@link BroadcastQueueModernImpl} instead
724      * of the default {@link BroadcastQueueImpl}.
725      */
726     final boolean mEnableModernQueue;
727 
728     static final int BROADCAST_QUEUE_FG = 0;
729     static final int BROADCAST_QUEUE_BG = 1;
730     static final int BROADCAST_QUEUE_BG_OFFLOAD = 2;
731     static final int BROADCAST_QUEUE_FG_OFFLOAD = 3;
732 
733     @GuardedBy("this")
734     private final SparseArray<IUnsafeIntentStrictModeCallback>
735             mStrictModeCallbacks = new SparseArray<>();
736 
737     // Convenient for easy iteration over the queues. Foreground is first
738     // so that dispatch of foreground broadcasts gets precedence.
739     final BroadcastQueue[] mBroadcastQueues;
740 
741     @GuardedBy("this")
742     BroadcastStats mLastBroadcastStats;
743 
744     @GuardedBy("this")
745     BroadcastStats mCurBroadcastStats;
746 
747     TraceErrorLogger mTraceErrorLogger;
748 
broadcastQueueForIntent(Intent intent)749     BroadcastQueue broadcastQueueForIntent(Intent intent) {
750         return broadcastQueueForFlags(intent.getFlags(), intent);
751     }
752 
broadcastQueueForFlags(int flags)753     BroadcastQueue broadcastQueueForFlags(int flags) {
754         return broadcastQueueForFlags(flags, null);
755     }
756 
broadcastQueueForFlags(int flags, Object cookie)757     BroadcastQueue broadcastQueueForFlags(int flags, Object cookie) {
758         if (mEnableModernQueue) {
759             return mBroadcastQueues[0];
760         }
761 
762         if (isOnFgOffloadQueue(flags)) {
763             if (DEBUG_BROADCAST_BACKGROUND) {
764                 Slog.i(TAG_BROADCAST,
765                         "Broadcast intent " + cookie + " on foreground offload queue");
766             }
767             return mBroadcastQueues[BROADCAST_QUEUE_FG_OFFLOAD];
768         }
769 
770         if (isOnBgOffloadQueue(flags)) {
771             if (DEBUG_BROADCAST_BACKGROUND) {
772                 Slog.i(TAG_BROADCAST,
773                         "Broadcast intent " + cookie + " on background offload queue");
774             }
775             return mBroadcastQueues[BROADCAST_QUEUE_BG_OFFLOAD];
776         }
777 
778         final boolean isFg = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
779         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
780                 "Broadcast intent " + cookie + " on "
781                 + (isFg ? "foreground" : "background") + " queue");
782         return (isFg) ? mBroadcastQueues[BROADCAST_QUEUE_FG]
783                 : mBroadcastQueues[BROADCAST_QUEUE_BG];
784     }
785 
786     private volatile int mDeviceOwnerUid = INVALID_UID;
787 
788     /**
789      * Map userId to its companion app uids.
790      */
791     private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
792 
793     /**
794      * The profile owner UIDs.
795      */
796     private ArraySet<Integer> mProfileOwnerUids = null;
797 
798     final UserController mUserController;
799     @VisibleForTesting
800     public final PendingIntentController mPendingIntentController;
801 
802     final AppErrors mAppErrors;
803     final PackageWatchdog mPackageWatchdog;
804 
805     @GuardedBy("mDeliveryGroupPolicyIgnoredActions")
806     private final ArraySet<String> mDeliveryGroupPolicyIgnoredActions = new ArraySet();
807 
808     /**
809      * Uids of apps with current active camera sessions.  Access synchronized on
810      * the IntArray instance itself, and no other locks must be acquired while that
811      * one is held.
812      */
813     @GuardedBy("mActiveCameraUids")
814     final IntArray mActiveCameraUids = new IntArray(4);
815 
816     /**
817      * Helper class which strips out priority and proto arguments then calls the dump function with
818      * the appropriate arguments. If priority arguments are omitted, function calls the legacy
819      * dump command.
820      * If priority arguments are omitted all sections are dumped, otherwise sections are dumped
821      * according to their priority.
822      */
823     private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
824         @Override
825         public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
826                 boolean asProto) {
827             if (asProto) return;
828             doDump(fd, pw, new String[]{"activities"}, asProto);
829             doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto);
830         }
831 
832         @Override
833         public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
834             doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto);
835         }
836 
837         @Override
838         public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
839             doDump(fd, pw, args, asProto);
840         }
841     };
842 
843     private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
844             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY);
845 
boostPriorityForLockedSection()846     static void boostPriorityForLockedSection() {
847         sThreadPriorityBooster.boost();
848     }
849 
resetPriorityAfterLockedSection()850     static void resetPriorityAfterLockedSection() {
851         sThreadPriorityBooster.reset();
852     }
853 
854     private static ThreadPriorityBooster sProcThreadPriorityBooster = new ThreadPriorityBooster(
855             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_PROC);
856 
boostPriorityForProcLockedSection()857     static void boostPriorityForProcLockedSection() {
858         if (ENABLE_PROC_LOCK) {
859             sProcThreadPriorityBooster.boost();
860         } else {
861             sThreadPriorityBooster.boost();
862         }
863     }
864 
resetPriorityAfterProcLockedSection()865     static void resetPriorityAfterProcLockedSection() {
866         if (ENABLE_PROC_LOCK) {
867             sProcThreadPriorityBooster.reset();
868         } else {
869             sThreadPriorityBooster.reset();
870         }
871     }
872 
873     /**
874      * Process management.
875      */
876     final ProcessList mProcessList;
877 
878     /**
879      * The list of phantom processes.
880      * @see PhantomProcessRecord
881      */
882     final PhantomProcessList mPhantomProcessList;
883 
884     /**
885      * Tracking long-term execution of processes to look for abuse and other
886      * bad app behavior.
887      */
888     final ProcessStatsService mProcessStats;
889 
890     /**
891      * Non-persistent appId allowlist for background restrictions
892      */
893     @CompositeRWLock({"this", "mProcLock"})
894     private int[] mBackgroundAppIdAllowlist = new int[] {
895             BLUETOOTH_UID
896     };
897 
898     /**
899      * Broadcast actions that will always be deliverable to unlaunched/background apps
900      */
901     @GuardedBy("this")
902     private ArraySet<String> mBackgroundLaunchBroadcasts;
903 
904     /**
905      * When an app has restrictions on the other apps that can have associations with it,
906      * it appears here with a set of the allowed apps and also track debuggability of the app.
907      */
908     @GuardedBy("this")
909     private ArrayMap<String, PackageAssociationInfo> mAllowedAssociations;
910 
911     @GuardedBy("this")
912     final ComponentAliasResolver mComponentAliasResolver;
913 
914     private static final long HOME_LAUNCH_TIMEOUT_MS = 15000;
915     private final AtomicBoolean mHasHomeDelay = new AtomicBoolean(false);
916 
917     /**
918      * Tracks all users with computed color resources by ThemeOverlaycvontroller
919      */
920     @GuardedBy("this")
921     private final Set<Integer> mThemeOverlayReadyUsers = new HashSet<>();
922 
923 
924     /**
925      * Tracks association information for a particular package along with debuggability.
926      * <p> Associations for a package A are allowed to package B if B is part of the
927      *     allowed associations for A or if A is debuggable.
928      */
929     private final class PackageAssociationInfo {
930         private final String mSourcePackage;
931         private final ArraySet<String> mAllowedPackageAssociations;
932         private boolean mIsDebuggable;
933 
PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)934         PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages,
935                 boolean isDebuggable) {
936             mSourcePackage = sourcePackage;
937             mAllowedPackageAssociations = allowedPackages;
938             mIsDebuggable = isDebuggable;
939         }
940 
941         /**
942          * Returns true if {@code mSourcePackage} is allowed association with
943          * {@code targetPackage}.
944          */
isPackageAssociationAllowed(String targetPackage)945         boolean isPackageAssociationAllowed(String targetPackage) {
946             return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage);
947         }
948 
isDebuggable()949         boolean isDebuggable() {
950             return mIsDebuggable;
951         }
952 
setDebuggable(boolean isDebuggable)953         void setDebuggable(boolean isDebuggable) {
954             mIsDebuggable = isDebuggable;
955         }
956 
getAllowedPackageAssociations()957         ArraySet<String> getAllowedPackageAssociations() {
958             return mAllowedPackageAssociations;
959         }
960     }
961 
962     /**
963      * These are the currently running processes for which we have a ProcessInfo.
964      * Note: needs to be static since the permission checking call chain is static.  This
965      * all probably should be refactored into a separate permission checking object.
966      */
967     @GuardedBy("sActiveProcessInfoSelfLocked")
968     static final SparseArray<ProcessInfo> sActiveProcessInfoSelfLocked = new SparseArray<>();
969 
970     /**
971      * All of the processes we currently have running organized by pid.
972      * The keys are the pid running the application.
973      *
974      * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock!
975      */
976     final PidMap mPidsSelfLocked = new PidMap();
977     static final class PidMap {
978         private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>();
979 
get(int pid)980         ProcessRecord get(int pid) {
981             return mPidMap.get(pid);
982         }
983 
size()984         int size() {
985             return mPidMap.size();
986         }
987 
valueAt(int index)988         ProcessRecord valueAt(int index) {
989             return mPidMap.valueAt(index);
990         }
991 
keyAt(int index)992         int keyAt(int index) {
993             return mPidMap.keyAt(index);
994         }
995 
indexOfKey(int key)996         int indexOfKey(int key) {
997             return mPidMap.indexOfKey(key);
998         }
999 
doAddInternal(int pid, ProcessRecord app)1000         void doAddInternal(int pid, ProcessRecord app) {
1001             mPidMap.put(pid, app);
1002         }
1003 
doRemoveInternal(int pid, ProcessRecord app)1004         boolean doRemoveInternal(int pid, ProcessRecord app) {
1005             final ProcessRecord existingApp = mPidMap.get(pid);
1006             if (existingApp != null && existingApp.getStartSeq() == app.getStartSeq()) {
1007                 mPidMap.remove(pid);
1008                 return true;
1009             }
1010             return false;
1011         }
1012     }
1013 
1014     private final PendingStartActivityUids mPendingStartActivityUids;
1015 
1016     /**
1017      * Puts the process record in the map.
1018      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
1019      * method.
1020      */
1021     @GuardedBy("this")
addPidLocked(ProcessRecord app)1022     void addPidLocked(ProcessRecord app) {
1023         final int pid = app.getPid();
1024         synchronized (mPidsSelfLocked) {
1025             mPidsSelfLocked.doAddInternal(pid, app);
1026         }
1027         synchronized (sActiveProcessInfoSelfLocked) {
1028             if (app.processInfo != null) {
1029                 sActiveProcessInfoSelfLocked.put(pid, app.processInfo);
1030             } else {
1031                 sActiveProcessInfoSelfLocked.remove(pid);
1032             }
1033         }
1034         mAtmInternal.onProcessMapped(pid, app.getWindowProcessController());
1035     }
1036 
1037     /**
1038      * Removes the process record from the map.
1039      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
1040      * method.
1041      */
1042     @GuardedBy("this")
removePidLocked(int pid, ProcessRecord app)1043     boolean removePidLocked(int pid, ProcessRecord app) {
1044         final boolean removed;
1045         synchronized (mPidsSelfLocked) {
1046             removed = mPidsSelfLocked.doRemoveInternal(pid, app);
1047         }
1048         if (removed) {
1049             synchronized (sActiveProcessInfoSelfLocked) {
1050                 sActiveProcessInfoSelfLocked.remove(pid);
1051             }
1052             mAtmInternal.onProcessUnMapped(pid);
1053         }
1054         return removed;
1055     }
1056 
1057     /**
1058      * All of the processes that have been forced to be important.  The key
1059      * is the pid of the caller who requested it (we hold a death
1060      * link on it).
1061      */
1062     abstract class ImportanceToken implements IBinder.DeathRecipient {
1063         final int pid;
1064         final IBinder token;
1065         final String reason;
1066 
ImportanceToken(int _pid, IBinder _token, String _reason)1067         ImportanceToken(int _pid, IBinder _token, String _reason) {
1068             pid = _pid;
1069             token = _token;
1070             reason = _reason;
1071         }
1072 
1073         @Override
toString()1074         public String toString() {
1075             return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this))
1076                     + " " + reason + " " + pid + " " + token + " }";
1077         }
1078 
dumpDebug(ProtoOutputStream proto, long fieldId)1079         void dumpDebug(ProtoOutputStream proto, long fieldId) {
1080             final long pToken = proto.start(fieldId);
1081             proto.write(ImportanceTokenProto.PID, pid);
1082             if (token != null) {
1083                 proto.write(ImportanceTokenProto.TOKEN, token.toString());
1084             }
1085             proto.write(ImportanceTokenProto.REASON, reason);
1086             proto.end(pToken);
1087         }
1088     }
1089     @GuardedBy("this")
1090     final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>();
1091 
1092     /**
1093      * List of records for processes that someone had tried to start before the
1094      * system was ready.  We don't start them at that point, but ensure they
1095      * are started by the time booting is complete.
1096      */
1097     @GuardedBy("this")
1098     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
1099 
1100     /**
1101      * List of persistent applications that are in the process
1102      * of being started.
1103      */
1104     @GuardedBy("this")
1105     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
1106 
1107     private final ActivityMetricsLaunchObserver mActivityLaunchObserver =
1108             new ActivityMetricsLaunchObserver() {
1109         @Override
1110         public void onActivityLaunched(long id, ComponentName name, int temperature) {
1111             mAppProfiler.onActivityLaunched();
1112         }
1113     };
1114 
1115     private volatile boolean mBinderTransactionTrackingEnabled = false;
1116 
1117     /**
1118      * Fingerprints (hashCode()) of stack traces that we've
1119      * already logged DropBox entries for.  Guarded by itself.  If
1120      * something (rogue user app) forces this over
1121      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
1122      */
1123     @GuardedBy("mAlreadyLoggedViolatedStacks")
1124     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
1125     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
1126 
1127     /**
1128      * Keeps track of all IIntentReceivers that have been registered for broadcasts.
1129      * Hash keys are the receiver IBinder, hash value is a ReceiverList.
1130      */
1131     @GuardedBy("this")
1132     final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
1133 
1134     /**
1135      * Resolver for broadcast intents to registered receivers.
1136      * Holds BroadcastFilter (subclass of IntentFilter).
1137      */
1138     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
1139             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
1140         @Override
1141         protected boolean allowFilterResult(
1142                 BroadcastFilter filter, List<BroadcastFilter> dest) {
1143             IBinder target = filter.receiverList.receiver.asBinder();
1144             for (int i = dest.size() - 1; i >= 0; i--) {
1145                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
1146                     return false;
1147                 }
1148             }
1149             return true;
1150         }
1151 
1152         @Override
1153         protected BroadcastFilter newResult(@NonNull Computer computer, BroadcastFilter filter,
1154                 int match, int userId, long customFlags) {
1155             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
1156                     || userId == filter.owningUserId) {
1157                 return super.newResult(computer, filter, match, userId, customFlags);
1158             }
1159             return null;
1160         }
1161 
1162         @Override
1163         protected IntentFilter getIntentFilter(@NonNull BroadcastFilter input) {
1164             return input;
1165         }
1166 
1167         @Override
1168         protected BroadcastFilter[] newArray(int size) {
1169             return new BroadcastFilter[size];
1170         }
1171 
1172         @Override
1173         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
1174             return packageName.equals(filter.packageName);
1175         }
1176     };
1177 
1178     /**
1179      * State of all active sticky broadcasts per user.  Keys are the action of the
1180      * sticky Intent, values are an ArrayList of all broadcasted intents with
1181      * that action (which should usually be one).  The SparseArray is keyed
1182      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
1183      * for stickies that are sent to all users.
1184      */
1185     @GuardedBy("this")
1186     final SparseArray<ArrayMap<String, ArrayList<StickyBroadcast>>> mStickyBroadcasts =
1187             new SparseArray<>();
1188 
1189     @VisibleForTesting
1190     static final class StickyBroadcast {
1191         public Intent intent;
1192         public boolean deferUntilActive;
1193         public int originalCallingUid;
1194         /** The snapshot process state of the app who sent this broadcast */
1195         public int originalCallingAppProcessState;
1196 
create(Intent intent, boolean deferUntilActive, int originalCallingUid, int originalCallingAppProcessState)1197         public static StickyBroadcast create(Intent intent, boolean deferUntilActive,
1198                 int originalCallingUid, int originalCallingAppProcessState) {
1199             final StickyBroadcast b = new StickyBroadcast();
1200             b.intent = intent;
1201             b.deferUntilActive = deferUntilActive;
1202             b.originalCallingUid = originalCallingUid;
1203             b.originalCallingAppProcessState = originalCallingAppProcessState;
1204             return b;
1205         }
1206 
1207         @Override
toString()1208         public String toString() {
1209             return "{intent=" + intent + ", defer=" + deferUntilActive + ", originalCallingUid="
1210                     + originalCallingUid + ", originalCallingAppProcessState="
1211                     + originalCallingAppProcessState + "}";
1212         }
1213     }
1214 
1215     final ActiveServices mServices;
1216 
1217     final static class Association {
1218         final int mSourceUid;
1219         final String mSourceProcess;
1220         final int mTargetUid;
1221         final ComponentName mTargetComponent;
1222         final String mTargetProcess;
1223 
1224         int mCount;
1225         long mTime;
1226 
1227         int mNesting;
1228         long mStartTime;
1229 
1230         // states of the source process when the bind occurred.
1231         int mLastState = ActivityManager.MAX_PROCESS_STATE + 1;
1232         long mLastStateUptime;
1233         long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE
1234                 - ActivityManager.MIN_PROCESS_STATE+1];
1235 
Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1236         Association(int sourceUid, String sourceProcess, int targetUid,
1237                 ComponentName targetComponent, String targetProcess) {
1238             mSourceUid = sourceUid;
1239             mSourceProcess = sourceProcess;
1240             mTargetUid = targetUid;
1241             mTargetComponent = targetComponent;
1242             mTargetProcess = targetProcess;
1243         }
1244     }
1245 
1246     /**
1247      * When service association tracking is enabled, this is all of the associations we
1248      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
1249      * -> association data.
1250      */
1251     @GuardedBy("this")
1252     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
1253             mAssociations = new SparseArray<>();
1254     boolean mTrackingAssociations;
1255 
1256     /**
1257      * Backup/restore process management
1258      */
1259     @GuardedBy("this")
1260     final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>();
1261 
1262     final ContentProviderHelper mCpHelper;
1263 
1264     CoreSettingsObserver mCoreSettingsObserver;
1265 
1266     /**
1267      * All information we have collected about the runtime performance of
1268      * any user id that can impact battery performance.
1269      */
1270     final BatteryStatsService mBatteryStatsService;
1271 
1272     /**
1273      * Information about component usage
1274      */
1275     volatile UsageStatsManagerInternal mUsageStatsService;
1276 
1277     /**
1278      * Access to DeviceIdleController service.
1279      */
1280     DeviceIdleInternal mLocalDeviceIdleController;
1281 
1282     /**
1283      * Power-save allowlisted app-ids (not including except-idle-allowlisted ones).
1284      */
1285     @CompositeRWLock({"this", "mProcLock"})
1286     int[] mDeviceIdleAllowlist = new int[0];
1287 
1288     /**
1289      * Power-save allowlisted app-ids (including except-idle-allowlisted ones).
1290      */
1291     @CompositeRWLock({"this", "mProcLock"})
1292     int[] mDeviceIdleExceptIdleAllowlist = new int[0];
1293 
1294     /**
1295      * Set of app ids that are temporarily allowed to escape bg check due to high-pri message
1296      */
1297     @CompositeRWLock({"this", "mProcLock"})
1298     int[] mDeviceIdleTempAllowlist = new int[0];
1299 
1300     static final class PendingTempAllowlist {
1301         final int targetUid;
1302         final long duration;
1303         final String tag;
1304         final int type;
1305         final @ReasonCode int reasonCode;
1306         final int callingUid;
1307 
PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, int type, int callingUid)1308         PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag,
1309                 int type, int callingUid) {
1310             this.targetUid = targetUid;
1311             this.duration = duration;
1312             this.tag = tag;
1313             this.type = type;
1314             this.reasonCode = reasonCode;
1315             this.callingUid = callingUid;
1316         }
1317 
dumpDebug(ProtoOutputStream proto, long fieldId)1318         void dumpDebug(ProtoOutputStream proto, long fieldId) {
1319             final long token = proto.start(fieldId);
1320             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID,
1321                     targetUid);
1322             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS,
1323                     duration);
1324             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag);
1325             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TYPE, type);
1326             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.REASON_CODE,
1327                     reasonCode);
1328             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.CALLING_UID,
1329                     callingUid);
1330             proto.end(token);
1331         }
1332     }
1333 
1334     @CompositeRWLock({"this", "mProcLock"})
1335     final PendingTempAllowlists mPendingTempAllowlist = new PendingTempAllowlists(this);
1336 
1337     public static final class FgsTempAllowListItem {
1338         final long mDuration;
1339         final @PowerExemptionManager.ReasonCode int mReasonCode;
1340         final String mReason;
1341         final int mCallingUid;
1342 
FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, String reason, int callingUid)1343         FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode,
1344                 String reason, int callingUid) {
1345             mDuration = duration;
1346             mReasonCode = reasonCode;
1347             mReason = reason;
1348             mCallingUid = callingUid;
1349         }
1350 
dump(PrintWriter pw)1351         void dump(PrintWriter pw) {
1352             pw.print(" duration=" + mDuration +
1353                     " callingUid=" + UserHandle.formatUid(mCallingUid) +
1354                     " reasonCode=" + PowerExemptionManager.reasonCodeToString(mReasonCode) +
1355                     " reason=" + mReason);
1356         }
1357     }
1358 
1359     /**
1360      * The temp-allowlist that is allowed to start FGS from background.
1361      */
1362     @CompositeRWLock({"this", "mProcLock"})
1363     final FgsTempAllowList<FgsTempAllowListItem> mFgsStartTempAllowList =
1364             new FgsTempAllowList();
1365 
1366     static final FgsTempAllowListItem FAKE_TEMP_ALLOW_LIST_ITEM = new FgsTempAllowListItem(
1367             Long.MAX_VALUE, REASON_SYSTEM_ALLOW_LISTED, "", INVALID_UID);
1368 
1369     /*
1370      * List of uids that are allowed to have while-in-use permission when FGS is started from
1371      * background.
1372      */
1373     private final FgsTempAllowList<String> mFgsWhileInUseTempAllowList =
1374             new FgsTempAllowList();
1375 
1376     /**
1377      * Information about and control over application operations
1378      */
1379     final AppOpsService mAppOpsService;
1380     private AppOpsManager mAppOpsManager;
1381 
1382     /**
1383      * List of initialization arguments to pass to all processes when binding applications to them.
1384      * For example, references to the commonly used services.
1385      */
1386     ArrayMap<String, IBinder> mAppBindArgs;
1387     ArrayMap<String, IBinder> mIsolatedAppBindArgs;
1388 
1389     volatile boolean mProcessesReady = false;
1390     volatile boolean mSystemReady = false;
1391     volatile boolean mOnBattery = false;
1392     final int mFactoryTest;
1393     volatile boolean mBooting = false;
1394 
1395     @GuardedBy("this") boolean mCallFinishBooting = false;
1396     @GuardedBy("this") boolean mBootAnimationComplete = false;
1397 
1398     final Context mContext;
1399 
1400     /**
1401      * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
1402      * change at runtime. Use mContext for non-UI purposes.
1403      */
1404     final Context mUiContext;
1405 
1406     /**
1407      * Last time (in uptime) at which we checked for power usage.
1408      */
1409     @GuardedBy("mProcLock")
1410     long mLastPowerCheckUptime;
1411 
1412     /**
1413      * For some direct access we need to power manager.
1414      */
1415     PowerManagerInternal mLocalPowerManager;
1416 
1417     /**
1418      * State of external calls telling us if the device is awake or asleep.
1419      */
1420     AtomicInteger mWakefulness = new AtomicInteger(PowerManagerInternal.WAKEFULNESS_AWAKE);
1421 
1422     /**
1423      * The uptime of the last time we performed idle maintenance.
1424      */
1425     @GuardedBy("mProcLock")
1426     long mLastIdleTime = SystemClock.uptimeMillis();
1427 
1428     /**
1429      * For reporting to battery stats the current top application.
1430      *
1431      * <p>It has its own lock to avoid from the need of double locking if using the global
1432      * ActivityManagerService lock and proc lock to guard it.</p>
1433      */
1434     @GuardedBy("mCurResumedAppLock")
1435     private String mCurResumedPackage = null;
1436 
1437     @GuardedBy("mCurResumedAppLock")
1438     private int mCurResumedUid = -1;
1439 
1440     /**
1441      * Dedicated lock for {@link #mCurResumedPackage} and {@link #mCurResumedUid}.
1442      */
1443     private final Object mCurResumedAppLock = new Object();
1444 
1445     /**
1446      * For reporting to battery stats the apps currently running foreground
1447      * service.  The ProcessMap is package/uid tuples; each of these contain
1448      * an array of the currently foreground processes.
1449      */
1450     @GuardedBy("this")
1451     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1452             = new ProcessMap<ArrayList<ProcessRecord>>();
1453 
1454     /**
1455      * The list of foreground service state change listeners.
1456      */
1457     @GuardedBy("this")
1458     final ArrayList<ForegroundServiceStateListener> mForegroundServiceStateListeners =
1459             new ArrayList<>();
1460 
1461     /**
1462      * The list of broadcast event listeners.
1463      */
1464     final CopyOnWriteArrayList<BroadcastEventListener> mBroadcastEventListeners =
1465             new CopyOnWriteArrayList<>();
1466 
1467     /**
1468      * The list of bind service event listeners.
1469      */
1470     final CopyOnWriteArrayList<BindServiceEventListener> mBindServiceEventListeners =
1471             new CopyOnWriteArrayList<>();
1472 
1473     /**
1474      * Set if the systemServer made a call to enterSafeMode.
1475      */
1476     @GuardedBy("this")
1477     boolean mSafeMode;
1478 
1479     @GuardedBy("this")
1480     private String mDebugApp = null;
1481 
1482     @GuardedBy("this")
1483     private boolean mWaitForDebugger = false;
1484 
1485     @GuardedBy("this")
1486     private boolean mSuspendUponWait = false;
1487 
1488     @GuardedBy("this")
1489     private boolean mDebugTransient = false;
1490 
1491     @GuardedBy("this")
1492     private String mOrigDebugApp = null;
1493 
1494     @GuardedBy("this")
1495     private boolean mOrigWaitForDebugger = false;
1496 
1497     @GuardedBy("this")
1498     boolean mAlwaysFinishActivities = false;
1499 
1500     @GuardedBy("mProcLock")
1501     private String mTrackAllocationApp = null;
1502 
1503     @GuardedBy("this")
1504     String mNativeDebuggingApp = null;
1505 
1506     final Injector mInjector;
1507 
1508     static final class ProcessChangeItem {
1509         static final int CHANGE_ACTIVITIES = 1<<0;
1510         static final int CHANGE_FOREGROUND_SERVICES = 1<<1;
1511         int changes;
1512         int uid;
1513         int pid;
1514         int processState;
1515         boolean foregroundActivities;
1516         int foregroundServiceTypes;
1517     }
1518 
1519     @GuardedBy("mOomAdjObserverLock")
1520     OomAdjObserver mCurOomAdjObserver;
1521 
1522     @GuardedBy("mOomAdjObserverLock")
1523     int mCurOomAdjUid;
1524 
1525     /**
1526      * Dedicated lock for {@link #mCurOomAdjObserver} and {@link #mCurOomAdjUid}.
1527      */
1528     final Object mOomAdjObserverLock = new Object();
1529 
1530     interface OomAdjObserver {
onOomAdjMessage(String msg)1531         void onOomAdjMessage(String msg);
1532     }
1533 
1534     final AnrHelper mAnrHelper = new AnrHelper(this);
1535 
1536     /** Set to true after the system has finished booting. */
1537     volatile boolean mBooted = false;
1538 
1539     /**
1540      * Current boot phase.
1541      */
1542     int mBootPhase;
1543 
1544     volatile boolean mDeterministicUidIdle = false;
1545 
1546     @VisibleForTesting
1547     public WindowManagerService mWindowManager;
1548     WindowManagerInternal mWmInternal;
1549     @VisibleForTesting
1550     public ActivityTaskManagerService mActivityTaskManager;
1551     @VisibleForTesting
1552     public ActivityTaskManagerInternal mAtmInternal;
1553     UriGrantsManagerInternal mUgmInternal;
1554     @VisibleForTesting
1555     public final ActivityManagerInternal mInternal;
1556     final ActivityThread mSystemThread;
1557 
1558     final UidObserverController mUidObserverController;
1559     private volatile IUidObserver mNetworkPolicyUidObserver;
1560 
1561     @GuardedBy("mUidNetworkBlockedReasons")
1562     private final SparseIntArray mUidNetworkBlockedReasons = new SparseIntArray();
1563 
1564     final AppRestrictionController mAppRestrictionController;
1565 
1566     /**
1567      * The collection of the MediaProjection tokens per UID, for the apps that are allowed to
1568      * start FGS with the type "mediaProjection"; this permission is granted via the request over
1569      * the call to {@link android.media.project.MediaProjectionManager#createScreenCaptureIntent()}.
1570      *
1571      * <p>Note, the "token" here is actually an instance of
1572      * {@link android.media.projection.IMediaProjection}.</p>
1573      */
1574     @GuardedBy("mMediaProjectionTokenMap")
1575     private final SparseArray<ArraySet<IBinder>> mMediaProjectionTokenMap = new SparseArray();
1576 
1577     private final class AppDeathRecipient implements IBinder.DeathRecipient {
1578         final ProcessRecord mApp;
1579         final int mPid;
1580         final IApplicationThread mAppThread;
1581 
AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1582         AppDeathRecipient(ProcessRecord app, int pid,
1583                 IApplicationThread thread) {
1584             if (DEBUG_ALL) Slog.v(
1585                 TAG, "New death recipient " + this
1586                  + " for thread " + thread.asBinder());
1587             mApp = app;
1588             mPid = pid;
1589             mAppThread = thread;
1590         }
1591 
1592         @Override
binderDied()1593         public void binderDied() {
1594             if (DEBUG_ALL) Slog.v(
1595                 TAG, "Death received in " + this
1596                 + " for thread " + mAppThread.asBinder());
1597             synchronized(ActivityManagerService.this) {
1598                 appDiedLocked(mApp, mPid, mAppThread, true, null);
1599             }
1600         }
1601     }
1602 
1603     static final int SHOW_ERROR_UI_MSG = 1;
1604     static final int SHOW_NOT_RESPONDING_UI_MSG = 2;
1605     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1606     static final int WAIT_FOR_DEBUGGER_UI_MSG = 6;
1607     static final int SERVICE_TIMEOUT_MSG = 12;
1608     static final int UPDATE_TIME_ZONE = 13;
1609     static final int PROC_START_TIMEOUT_MSG = 20;
1610     static final int KILL_APPLICATION_MSG = 22;
1611     static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
1612     static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27;
1613     static final int CLEAR_DNS_CACHE_MSG = 28;
1614     static final int UPDATE_HTTP_PROXY_MSG = 29;
1615     static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31;
1616     static final int DISPATCH_PROCESS_DIED_UI_MSG = 32;
1617     static final int REPORT_MEM_USAGE_MSG = 33;
1618     static final int UPDATE_TIME_PREFERENCE_MSG = 41;
1619     static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49;
1620     static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50;
1621     static final int ABORT_DUMPHEAP_MSG = 51;
1622     static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56;
1623     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57;
1624     static final int IDLE_UIDS_MSG = 58;
1625     static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63;
1626     static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66;
1627     static final int SERVICE_FOREGROUND_TIMEOUT_ANR_MSG = 67;
1628     static final int PUSH_TEMP_ALLOWLIST_UI_MSG = 68;
1629     static final int SERVICE_FOREGROUND_CRASH_MSG = 69;
1630     static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70;
1631     static final int KILL_APP_ZYGOTE_MSG = 71;
1632     static final int BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG = 72;
1633     static final int WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG = 73;
1634     static final int DISPATCH_SENDING_BROADCAST_EVENT = 74;
1635     static final int DISPATCH_BINDING_SERVICE_EVENT = 75;
1636     static final int SERVICE_SHORT_FGS_TIMEOUT_MSG = 76;
1637     static final int SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG = 77;
1638     static final int SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG = 78;
1639     static final int UPDATE_CACHED_APP_HIGH_WATERMARK = 79;
1640     static final int ADD_UID_TO_OBSERVER_MSG = 80;
1641     static final int REMOVE_UID_FROM_OBSERVER_MSG = 81;
1642     static final int BIND_APPLICATION_TIMEOUT_MSG = 82;
1643 
1644     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1645 
1646     /**
1647      * Flag whether the current user is a "monkey", i.e. whether
1648      * the UI is driven by a UI automation tool.
1649      */
1650     private volatile boolean mUserIsMonkey;
1651 
1652     @VisibleForTesting
1653     public final ServiceThread mHandlerThread;
1654     final MainHandler mHandler;
1655     final Handler mUiHandler;
1656     final ServiceThread mProcStartHandlerThread;
1657     final ProcStartHandler mProcStartHandler;
1658 
1659     ActivityManagerConstants mConstants;
1660 
1661     // Encapsulates the global setting "hidden_api_blacklist_exemptions"
1662     final HiddenApiSettings mHiddenApiBlacklist;
1663 
1664     private final PlatformCompat mPlatformCompat;
1665 
1666     PackageManagerInternal mPackageManagerInt;
1667     PermissionManagerServiceInternal mPermissionManagerInt;
1668     private TestUtilityService mTestUtilityService;
1669 
1670     /**
1671      * Whether to force background check on all apps (for battery saver) or not.
1672      */
1673     @CompositeRWLock({"this", "mProcLock"})
1674     private boolean mForceBackgroundCheck;
1675 
1676     private static String sTheRealBuildSerial = Build.UNKNOWN;
1677 
1678     @GuardedBy("mProcLock")
1679     private ParcelFileDescriptor[] mLifeMonitorFds;
1680 
1681     static final HostingRecord sNullHostingRecord =
1682             new HostingRecord(HostingRecord.HOSTING_TYPE_EMPTY);
1683     /**
1684      * Used to notify activity lifecycle events.
1685      */
1686     @Nullable volatile ContentCaptureManagerInternal mContentCaptureService;
1687 
1688     /*
1689      * The default duration for the binder heavy hitter auto sampler
1690      */
1691     private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS = 300000L;
1692 
1693     /**
1694      * The default throttling duration for the binder heavy hitter auto sampler
1695      */
1696     private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS = 3600000L;
1697 
1698     /**
1699      * The last time when the binder heavy hitter auto sampler started.
1700      */
1701     @GuardedBy("mProcLock")
1702     private long mLastBinderHeavyHitterAutoSamplerStart = 0L;
1703 
1704     final AppProfiler mAppProfiler;
1705 
1706     private static final int INDEX_NATIVE_PSS = 0;
1707     private static final int INDEX_NATIVE_SWAP_PSS = 1;
1708     private static final int INDEX_NATIVE_RSS = 2;
1709     private static final int INDEX_DALVIK_PSS = 3;
1710     private static final int INDEX_DALVIK_SWAP_PSS = 4;
1711     private static final int INDEX_DALVIK_RSS = 5;
1712     private static final int INDEX_OTHER_PSS = 6;
1713     private static final int INDEX_OTHER_SWAP_PSS = 7;
1714     private static final int INDEX_OTHER_RSS = 8;
1715     private static final int INDEX_TOTAL_PSS = 9;
1716     private static final int INDEX_TOTAL_SWAP_PSS = 10;
1717     private static final int INDEX_TOTAL_RSS = 11;
1718     private static final int INDEX_TOTAL_NATIVE_PSS = 12;
1719     private static final int INDEX_TOTAL_MEMTRACK_GRAPHICS = 13;
1720     private static final int INDEX_TOTAL_MEMTRACK_GL = 14;
1721     private static final int INDEX_LAST = 15;
1722 
1723     /**
1724      * Used to notify activity lifecycle events.
1725      */
1726     @Nullable
1727     volatile ActivityManagerInternal.VoiceInteractionManagerProvider
1728             mVoiceInteractionManagerProvider;
1729 
1730     final class UiHandler extends Handler {
UiHandler()1731         public UiHandler() {
1732             super(com.android.server.UiThread.get().getLooper(), null, true);
1733         }
1734 
1735         @Override
handleMessage(Message msg)1736         public void handleMessage(Message msg) {
1737             switch (msg.what) {
1738                 case SHOW_ERROR_UI_MSG: {
1739                     mAppErrors.handleShowAppErrorUi(msg);
1740                     ensureBootCompleted();
1741                 } break;
1742                 case SHOW_NOT_RESPONDING_UI_MSG: {
1743                     mAppErrors.handleShowAnrUi(msg);
1744                     ensureBootCompleted();
1745                 } break;
1746                 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: {
1747                     HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1748                     synchronized (mProcLock) {
1749                         ProcessRecord proc = (ProcessRecord) data.get("app");
1750                         if (proc == null) {
1751                             Slog.e(TAG, "App not found when showing strict mode dialog.");
1752                             break;
1753                         }
1754                         if (proc.mErrorState.getDialogController().hasViolationDialogs()) {
1755                             Slog.e(TAG, "App already has strict mode dialog: " + proc);
1756                             return;
1757                         }
1758                         AppErrorResult res = (AppErrorResult) data.get("result");
1759                         if (mAtmInternal.showStrictModeViolationDialog()) {
1760                             proc.mErrorState.getDialogController().showViolationDialogs(res);
1761                         } else {
1762                             // The device is asleep, so just pretend that the user
1763                             // saw a crash dialog and hit "force quit".
1764                             res.set(0);
1765                         }
1766                     }
1767                     ensureBootCompleted();
1768                 } break;
1769                 case WAIT_FOR_DEBUGGER_UI_MSG: {
1770                     synchronized (mProcLock) {
1771                         ProcessRecord app = (ProcessRecord) msg.obj;
1772                         if (msg.arg1 != 0) {
1773                             if (!app.hasWaitedForDebugger()) {
1774                                 app.mErrorState.getDialogController().showDebugWaitingDialogs();
1775                                 app.setWaitedForDebugger(true);
1776                             }
1777                         } else {
1778                             app.mErrorState.getDialogController().clearWaitingDialog();
1779                         }
1780                     }
1781                 } break;
1782                 case DISPATCH_PROCESSES_CHANGED_UI_MSG: {
1783                     mProcessList.dispatchProcessesChanged();
1784                     break;
1785                 }
1786                 case DISPATCH_PROCESS_DIED_UI_MSG: {
1787                     if (false) { // DO NOT SUBMIT WITH TRUE
1788                         maybeTriggerWatchdog();
1789                     }
1790                     final int pid = msg.arg1;
1791                     final int uid = msg.arg2;
1792                     mProcessList.dispatchProcessDied(pid, uid);
1793                     break;
1794                 }
1795                 case DISPATCH_OOM_ADJ_OBSERVER_MSG: {
1796                     dispatchOomAdjObserver((String) msg.obj);
1797                 } break;
1798                 case PUSH_TEMP_ALLOWLIST_UI_MSG: {
1799                     pushTempAllowlist();
1800                 } break;
1801                 case ADD_UID_TO_OBSERVER_MSG: {
1802                     mUidObserverController.addUidToObserverImpl((IBinder) msg.obj, msg.arg1);
1803                 } break;
1804                 case REMOVE_UID_FROM_OBSERVER_MSG: {
1805                     mUidObserverController.removeUidFromObserverImpl((IBinder) msg.obj, msg.arg1);
1806                 } break;
1807             }
1808         }
1809     }
1810 
1811     final class MainHandler extends Handler {
MainHandler(Looper looper)1812         public MainHandler(Looper looper) {
1813             super(looper, null, true);
1814         }
1815 
1816         @Override
handleMessage(Message msg)1817         public void handleMessage(Message msg) {
1818             switch (msg.what) {
1819             case GC_BACKGROUND_PROCESSES_MSG: {
1820                 synchronized (ActivityManagerService.this) {
1821                     mAppProfiler.performAppGcsIfAppropriateLocked();
1822                 }
1823             } break;
1824             case SERVICE_TIMEOUT_MSG: {
1825                 mServices.serviceTimeout((ProcessRecord) msg.obj);
1826             } break;
1827             case SERVICE_FOREGROUND_TIMEOUT_MSG: {
1828                 mServices.serviceForegroundTimeout((ServiceRecord) msg.obj);
1829             } break;
1830             case SERVICE_FOREGROUND_TIMEOUT_ANR_MSG: {
1831                 SomeArgs args = (SomeArgs) msg.obj;
1832                 mServices.serviceForegroundTimeoutANR((ProcessRecord) args.arg1,
1833                         (TimeoutRecord) args.arg2);
1834                 args.recycle();
1835             } break;
1836             case SERVICE_FOREGROUND_CRASH_MSG: {
1837                 SomeArgs args = (SomeArgs) msg.obj;
1838                 mServices.serviceForegroundCrash(
1839                         (ProcessRecord) args.arg1,
1840                         (String) args.arg2,
1841                         (ComponentName) args.arg3);
1842                 args.recycle();
1843             } break;
1844             case UPDATE_TIME_ZONE: {
1845                 synchronized (mProcLock) {
1846                     mProcessList.forEachLruProcessesLOSP(false, app -> {
1847                         final IApplicationThread thread = app.getThread();
1848                         if (thread != null) {
1849                             try {
1850                                 thread.updateTimeZone();
1851                             } catch (RemoteException ex) {
1852                                 Slog.w(TAG, "Failed to update time zone for: "
1853                                         + app.info.processName);
1854                             }
1855                             }
1856                         });
1857                     }
1858             } break;
1859             case CLEAR_DNS_CACHE_MSG: {
1860                 synchronized (mProcLock) {
1861                     mProcessList.clearAllDnsCacheLOSP();
1862                 }
1863             } break;
1864             case UPDATE_HTTP_PROXY_MSG: {
1865                 mProcessList.setAllHttpProxy();
1866             } break;
1867             case PROC_START_TIMEOUT_MSG: {
1868                 ProcessRecord app = (ProcessRecord) msg.obj;
1869                 synchronized (ActivityManagerService.this) {
1870                     handleProcessStartOrKillTimeoutLocked(app, /* isKillTimeout */ false);
1871                 }
1872             } break;
1873             case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
1874                 ProcessRecord app = (ProcessRecord) msg.obj;
1875                 synchronized (ActivityManagerService.this) {
1876                     mCpHelper.processContentProviderPublishTimedOutLocked(app);
1877                 }
1878             } break;
1879             case KILL_APPLICATION_MSG: {
1880                 synchronized (ActivityManagerService.this) {
1881                     final int appId = msg.arg1;
1882                     final int userId = msg.arg2;
1883                     SomeArgs args = (SomeArgs) msg.obj;
1884                     String pkg = (String) args.arg1;
1885                     String reason = (String) args.arg2;
1886                     int exitInfoReason = (int) args.arg3;
1887                     args.recycle();
1888                     forceStopPackageLocked(pkg, appId, false, false, true, false,
1889                             false, userId, reason, exitInfoReason);
1890                 }
1891             } break;
1892 
1893                 case KILL_APP_ZYGOTE_MSG: {
1894                     synchronized (ActivityManagerService.this) {
1895                         final AppZygote appZygote = (AppZygote) msg.obj;
1896                         mProcessList.killAppZygoteIfNeededLocked(appZygote, false /* force */);
1897                     }
1898                 } break;
1899             case CHECK_EXCESSIVE_POWER_USE_MSG: {
1900                 checkExcessivePowerUsage();
1901                 removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG);
1902                 Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
1903                 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
1904             } break;
1905             case REPORT_MEM_USAGE_MSG: {
1906                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>) msg.obj;
1907                 Thread thread = new Thread() {
1908                     @Override public void run() {
1909                         mAppProfiler.reportMemUsage(memInfos);
1910                     }
1911                 };
1912                 thread.start();
1913                 break;
1914             }
1915             case UPDATE_TIME_PREFERENCE_MSG: {
1916                 // The user's time format preference might have changed.
1917                 // For convenience we re-use the Intent extra values.
1918                 synchronized (mProcLock) {
1919                     mProcessList.updateAllTimePrefsLOSP(msg.arg1);
1920                 }
1921                 break;
1922             }
1923             case NOTIFY_CLEARTEXT_NETWORK_MSG: {
1924                 final int uid = msg.arg1;
1925                 final byte[] firstPacket = (byte[]) msg.obj;
1926 
1927                 synchronized (mProcLock) {
1928                     synchronized (mPidsSelfLocked) {
1929                         for (int i = 0; i < mPidsSelfLocked.size(); i++) {
1930                             final ProcessRecord p = mPidsSelfLocked.valueAt(i);
1931                             final IApplicationThread thread = p.getThread();
1932                             if (p.uid == uid && thread != null) {
1933                                 try {
1934                                     thread.notifyCleartextNetwork(firstPacket);
1935                                 } catch (RemoteException ignored) {
1936                                 }
1937                             }
1938                         }
1939                     }
1940                 }
1941             } break;
1942             case POST_DUMP_HEAP_NOTIFICATION_MSG: {
1943                 mAppProfiler.handlePostDumpHeapNotification();
1944             } break;
1945             case ABORT_DUMPHEAP_MSG: {
1946                 mAppProfiler.handleAbortDumpHeap((String) msg.obj);
1947             } break;
1948             case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
1949                 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
1950                 try {
1951                     connection.shutdown();
1952                 } catch (RemoteException e) {
1953                     Slog.w(TAG, "Error shutting down UiAutomationConnection");
1954                 }
1955                 // Only a UiAutomation can set this flag and now that
1956                 // it is finished we make sure it is reset to its default.
1957                 mUserIsMonkey = false;
1958             } break;
1959             case IDLE_UIDS_MSG: {
1960                 idleUids();
1961             } break;
1962             case HANDLE_TRUST_STORAGE_UPDATE_MSG: {
1963                 synchronized (mProcLock) {
1964                     mProcessList.handleAllTrustStorageUpdateLOSP();
1965                 }
1966             } break;
1967                 case BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG: {
1968                     handleBinderHeavyHitterAutoSamplerTimeOut();
1969                 } break;
1970                 case WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG: {
1971                     synchronized (ActivityManagerService.this) {
1972                         ((ContentProviderRecord) msg.obj).onProviderPublishStatusLocked(false);
1973                     }
1974                 } break;
1975                 case DISPATCH_SENDING_BROADCAST_EVENT: {
1976                     mBroadcastEventListeners.forEach(l ->
1977                             l.onSendingBroadcast((String) msg.obj, msg.arg1));
1978                 } break;
1979                 case DISPATCH_BINDING_SERVICE_EVENT: {
1980                     mBindServiceEventListeners.forEach(l ->
1981                             l.onBindingService((String) msg.obj, msg.arg1));
1982                 } break;
1983                 case SERVICE_SHORT_FGS_TIMEOUT_MSG: {
1984                     mServices.onShortFgsTimeout((ServiceRecord) msg.obj);
1985                 } break;
1986                 case SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG: {
1987                     mServices.onShortFgsProcstateTimeout((ServiceRecord) msg.obj);
1988                 } break;
1989                 case SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG: {
1990                     mServices.onShortFgsAnrTimeout((ServiceRecord) msg.obj);
1991                 } break;
1992                 case UPDATE_CACHED_APP_HIGH_WATERMARK: {
1993                     mAppProfiler.mCachedAppsWatermarkData.updateCachedAppsSnapshot((long) msg.obj);
1994                 } break;
1995                 case BIND_APPLICATION_TIMEOUT_MSG: {
1996                     ProcessRecord app = (ProcessRecord) msg.obj;
1997 
1998                     final String anrMessage;
1999                     synchronized (app) {
2000                         anrMessage = "Process " + app + " failed to complete startup";
2001                     }
2002 
2003                     mAnrHelper.appNotResponding(app, TimeoutRecord.forAppStart(anrMessage));
2004                 } break;
2005             }
2006         }
2007     }
2008 
2009 
setSystemProcess()2010     public void setSystemProcess() {
2011         try {
2012             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2013                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
2014             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2015             ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2016                     DUMP_FLAG_PRIORITY_HIGH);
2017             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2018             ServiceManager.addService("dbinfo", new DbBinder(this));
2019             mAppProfiler.setCpuInfoService();
2020             ServiceManager.addService("permission", new PermissionController(this));
2021             ServiceManager.addService("processinfo", new ProcessInfoService(this));
2022             ServiceManager.addService("cacheinfo", new CacheBinder(this));
2023 
2024             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2025                     "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2026             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2027 
2028             synchronized (this) {
2029                 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
2030                         false,
2031                         0,
2032                         false,
2033                         0,
2034                         null,
2035                         new HostingRecord(HostingRecord.HOSTING_TYPE_SYSTEM));
2036                 app.setPersistent(true);
2037                 app.setPid(MY_PID);
2038                 app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
2039                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2040                 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_SYSTEM);
2041                 addPidLocked(app);
2042                 updateLruProcessLocked(app, false, null);
2043                 updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT);
2044             }
2045         } catch (PackageManager.NameNotFoundException e) {
2046             throw new RuntimeException(
2047                     "Unable to find android system package", e);
2048         }
2049 
2050         // Start watching app ops after we and the package manager are up and running.
2051         mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2052                 new IAppOpsCallback.Stub() {
2053                     @Override public void opChanged(int op, int uid, String packageName) {
2054                         if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2055                             if (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
2056                                     != AppOpsManager.MODE_ALLOWED) {
2057                                 runInBackgroundDisabled(uid);
2058                             }
2059                         }
2060                     }
2061                 });
2062 
2063         final int[] cameraOp = {AppOpsManager.OP_CAMERA};
2064         mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
2065             @Override
2066             public void opActiveChanged(int op, int uid, String packageName, String attributionTag,
2067                     boolean active, @AttributionFlags int attributionFlags,
2068                     int attributionChainId) {
2069                 cameraActiveChanged(uid, active);
2070             }
2071         });
2072     }
2073 
setWindowManager(WindowManagerService wm)2074     public void setWindowManager(WindowManagerService wm) {
2075         synchronized (this) {
2076             mWindowManager = wm;
2077             mWmInternal = LocalServices.getService(WindowManagerInternal.class);
2078             mActivityTaskManager.setWindowManager(wm);
2079         }
2080     }
2081 
2082     /**
2083      * @param usageStatsManager shouldn't be null
2084      */
setUsageStatsManager(@onNull UsageStatsManagerInternal usageStatsManager)2085     public void setUsageStatsManager(@NonNull UsageStatsManagerInternal usageStatsManager) {
2086         mUsageStatsService = usageStatsManager;
2087         mActivityTaskManager.setUsageStatsManager(usageStatsManager);
2088     }
2089 
2090     /**
2091      * Sets the internal content capture manager service.
2092      *
2093      * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock.
2094      */
setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)2095     public void setContentCaptureManager(
2096             @Nullable ContentCaptureManagerInternal contentCaptureManager) {
2097         mContentCaptureService = contentCaptureManager;
2098     }
2099 
startObservingNativeCrashes()2100     public void startObservingNativeCrashes() {
2101         final NativeCrashListener ncl = new NativeCrashListener(this);
2102         ncl.start();
2103     }
2104 
2105     /**
2106      * Sets a policy for handling app ops.
2107      *
2108      * @param appOpsPolicy The policy.
2109      */
setAppOpsPolicy(@ullable CheckOpsDelegate appOpsPolicy)2110     public void setAppOpsPolicy(@Nullable CheckOpsDelegate appOpsPolicy) {
2111         mAppOpsService.setAppOpsPolicy(appOpsPolicy);
2112     }
2113 
getAppOpsService()2114     public IAppOpsService getAppOpsService() {
2115         return mAppOpsService;
2116     }
2117 
2118     /**
2119      * Sets the internal voice interaction manager service.
2120      */
setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)2121     private void setVoiceInteractionManagerProvider(
2122             @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) {
2123         mVoiceInteractionManagerProvider = provider;
2124     }
2125 
2126     /**
2127      * Represents volatile states associated with a Dropbox entry.
2128      * <p>
2129      * These states, such as the process frozen state, can change quickly over time and thus
2130      * should be captured as soon as possible to ensure accurate state. If a state is undefined,
2131      * it means that the state was not read early and a fallback value can be used.
2132      * </p>
2133      */
2134     static class VolatileDropboxEntryStates {
2135         private final Boolean mIsProcessFrozen;
2136 
VolatileDropboxEntryStates(Boolean frozenState)2137         private VolatileDropboxEntryStates(Boolean frozenState) {
2138             this.mIsProcessFrozen = frozenState;
2139         }
2140 
withProcessFrozenState(boolean frozenState)2141         public static VolatileDropboxEntryStates withProcessFrozenState(boolean frozenState) {
2142             return new VolatileDropboxEntryStates(frozenState);
2143         }
2144 
emptyVolatileDropboxEnytyStates()2145         public static VolatileDropboxEntryStates emptyVolatileDropboxEnytyStates() {
2146             return new VolatileDropboxEntryStates(null);
2147         }
2148 
isProcessFrozen()2149         public Boolean isProcessFrozen() {
2150             return mIsProcessFrozen;
2151         }
2152     }
2153 
2154     static class MemBinder extends Binder {
2155         ActivityManagerService mActivityManagerService;
2156         private final PriorityDump.PriorityDumper mPriorityDumper =
2157                 new PriorityDump.PriorityDumper() {
2158             @Override
2159             public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args,
2160                     boolean asProto) {
2161                 dump(fd, pw, new String[] {"-a"}, asProto);
2162             }
2163 
2164             @Override
2165             public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
2166                 mActivityManagerService.dumpApplicationMemoryUsage(
2167                         fd, pw, "  ", args, false, null, asProto);
2168             }
2169         };
2170 
MemBinder(ActivityManagerService activityManagerService)2171         MemBinder(ActivityManagerService activityManagerService) {
2172             mActivityManagerService = activityManagerService;
2173         }
2174 
2175         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2176         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2177             try {
2178                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2179 
2180                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2181                         "meminfo", pw)) return;
2182                 PriorityDump.dump(mPriorityDumper, fd, pw, args);
2183             } finally {
2184                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2185             }
2186         }
2187     }
2188 
2189     static class GraphicsBinder extends Binder {
2190         ActivityManagerService mActivityManagerService;
GraphicsBinder(ActivityManagerService activityManagerService)2191         GraphicsBinder(ActivityManagerService activityManagerService) {
2192             mActivityManagerService = activityManagerService;
2193         }
2194 
2195         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2196         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2197             try {
2198                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2199 
2200                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2201                         "gfxinfo", pw)) return;
2202                 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2203             } finally {
2204                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2205             }
2206         }
2207     }
2208 
2209     static class DbBinder extends Binder {
2210         ActivityManagerService mActivityManagerService;
DbBinder(ActivityManagerService activityManagerService)2211         DbBinder(ActivityManagerService activityManagerService) {
2212             mActivityManagerService = activityManagerService;
2213         }
2214 
2215         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2216         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2217             try {
2218                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2219 
2220                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2221                         "dbinfo", pw)) return;
2222                 mActivityManagerService.dumpDbInfo(fd, pw, args);
2223             } finally {
2224                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2225             }
2226         }
2227     }
2228 
2229     static class CacheBinder extends Binder {
2230         ActivityManagerService mActivityManagerService;
2231 
CacheBinder(ActivityManagerService activityManagerService)2232         CacheBinder(ActivityManagerService activityManagerService) {
2233             mActivityManagerService = activityManagerService;
2234         }
2235 
2236         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2237         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2238             try {
2239                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2240 
2241                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2242                         "cacheinfo", pw)) {
2243                     return;
2244                 }
2245 
2246                 mActivityManagerService.dumpBinderCacheContents(fd, pw, args);
2247             } finally {
2248                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2249             }
2250         }
2251     }
2252 
2253     public static final class Lifecycle extends SystemService {
2254         private final ActivityManagerService mService;
2255         private static ActivityTaskManagerService sAtm;
2256 
Lifecycle(Context context)2257         public Lifecycle(Context context) {
2258             super(context);
2259             mService = new ActivityManagerService(context, sAtm);
2260         }
2261 
startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2262         public static ActivityManagerService startService(
2263                 SystemServiceManager ssm, ActivityTaskManagerService atm) {
2264             sAtm = atm;
2265             return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
2266         }
2267 
2268         @Override
onStart()2269         public void onStart() {
2270             mService.start();
2271         }
2272 
2273         @Override
onBootPhase(int phase)2274         public void onBootPhase(int phase) {
2275             mService.mBootPhase = phase;
2276             if (phase == PHASE_SYSTEM_SERVICES_READY) {
2277                 mService.mBatteryStatsService.systemServicesReady();
2278                 mService.mServices.systemServicesReady();
2279             } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
2280                 mService.startBroadcastObservers();
2281             } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
2282                 mService.mPackageWatchdog.onPackagesReady();
2283                 mService.scheduleHomeTimeout();
2284             }
2285         }
2286 
2287         @Override
onUserStopped(@onNull TargetUser user)2288         public void onUserStopped(@NonNull TargetUser user) {
2289             mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier());
2290         }
2291 
getService()2292         public ActivityManagerService getService() {
2293             return mService;
2294         }
2295     }
2296 
maybeLogUserspaceRebootEvent()2297     private void maybeLogUserspaceRebootEvent() {
2298         if (!UserspaceRebootLogger.shouldLogUserspaceRebootEvent()) {
2299             return;
2300         }
2301         final int userId = mUserController.getCurrentUserId();
2302         if (userId != UserHandle.USER_SYSTEM) {
2303             // Only log for user0.
2304             return;
2305         }
2306         // TODO(b/148767783): should we check all profiles under user0?
2307         UserspaceRebootLogger.logEventAsync(StorageManager.isUserKeyUnlocked(userId),
2308                 BackgroundThread.getExecutor());
2309     }
2310 
2311     /**
2312      * Encapsulates global settings related to hidden API enforcement behaviour, including tracking
2313      * the latest value via a content observer.
2314      */
2315     static class HiddenApiSettings extends ContentObserver
2316             implements DeviceConfig.OnPropertiesChangedListener {
2317 
2318         private final Context mContext;
2319         private boolean mBlacklistDisabled;
2320         private String mExemptionsStr;
2321         private List<String> mExemptions = Collections.emptyList();
2322         private int mLogSampleRate = -1;
2323         private int mStatslogSampleRate = -1;
2324         @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT;
2325 
2326         /**
2327          * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in
2328          * the range 0 to 0x10000 inclusive.
2329          *
2330          * @hide
2331          */
2332         public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE =
2333                 "hidden_api_access_log_sampling_rate";
2334 
2335         /**
2336          * Sampling rate for hidden API access event logging with statslog, as an integer in the
2337          * range 0 to 0x10000 inclusive.
2338          *
2339          * @hide
2340          */
2341         public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE =
2342                 "hidden_api_access_statslog_sampling_rate";
2343 
onPropertiesChanged(DeviceConfig.Properties properties)2344         public void onPropertiesChanged(DeviceConfig.Properties properties) {
2345             int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0x0);
2346             if (logSampleRate < 0 || logSampleRate > 0x10000) {
2347                 logSampleRate = -1;
2348             }
2349             if (logSampleRate != -1 && logSampleRate != mLogSampleRate) {
2350                 mLogSampleRate = logSampleRate;
2351                 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate);
2352             }
2353 
2354             int statslogSampleRate =
2355                     properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0);
2356             if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) {
2357                 statslogSampleRate = -1;
2358             }
2359             if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) {
2360                 mStatslogSampleRate = statslogSampleRate;
2361                 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate);
2362             }
2363         }
2364 
HiddenApiSettings(Handler handler, Context context)2365         public HiddenApiSettings(Handler handler, Context context) {
2366             super(handler);
2367             mContext = context;
2368         }
2369 
registerObserver()2370         public void registerObserver() {
2371             mContext.getContentResolver().registerContentObserver(
2372                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS),
2373                     false,
2374                     this);
2375             mContext.getContentResolver().registerContentObserver(
2376                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY),
2377                     false,
2378                     this);
2379             DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT,
2380                     mContext.getMainExecutor(), this);
2381             update();
2382         }
2383 
update()2384         private void update() {
2385             String exemptions = Settings.Global.getString(mContext.getContentResolver(),
2386                     Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS);
2387             if (!TextUtils.equals(exemptions, mExemptionsStr)) {
2388                 mExemptionsStr = exemptions;
2389                 if ("*".equals(exemptions)) {
2390                     mBlacklistDisabled = true;
2391                     mExemptions = Collections.emptyList();
2392                 } else {
2393                     mBlacklistDisabled = false;
2394                     mExemptions = TextUtils.isEmpty(exemptions)
2395                             ? Collections.emptyList()
2396                             : Arrays.asList(exemptions.split(","));
2397                 }
2398                 if (!ZYGOTE_PROCESS.setApiDenylistExemptions(mExemptions)) {
2399                   Slog.e(TAG, "Failed to set API blacklist exemptions!");
2400                   // leave mExemptionsStr as is, so we don't try to send the same list again.
2401                   mExemptions = Collections.emptyList();
2402                 }
2403             }
2404             mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY);
2405         }
2406 
getValidEnforcementPolicy(String settingsKey)2407         private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) {
2408             int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey,
2409                     ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT);
2410             if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) {
2411                 return policy;
2412             } else {
2413                 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
2414             }
2415         }
2416 
isDisabled()2417         boolean isDisabled() {
2418             return mBlacklistDisabled;
2419         }
2420 
getPolicy()2421         @HiddenApiEnforcementPolicy int getPolicy() {
2422             return mPolicy;
2423         }
2424 
onChange(boolean selfChange)2425         public void onChange(boolean selfChange) {
2426             update();
2427         }
2428     }
2429 
getAppOpsManager()2430     AppOpsManager getAppOpsManager() {
2431         if (mAppOpsManager == null) {
2432             mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
2433         }
2434         return mAppOpsManager;
2435     }
2436 
2437     /** Provides the basic functionality for unit tests. */
2438     @VisibleForTesting
ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread)2439     ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread) {
2440         this(injector, handlerThread, null);
2441     }
2442 
2443     /** Provides the basic functionality for unit tests. */
2444     @VisibleForTesting
ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread, @Nullable UserController userController)2445     ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread,
2446             @Nullable UserController userController) {
2447         mInjector = injector;
2448         mContext = mInjector.getContext();
2449         mUiContext = null;
2450         mAppErrors = null;
2451         mPackageWatchdog = null;
2452         mAppOpsService = mInjector.getAppOpsService(null /* recentAccessesFile */,
2453             null /* storageFile */, null /* handler */);
2454         mBatteryStatsService = mInjector.getBatteryStatsService();
2455         mHandler = new MainHandler(handlerThread.getLooper());
2456         mHandlerThread = handlerThread;
2457         mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2458         final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
2459         mPlatformCompat = null;
2460         mProcessList = injector.getProcessList(this);
2461         mProcessList.init(this, activeUids, mPlatformCompat);
2462         mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), null);
2463         mPhantomProcessList = new PhantomProcessList(this);
2464         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids, handlerThread);
2465 
2466         mIntentFirewall = null;
2467         mProcessStats = new ProcessStatsService(this, mContext.getCacheDir());
2468         mCpHelper = new ContentProviderHelper(this, false);
2469         mServices = mInjector.getActiveServices(this);
2470         mSystemThread = null;
2471         mUiHandler = injector.getUiHandler(null /* service */);
2472         mUidObserverController = new UidObserverController(mUiHandler);
2473         mUserController = userController == null ? new UserController(this) : userController;
2474         mInjector.mUserController = mUserController;
2475         mPendingIntentController =
2476                 new PendingIntentController(handlerThread.getLooper(), mUserController, mConstants);
2477         mAppRestrictionController = new AppRestrictionController(mContext, this);
2478         mProcStartHandlerThread = null;
2479         mProcStartHandler = null;
2480         mHiddenApiBlacklist = null;
2481         mFactoryTest = FACTORY_TEST_OFF;
2482         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2483         mInternal = new LocalService();
2484         mPendingStartActivityUids = new PendingStartActivityUids();
2485         mUseFifoUiScheduling = false;
2486         mEnableOffloadQueue = false;
2487         mEnableModernQueue = false;
2488         mBroadcastQueues = new BroadcastQueue[0];
2489         mComponentAliasResolver = new ComponentAliasResolver(this);
2490     }
2491 
2492     // Note: This method is invoked on the main thread but may need to attach various
2493     // handlers to other threads.  So take care to be explicit about the looper.
ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2494     public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
2495         LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2496         mInjector = new Injector(systemContext);
2497         mContext = systemContext;
2498 
2499         mFactoryTest = FactoryTest.getMode();
2500         mSystemThread = ActivityThread.currentActivityThread();
2501         mUiContext = mSystemThread.getSystemUiContext();
2502 
2503         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2504 
2505         mHandlerThread = new ServiceThread(TAG,
2506                 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2507         mHandlerThread.start();
2508         mHandler = new MainHandler(mHandlerThread.getLooper());
2509         mUiHandler = mInjector.getUiHandler(this);
2510 
2511         mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
2512                 THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
2513         mProcStartHandlerThread.start();
2514         mProcStartHandler = new ProcStartHandler(this, mProcStartHandlerThread.getLooper());
2515 
2516         mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2517         final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
2518         mPlatformCompat = (PlatformCompat) ServiceManager.getService(
2519                 Context.PLATFORM_COMPAT_SERVICE);
2520         mProcessList = mInjector.getProcessList(this);
2521         mProcessList.init(this, activeUids, mPlatformCompat);
2522         mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
2523                 new LowMemDetector(this));
2524         mPhantomProcessList = new PhantomProcessList(this);
2525         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2526 
2527         // Broadcast policy parameters
2528         final BroadcastConstants foreConstants = new BroadcastConstants(
2529                 Settings.Global.BROADCAST_FG_CONSTANTS);
2530         foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
2531 
2532         final BroadcastConstants backConstants = new BroadcastConstants(
2533                 Settings.Global.BROADCAST_BG_CONSTANTS);
2534         backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2535 
2536         final BroadcastConstants offloadConstants = new BroadcastConstants(
2537                 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
2538         offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2539         // by default, no "slow" policy in this queue
2540         offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
2541 
2542         mEnableOffloadQueue = SystemProperties.getBoolean(
2543                 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", true);
2544         mEnableModernQueue = foreConstants.MODERN_QUEUE_ENABLED;
2545 
2546         if (mEnableModernQueue) {
2547             mBroadcastQueues = new BroadcastQueue[1];
2548             mBroadcastQueues[0] = new BroadcastQueueModernImpl(this, mHandler,
2549                     foreConstants, backConstants);
2550         } else {
2551             mBroadcastQueues = new BroadcastQueue[4];
2552             mBroadcastQueues[BROADCAST_QUEUE_FG] = new BroadcastQueueImpl(this, mHandler,
2553                     "foreground", foreConstants, false, ProcessList.SCHED_GROUP_DEFAULT);
2554             mBroadcastQueues[BROADCAST_QUEUE_BG] = new BroadcastQueueImpl(this, mHandler,
2555                     "background", backConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
2556             mBroadcastQueues[BROADCAST_QUEUE_BG_OFFLOAD] = new BroadcastQueueImpl(this, mHandler,
2557                     "offload_bg", offloadConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
2558             mBroadcastQueues[BROADCAST_QUEUE_FG_OFFLOAD] = new BroadcastQueueImpl(this, mHandler,
2559                     "offload_fg", foreConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
2560         }
2561 
2562         mServices = new ActiveServices(this);
2563         mCpHelper = new ContentProviderHelper(this, true);
2564         mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
2565         mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
2566         mUidObserverController = new UidObserverController(mUiHandler);
2567 
2568         final File systemDir = SystemServiceManager.ensureSystemDir();
2569 
2570         // TODO: Move creation of battery stats service outside of activity manager service.
2571         mBatteryStatsService = BatteryStatsService.create(systemContext, systemDir,
2572                 BackgroundThread.getHandler(), this);
2573         mOnBattery = DEBUG_POWER ? true
2574                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2575         mOomAdjProfiler.batteryPowerChanged(mOnBattery);
2576 
2577         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2578 
2579         mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops_accesses.xml"),
2580                 new File(systemDir, "appops.xml"), mHandler);
2581 
2582         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2583 
2584         mUserController = new UserController(this);
2585         mInjector.mUserController = mUserController;
2586 
2587         mPendingIntentController = new PendingIntentController(
2588                 mHandlerThread.getLooper(), mUserController, mConstants);
2589 
2590         mAppRestrictionController = new AppRestrictionController(mContext, this);
2591 
2592         mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;
2593 
2594         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2595         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2596 
2597         mActivityTaskManager = atm;
2598         mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
2599                 DisplayThread.get().getLooper());
2600         mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
2601 
2602         mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
2603 
2604         Watchdog.getInstance().addMonitor(this);
2605         Watchdog.getInstance().addThread(mHandler);
2606 
2607         // bind background threads to little cores
2608         // this is expected to fail inside of framework tests because apps can't touch cpusets directly
2609         // make sure we've already adjusted system_server's internal view of itself first
2610         updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT);
2611         try {
2612             Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
2613                     Process.THREAD_GROUP_SYSTEM);
2614             Process.setThreadGroupAndCpuset(
2615                     mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
2616                     Process.THREAD_GROUP_SYSTEM);
2617         } catch (Exception e) {
2618             Slog.w(TAG, "Setting background thread cpuset failed");
2619         }
2620 
2621         mInternal = new LocalService();
2622         mPendingStartActivityUids = new PendingStartActivityUids();
2623         mTraceErrorLogger = new TraceErrorLogger();
2624         mComponentAliasResolver = new ComponentAliasResolver(this);
2625     }
2626 
setSystemServiceManager(SystemServiceManager mgr)2627     public void setSystemServiceManager(SystemServiceManager mgr) {
2628         mSystemServiceManager = mgr;
2629     }
2630 
setInstaller(Installer installer)2631     public void setInstaller(Installer installer) {
2632         mInstaller = installer;
2633     }
2634 
start()2635     private void start() {
2636         mBatteryStatsService.publish();
2637         mAppOpsService.publish();
2638         mProcessStats.publish();
2639         Slog.d("AppOps", "AppOpsService published");
2640         LocalServices.addService(ActivityManagerInternal.class, mInternal);
2641         LocalManagerRegistry.addManager(ActivityManagerLocal.class,
2642                 (ActivityManagerLocal) mInternal);
2643         mActivityTaskManager.onActivityManagerInternalAdded();
2644         mPendingIntentController.onActivityManagerInternalAdded();
2645         mAppProfiler.onActivityManagerInternalAdded();
2646         CriticalEventLog.init();
2647     }
2648 
initPowerManagement()2649     public void initPowerManagement() {
2650         mActivityTaskManager.onInitPowerManagement();
2651         mBatteryStatsService.initPowerManagement();
2652         mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
2653     }
2654 
getBackgroundLaunchBroadcasts()2655     private ArraySet<String> getBackgroundLaunchBroadcasts() {
2656         if (mBackgroundLaunchBroadcasts == null) {
2657             mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts();
2658         }
2659         return mBackgroundLaunchBroadcasts;
2660     }
2661 
2662     /**
2663      * Ensures that the given package name has an explicit set of allowed associations.
2664      * If it does not, give it an empty set.
2665      */
requireAllowedAssociationsLocked(String packageName)2666     void requireAllowedAssociationsLocked(String packageName) {
2667         ensureAllowedAssociations();
2668         if (mAllowedAssociations.get(packageName) == null) {
2669             mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName,
2670                     new ArraySet<>(), /* isDebuggable = */ false));
2671         }
2672     }
2673 
2674     /**
2675      * Returns true if the package {@code pkg1} running under user handle {@code uid1} is
2676      * allowed association with the package {@code pkg2} running under user handle {@code uid2}.
2677      * <p> If either of the packages are running as  part of the core system, then the
2678      * association is implicitly allowed.
2679      */
validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2680     boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) {
2681         ensureAllowedAssociations();
2682         // Interactions with the system uid are always allowed, since that is the core system
2683         // that everyone needs to be able to interact with. Also allow reflexive associations
2684         // within the same uid.
2685         if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID
2686                 || UserHandle.getAppId(uid2) == SYSTEM_UID) {
2687             return true;
2688         }
2689 
2690         // Check for association on both source and target packages.
2691         PackageAssociationInfo pai = mAllowedAssociations.get(pkg1);
2692         if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) {
2693             return false;
2694         }
2695         pai = mAllowedAssociations.get(pkg2);
2696         if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) {
2697             return false;
2698         }
2699         // If no explicit associations are provided in the manifest, then assume the app is
2700         // allowed associations with any package.
2701         return true;
2702     }
2703 
2704     /** Sets up allowed associations for system prebuilt packages from system config (if needed). */
ensureAllowedAssociations()2705     private void ensureAllowedAssociations() {
2706         if (mAllowedAssociations == null) {
2707             ArrayMap<String, ArraySet<String>> allowedAssociations =
2708                     SystemConfig.getInstance().getAllowedAssociations();
2709             mAllowedAssociations = new ArrayMap<>(allowedAssociations.size());
2710             PackageManagerInternal pm = getPackageManagerInternal();
2711             for (int i = 0; i < allowedAssociations.size(); i++) {
2712                 final String pkg = allowedAssociations.keyAt(i);
2713                 final ArraySet<String> asc = allowedAssociations.valueAt(i);
2714 
2715                 // Query latest debuggable flag from package-manager.
2716                 boolean isDebuggable = false;
2717                 try {
2718                     ApplicationInfo ai = AppGlobals.getPackageManager()
2719                             .getApplicationInfo(pkg, MATCH_ALL, 0);
2720                     if (ai != null) {
2721                         isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2722                     }
2723                 } catch (RemoteException e) {
2724                     /* ignore */
2725                 }
2726                 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable));
2727             }
2728         }
2729     }
2730 
2731     /** Updates allowed associations for app info (specifically, based on debuggability).  */
updateAssociationForApp(ApplicationInfo appInfo)2732     private void updateAssociationForApp(ApplicationInfo appInfo) {
2733         ensureAllowedAssociations();
2734         PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName);
2735         if (pai != null) {
2736             pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
2737         }
2738     }
2739 
2740     @Override
onTransact(int code, Parcel data, Parcel reply, int flags)2741     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2742             throws RemoteException {
2743         if (code == SYSPROPS_TRANSACTION) {
2744             // We need to tell all apps about the system property change.
2745             ArrayList<IBinder> procs = new ArrayList<IBinder>();
2746             synchronized (mProcLock) {
2747                 final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
2748                         mProcessList.getProcessNamesLOSP().getMap();
2749                 final int numOfNames = pmap.size();
2750                 for (int ip = 0; ip < numOfNames; ip++) {
2751                     SparseArray<ProcessRecord> apps = pmap.valueAt(ip);
2752                     final int numOfApps = apps.size();
2753                     for (int ia = 0; ia < numOfApps; ia++) {
2754                         ProcessRecord app = apps.valueAt(ia);
2755                         final IApplicationThread thread = app.getThread();
2756                         if (thread != null) {
2757                             procs.add(thread.asBinder());
2758                         }
2759                     }
2760                 }
2761             }
2762 
2763             int N = procs.size();
2764             for (int i=0; i<N; i++) {
2765                 Parcel data2 = Parcel.obtain();
2766                 try {
2767                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null,
2768                             Binder.FLAG_ONEWAY);
2769                 } catch (RemoteException e) {
2770                 }
2771                 data2.recycle();
2772             }
2773         }
2774         try {
2775             return super.onTransact(code, data, reply, flags);
2776         } catch (RuntimeException e) {
2777             // The activity manager only throws certain exceptions intentionally, so let's
2778             // log all others.
2779             if (!(e instanceof SecurityException
2780                     || e instanceof IllegalArgumentException
2781                     || e instanceof IllegalStateException)) {
2782                 Slog.wtf(TAG, "Activity Manager Crash."
2783                         + " UID:" + Binder.getCallingUid()
2784                         + " PID:" + Binder.getCallingPid()
2785                         + " TRANS:" + code, e);
2786             }
2787             throw e;
2788         }
2789     }
2790 
updateCpuStats()2791     void updateCpuStats() {
2792         mAppProfiler.updateCpuStats();
2793     }
2794 
updateCpuStatsNow()2795     void updateCpuStatsNow() {
2796         mAppProfiler.updateCpuStatsNow();
2797     }
2798 
2799     @Override
batteryNeedsCpuUpdate()2800     public void batteryNeedsCpuUpdate() {
2801         updateCpuStatsNow();
2802     }
2803 
2804     @Override
batteryPowerChanged(boolean onBattery)2805     public void batteryPowerChanged(boolean onBattery) {
2806         // When plugging in, update the CPU stats first before changing
2807         // the plug state.
2808         updateCpuStatsNow();
2809         synchronized (mProcLock) {
2810             mOnBattery = DEBUG_POWER ? true : onBattery;
2811             mOomAdjProfiler.batteryPowerChanged(onBattery);
2812         }
2813     }
2814 
2815     @Override
batteryStatsReset()2816     public void batteryStatsReset() {
2817         mOomAdjProfiler.reset();
2818     }
2819 
2820     @Override
batterySendBroadcast(Intent intent)2821     public void batterySendBroadcast(Intent intent) {
2822         synchronized (this) {
2823             broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, null,
2824                     null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
2825                     Binder.getCallingPid(), UserHandle.USER_ALL);
2826         }
2827     }
2828 
2829     /**
2830      * Initialize the application bind args. These are passed to each
2831      * process when the bindApplication() IPC is sent to the process. They're
2832      * lazily setup to make sure the services are running when they're asked for.
2833      */
getCommonServicesLocked(boolean isolated)2834     private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
2835         // Isolated processes won't get this optimization, so that we don't
2836         // violate the rules about which services they have access to.
2837         if (isolated) {
2838             if (mIsolatedAppBindArgs == null) {
2839                 mIsolatedAppBindArgs = new ArrayMap<>(1);
2840                 addServiceToMap(mIsolatedAppBindArgs, "package");
2841                 addServiceToMap(mIsolatedAppBindArgs, "permissionmgr");
2842             }
2843             return mIsolatedAppBindArgs;
2844         }
2845 
2846         if (mAppBindArgs == null) {
2847             mAppBindArgs = new ArrayMap<>();
2848 
2849             // Add common services.
2850             // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too.
2851             // Enable the check in ApplicationThread.bindApplication() to make sure.
2852             addServiceToMap(mAppBindArgs, "package");
2853             addServiceToMap(mAppBindArgs, "permissionmgr");
2854             addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE);
2855             addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE);
2856             addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE);
2857             addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE);
2858             addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE);
2859             addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE);
2860             addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE);
2861             addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE);
2862             addServiceToMap(mAppBindArgs, "graphicsstats");
2863             addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE);
2864             addServiceToMap(mAppBindArgs, "content");
2865             addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE);
2866             addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE);
2867             addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE);
2868             addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE);
2869             addServiceToMap(mAppBindArgs, Context.POWER_SERVICE);
2870             addServiceToMap(mAppBindArgs, Context.USER_SERVICE);
2871             addServiceToMap(mAppBindArgs, "mount");
2872             addServiceToMap(mAppBindArgs, Context.PLATFORM_COMPAT_SERVICE);
2873         }
2874         return mAppBindArgs;
2875     }
2876 
addServiceToMap(ArrayMap<String, IBinder> map, String name)2877     private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) {
2878         final IBinder service = ServiceManager.getService(name);
2879         if (service != null) {
2880             map.put(name, service);
2881             if (false) {
2882                 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache.");
2883             }
2884         }
2885     }
2886 
2887     @Override
setFocusedRootTask(int taskId)2888     public void setFocusedRootTask(int taskId) {
2889         mActivityTaskManager.setFocusedRootTask(taskId);
2890     }
2891 
2892     /** Sets the task stack listener that gets callbacks when a task stack changes. */
2893     @Override
registerTaskStackListener(ITaskStackListener listener)2894     public void registerTaskStackListener(ITaskStackListener listener) {
2895         mActivityTaskManager.registerTaskStackListener(listener);
2896     }
2897 
2898     /**
2899      * Unregister a task stack listener so that it stops receiving callbacks.
2900      */
2901     @Override
unregisterTaskStackListener(ITaskStackListener listener)2902     public void unregisterTaskStackListener(ITaskStackListener listener) {
2903         mActivityTaskManager.unregisterTaskStackListener(listener);
2904     }
2905 
2906     @GuardedBy("this")
updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2907     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
2908             ProcessRecord client) {
2909         mProcessList.updateLruProcessLocked(app, activityChange, client);
2910     }
2911 
2912     @GuardedBy("this")
removeLruProcessLocked(ProcessRecord app)2913     final void removeLruProcessLocked(ProcessRecord app) {
2914         mProcessList.removeLruProcessLocked(app);
2915     }
2916 
2917     @GuardedBy("this")
getProcessRecordLocked(String processName, int uid)2918     final ProcessRecord getProcessRecordLocked(String processName, int uid) {
2919         return mProcessList.getProcessRecordLocked(processName, uid);
2920     }
2921 
2922     @GuardedBy(anyOf = {"this", "mProcLock"})
getProcessNamesLOSP()2923     final ProcessMap<ProcessRecord> getProcessNamesLOSP() {
2924         return mProcessList.getProcessNamesLOSP();
2925     }
2926 
notifyPackageUse(String packageName, int reason)2927     void notifyPackageUse(String packageName, int reason) {
2928         getPackageManagerInternal().notifyPackageUse(packageName, reason);
2929     }
2930 
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2931     boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
2932             String processName, String abiOverride, int uid, Runnable crashHandler) {
2933         synchronized(this) {
2934             ApplicationInfo info = new ApplicationInfo();
2935             // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
2936             // For isolated processes, the former contains the parent's uid and the latter the
2937             // actual uid of the isolated process.
2938             // In the special case introduced by this method (which is, starting an isolated
2939             // process directly from the SystemServer without an actual parent app process) the
2940             // closest thing to a parent's uid is SYSTEM_UID.
2941             // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
2942             // the |isolated| logic in the ProcessRecord constructor.
2943             info.uid = SYSTEM_UID;
2944             info.processName = processName;
2945             info.className = entryPoint;
2946             info.packageName = "android";
2947             info.seInfoUser = SELinuxUtil.COMPLETE_STR;
2948             info.targetSdkVersion = Build.VERSION.SDK_INT;
2949             ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */,
2950                     false /* knownToBeDead */, 0 /* intentFlags */,
2951                     sNullHostingRecord  /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY,
2952                     true /* allowWhileBooting */, true /* isolated */,
2953                     uid, false /* isSdkSandbox */, 0 /* sdkSandboxUid */,
2954                     null /* sdkSandboxClientAppPackage */,
2955                     abiOverride, entryPoint, entryPointArgs, crashHandler);
2956             return proc != null;
2957         }
2958     }
2959 
2960     @GuardedBy("this")
startSdkSandboxProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid, String sdkSandboxClientAppPackage)2961     final ProcessRecord startSdkSandboxProcessLocked(String processName,
2962             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
2963             HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid,
2964             String sdkSandboxClientAppPackage) {
2965         return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
2966                 hostingRecord, zygotePolicyFlags, false /* allowWhileBooting */,
2967                 false /* isolated */, 0 /* isolatedUid */,
2968                 true /* isSdkSandbox */, sdkSandboxUid, sdkSandboxClientAppPackage,
2969                 null /* ABI override */, null /* entryPoint */,
2970                 null /* entryPointArgs */, null /* crashHandler */);
2971     }
2972 
2973     @GuardedBy("this")
startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated)2974     final ProcessRecord startProcessLocked(String processName,
2975             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
2976             HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
2977             boolean isolated) {
2978         return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
2979                 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
2980                 false /* isSdkSandbox */, 0 /* sdkSandboxClientAppUid */,
2981                 null /* sdkSandboxClientAppPackage */,
2982                 null /* ABI override */, null /* entryPoint */,
2983                 null /* entryPointArgs */, null /* crashHandler */);
2984     }
2985 
isAllowedWhileBooting(ApplicationInfo ai)2986     boolean isAllowedWhileBooting(ApplicationInfo ai) {
2987         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2988     }
2989 
2990     /**
2991      * Update battery stats on the activity' usage.
2992      * @param activity
2993      * @param uid
2994      * @param userId
2995      * @param resumed
2996      */
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)2997     void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) {
2998         if (DEBUG_SWITCH) {
2999             Slog.d(TAG_SWITCH,
3000                     "updateBatteryStats: comp=" + activity + "res=" + resumed);
3001         }
3002         mBatteryStatsService.updateBatteryStatsOnActivityUsage(activity.getPackageName(),
3003                 activity.getShortClassName(), uid, userId, resumed);
3004     }
3005 
3006     /**
3007      * Update UsageStas on the activity's usage.
3008      * @param activity
3009      * @param userId
3010      * @param event
3011      * @param appToken ActivityRecord's appToken.
3012      * @param taskRoot Task's root
3013      */
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)3014     public void updateActivityUsageStats(ComponentName activity, int userId, int event,
3015             IBinder appToken, ComponentName taskRoot, ActivityId activityId) {
3016         if (DEBUG_SWITCH) {
3017             Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp="
3018                     + activity + " hash=" + appToken.hashCode() + " event=" + event);
3019         }
3020         if (mUsageStatsService != null) {
3021             mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(), taskRoot);
3022             if (event == Event.ACTIVITY_RESUMED) {
3023                 // Report component usage as an activity is an app component
3024                 mUsageStatsService.reportEvent(
3025                         activity.getPackageName(), userId, Event.APP_COMPONENT_USED);
3026             }
3027         }
3028         ContentCaptureManagerInternal contentCaptureService = mContentCaptureService;
3029         if (contentCaptureService != null && (event == Event.ACTIVITY_PAUSED
3030                 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED
3031                 || event == Event.ACTIVITY_DESTROYED)) {
3032             contentCaptureService.notifyActivityEvent(userId, activity, event, activityId);
3033         }
3034         // Currently we have move most of logic to the client side. When the activity lifecycle
3035         // event changed, the client side will notify the VoiceInteractionManagerService. But
3036         // when the application process died, the VoiceInteractionManagerService will miss the
3037         // activity lifecycle event changed, so we still need ACTIVITY_DESTROYED event here to
3038         // know if the activity has been destroyed.
3039         if (mVoiceInteractionManagerProvider != null && event == Event.ACTIVITY_DESTROYED) {
3040             mVoiceInteractionManagerProvider.notifyActivityDestroyed(appToken);
3041         }
3042     }
3043 
3044     /**
3045      * Update UsageStats on this package's usage.
3046      * @param packageName
3047      * @param userId
3048      * @param event
3049      */
updateActivityUsageStats(String packageName, int userId, int event)3050     public void updateActivityUsageStats(String packageName, int userId, int event) {
3051         if (DEBUG_SWITCH) {
3052             Slog.d(TAG_SWITCH, "updateActivityUsageStats: package="
3053                     + packageName + " event=" + event);
3054         }
3055         if (mUsageStatsService != null) {
3056             mUsageStatsService.reportEvent(packageName, userId, event);
3057         }
3058     }
3059 
3060     /**
3061      * Update Usages on this foreground service's usage.
3062      * @param service
3063      * @param userId
3064      * @param started
3065      */
updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)3066     void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) {
3067         if (DEBUG_SWITCH) {
3068             Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp="
3069                     + service + " started=" + started);
3070         }
3071         if (mUsageStatsService != null) {
3072             mUsageStatsService.reportEvent(service, userId,
3073                     started ? UsageEvents.Event.FOREGROUND_SERVICE_START
3074                             : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null);
3075         }
3076     }
3077 
compatibilityInfoForPackage(ApplicationInfo ai)3078     CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
3079         return mAtmInternal.compatibilityInfoForPackage(ai);
3080     }
3081 
3082     /**
3083      * Enforces that the uid that calls a method is not an
3084      * {@link UserHandle#isIsolated(int) isolated} uid.
3085      *
3086      * @param caller the name of the method being called.
3087      * @throws SecurityException if the calling uid is an isolated uid.
3088      */
enforceNotIsolatedCaller(String caller)3089     /* package */ void enforceNotIsolatedCaller(String caller) {
3090         if (UserHandle.isIsolated(Binder.getCallingUid())) {
3091             throw new SecurityException("Isolated process not allowed to call " + caller);
3092         }
3093     }
3094 
3095     /**
3096      * Enforces that the uid that calls a method is not an
3097      * {@link UserHandle#isIsolated(int) isolated} uid or an
3098      * {@link Process#isSdkSandboxUid(int) SDK sandbox} uid.
3099      *
3100      * @param caller the name of the method being called.
3101      * @throws SecurityException if the calling uid is an isolated uid or SDK sandbox uid.
3102      */
enforceNotIsolatedOrSdkSandboxCaller(String caller)3103     void enforceNotIsolatedOrSdkSandboxCaller(String caller) {
3104         enforceNotIsolatedCaller(caller);
3105 
3106         if (Process.isSdkSandboxUid(Binder.getCallingUid())) {
3107             throw new SecurityException("SDK sandbox process not allowed to call " + caller);
3108         }
3109     }
3110 
3111     /**
3112      * If the caller is an {@link Process#isSdkSandboxUid(int) SDK sandbox uid}, enforces that the
3113      * SDK sandbox has permission to start or bind to a given service.
3114      *
3115      * @param intent the intent used to start or bind to the service.
3116      * @throws IllegalStateException if {@link SdkSandboxManagerLocal} cannot be resolved.
3117      * @throws SecurityException if the SDK sandbox is not allowed to bind to this service.
3118      */
enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent)3119     private void enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent) {
3120         if (Process.isSdkSandboxUid(Binder.getCallingUid())) {
3121             SdkSandboxManagerLocal sdkSandboxManagerLocal =
3122                     LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class);
3123             if (sdkSandboxManagerLocal != null) {
3124                 sdkSandboxManagerLocal.enforceAllowedToStartOrBindService(intent);
3125             } else {
3126                 throw new IllegalStateException("SdkSandboxManagerLocal not found when checking"
3127                         + " whether SDK sandbox uid may start or bind to a service.");
3128             }
3129         }
3130     }
3131 
3132     /**
3133      * Enforces that the uid of the caller matches the uid of the package.
3134      *
3135      * @param packageName the name of the package to match uid against.
3136      * @param callingUid the uid of the caller.
3137      * @throws SecurityException if the calling uid doesn't match uid of the package.
3138      */
enforceCallingPackage(String packageName, int callingUid)3139     private void enforceCallingPackage(String packageName, int callingUid) {
3140         final int userId = UserHandle.getUserId(callingUid);
3141         final int packageUid = getPackageManagerInternal().getPackageUid(packageName,
3142                 /*flags=*/ 0, userId);
3143         if (packageUid != callingUid) {
3144             throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3145         }
3146     }
3147 
3148     @Override
setPackageScreenCompatMode(String packageName, int mode)3149     public void setPackageScreenCompatMode(String packageName, int mode) {
3150         mActivityTaskManager.setPackageScreenCompatMode(packageName, mode);
3151     }
3152 
hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid)3153     private boolean hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid) {
3154         final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS,
3155                 callingUid, callingPackage, null, false, "", false).getOpMode();
3156         if (mode == AppOpsManager.MODE_DEFAULT) {
3157             return checkPermission(Manifest.permission.PACKAGE_USAGE_STATS, callingPid, callingUid)
3158                     == PackageManager.PERMISSION_GRANTED;
3159         }
3160         return mode == AppOpsManager.MODE_ALLOWED;
3161     }
3162 
hasUsageStatsPermission(String callingPackage)3163     private boolean hasUsageStatsPermission(String callingPackage) {
3164         return hasUsageStatsPermission(callingPackage,
3165                 Binder.getCallingUid(), Binder.getCallingPid());
3166     }
3167 
enforceUsageStatsPermission(String callingPackage, int callingUid, int callingPid, String operation)3168     private void enforceUsageStatsPermission(String callingPackage,
3169             int callingUid, int callingPid, String operation) {
3170         if (!hasUsageStatsPermission(callingPackage, callingUid, callingPid)) {
3171             final String errorMsg = "Permission denial for <" + operation + "> from pid="
3172                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3173                     + " which requires PACKAGE_USAGE_STATS permission";
3174             throw new SecurityException(errorMsg);
3175         }
3176     }
3177 
3178     @Override
getPackageProcessState(String packageName, String callingPackage)3179     public int getPackageProcessState(String packageName, String callingPackage) {
3180         if (!hasUsageStatsPermission(callingPackage)) {
3181             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
3182                     "getPackageProcessState");
3183         }
3184 
3185         final int[] procState = {PROCESS_STATE_NONEXISTENT};
3186         synchronized (mProcLock) {
3187             mProcessList.forEachLruProcessesLOSP(false, proc -> {
3188                 if (procState[0] > proc.mState.getSetProcState()) {
3189                     if (proc.getPkgList().containsKey(packageName) || (proc.getPkgDeps() != null
3190                                 && proc.getPkgDeps().contains(packageName))) {
3191                         procState[0] = proc.mState.getSetProcState();
3192                     }
3193                 }
3194             });
3195         }
3196         return procState[0];
3197     }
3198 
3199     @Override
setProcessMemoryTrimLevel(String process, int userId, int level)3200     public boolean setProcessMemoryTrimLevel(String process, int userId, int level)
3201             throws RemoteException {
3202         if (!isCallerShell()) {
3203             throw new SecurityException("Only shell can call it");
3204         }
3205         synchronized (this) {
3206             final ProcessRecord app = findProcessLOSP(process, userId, "setProcessMemoryTrimLevel");
3207             if (app == null) {
3208                 throw new IllegalArgumentException("Unknown process: " + process);
3209             }
3210             final IApplicationThread thread = app.getThread();
3211             if (thread == null) {
3212                 throw new IllegalArgumentException("Process has no app thread");
3213             }
3214             if (app.mProfile.getTrimMemoryLevel() >= level) {
3215                 throw new IllegalArgumentException(
3216                         "Unable to set a higher trim level than current level");
3217             }
3218             if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
3219                     app.mState.getCurProcState() > PROCESS_STATE_IMPORTANT_FOREGROUND)) {
3220                 throw new IllegalArgumentException("Unable to set a background trim level "
3221                     + "on a foreground process");
3222             }
3223             thread.scheduleTrimMemory(level);
3224             synchronized (mProcLock) {
3225                 app.mProfile.setTrimMemoryLevel(level);
3226             }
3227             return true;
3228         }
3229     }
3230 
dispatchOomAdjObserver(String msg)3231     void dispatchOomAdjObserver(String msg) {
3232         OomAdjObserver observer;
3233         synchronized (mOomAdjObserverLock) {
3234             observer = mCurOomAdjObserver;
3235         }
3236 
3237         if (observer != null) {
3238             observer.onOomAdjMessage(msg);
3239         }
3240     }
3241 
setOomAdjObserver(int uid, OomAdjObserver observer)3242     void setOomAdjObserver(int uid, OomAdjObserver observer) {
3243         synchronized (mOomAdjObserverLock) {
3244             mCurOomAdjUid = uid;
3245             mCurOomAdjObserver = observer;
3246         }
3247     }
3248 
clearOomAdjObserver()3249     void clearOomAdjObserver() {
3250         synchronized (mOomAdjObserverLock) {
3251             mCurOomAdjUid = -1;
3252             mCurOomAdjObserver = null;
3253         }
3254     }
3255 
reportUidInfoMessageLocked(String tag, String msg, int uid)3256     void reportUidInfoMessageLocked(String tag, String msg, int uid) {
3257         Slog.i(TAG, msg);
3258         synchronized (mOomAdjObserverLock) {
3259             if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) {
3260                 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
3261             }
3262         }
3263     }
3264 
3265     /**
3266      * @deprecated use {@link #startActivityWithFeature} instead
3267      */
3268     @Deprecated
3269     @Override
startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3270     public int startActivity(IApplicationThread caller, String callingPackage,
3271             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3272             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
3273         return mActivityTaskManager.startActivity(caller, callingPackage, null, intent,
3274                 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
3275     }
3276 
3277     @Override
startActivityWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3278     public int startActivityWithFeature(IApplicationThread caller, String callingPackage,
3279             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
3280             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
3281             Bundle bOptions) {
3282         return mActivityTaskManager.startActivity(caller, callingPackage, callingFeatureId, intent,
3283                 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
3284     }
3285 
3286     /**
3287      * @deprecated use {@link #startActivityAsUserWithFeature} instead
3288      */
3289     @Deprecated
3290     @Override
startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3291     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3292             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3293             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3294         return startActivityAsUserWithFeature(caller, callingPackage, null, intent, resolvedType,
3295                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId);
3296     }
3297 
3298     @Override
startActivityAsUserWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3299     public final int startActivityAsUserWithFeature(IApplicationThread caller,
3300             String callingPackage, String callingFeatureId, Intent intent, String resolvedType,
3301             IBinder resultTo, String resultWho, int requestCode, int startFlags,
3302             ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3303         return mActivityTaskManager.startActivityAsUser(caller, callingPackage,
3304                     callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode,
3305                     startFlags, profilerInfo, bOptions, userId);
3306     }
3307 
startActivityAndWait(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3308     WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
3309             @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
3310             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
3311             Bundle bOptions, int userId) {
3312             return mActivityTaskManager.startActivityAndWait(caller, callingPackage,
3313                     callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode,
3314                     startFlags, profilerInfo, bOptions, userId);
3315     }
3316 
3317     @Override
startActivityFromRecents(int taskId, Bundle bOptions)3318     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
3319         return mActivityTaskManager.startActivityFromRecents(taskId, bOptions);
3320     }
3321 
3322     /**
3323      * This is the internal entry point for handling Activity.finish().
3324      *
3325      * @param token The Binder token referencing the Activity we want to finish.
3326      * @param resultCode Result code, if any, from this Activity.
3327      * @param resultData Result data (Intent), if any, from this Activity.
3328      * @param finishTask Whether to finish the task associated with this Activity.
3329      *
3330      * @return Returns true if the activity successfully finished, or false if it is still running.
3331      */
3332     @Override
finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3333     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
3334             int finishTask) {
3335         return ActivityClient.getInstance().finishActivity(token, resultCode, resultData,
3336                 finishTask);
3337     }
3338 
3339     @Override
setRequestedOrientation(IBinder token, int requestedOrientation)3340     public void setRequestedOrientation(IBinder token, int requestedOrientation) {
3341         ActivityClient.getInstance().setRequestedOrientation(token, requestedOrientation);
3342     }
3343 
3344     @Override
finishHeavyWeightApp()3345     public final void finishHeavyWeightApp() {
3346         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3347                 != PackageManager.PERMISSION_GRANTED) {
3348             String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3349                     + Binder.getCallingPid()
3350                     + ", uid=" + Binder.getCallingUid()
3351                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3352             Slog.w(TAG, msg);
3353             throw new SecurityException(msg);
3354         }
3355         mAtmInternal.finishHeavyWeightApp();
3356     }
3357 
3358     @Override
crashApplicationWithType(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId)3359     public void crashApplicationWithType(int uid, int initialPid, String packageName, int userId,
3360             String message, boolean force, int exceptionTypeId) {
3361         crashApplicationWithTypeWithExtras(uid, initialPid, packageName, userId, message,
3362                 force, exceptionTypeId, null);
3363     }
3364 
3365     @Override
crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId, @Nullable Bundle extras)3366     public void crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName,
3367             int userId, String message, boolean force, int exceptionTypeId,
3368             @Nullable Bundle extras) {
3369         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3370                 != PackageManager.PERMISSION_GRANTED) {
3371             String msg = "Permission Denial: crashApplication() from pid="
3372                     + Binder.getCallingPid()
3373                     + ", uid=" + Binder.getCallingUid()
3374                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3375             Slog.w(TAG, msg);
3376             throw new SecurityException(msg);
3377         }
3378 
3379         synchronized(this) {
3380             mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId,
3381                     message, force, exceptionTypeId, extras);
3382         }
3383     }
3384 
3385     /**
3386      * Main function for removing an existing process from the activity manager
3387      * as a result of that process going away.  Clears out all connections
3388      * to the process.
3389      */
3390     @GuardedBy("this")
handleAppDiedLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, boolean fromBinderDied)3391     final void handleAppDiedLocked(ProcessRecord app, int pid,
3392             boolean restarting, boolean allowRestart, boolean fromBinderDied) {
3393         boolean kept = cleanUpApplicationRecordLocked(app, pid, restarting, allowRestart, -1,
3394                 false /*replacingPid*/, fromBinderDied);
3395         if (!kept && !restarting) {
3396             removeLruProcessLocked(app);
3397             if (pid > 0) {
3398                 ProcessList.remove(pid);
3399             }
3400         }
3401 
3402         mAppProfiler.onAppDiedLocked(app);
3403 
3404         mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> {
3405             Slog.w(TAG, "Crash of app " + app.processName
3406                     + " running instrumentation " + app.getActiveInstrumentation().mClass);
3407             Bundle info = new Bundle();
3408             info.putString("shortMsg", "Process crashed.");
3409             finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3410         });
3411     }
3412 
3413     @GuardedBy(anyOf = {"this", "mProcLock"})
getRecordForAppLOSP(IApplicationThread thread)3414     ProcessRecord getRecordForAppLOSP(IApplicationThread thread) {
3415         if (thread == null) {
3416             return null;
3417         }
3418         return getRecordForAppLOSP(thread.asBinder());
3419     }
3420 
3421     @GuardedBy(anyOf = {"this", "mProcLock"})
getRecordForAppLOSP(IBinder threadBinder)3422     ProcessRecord getRecordForAppLOSP(IBinder threadBinder) {
3423         if (threadBinder == null) {
3424             return null;
3425         }
3426 
3427         ProcessRecord record = mProcessList.getLRURecordForAppLOSP(threadBinder);
3428         if (record != null) return record;
3429 
3430         // Validation: if it isn't in the LRU list, it shouldn't exist, but let's double-check that.
3431         final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
3432                 mProcessList.getProcessNamesLOSP().getMap();
3433         for (int i = pmap.size()-1; i >= 0; i--) {
3434             final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
3435             for (int j = procs.size()-1; j >= 0; j--) {
3436                 final ProcessRecord proc = procs.valueAt(j);
3437                 final IApplicationThread procThread = proc.getThread();
3438                 if (procThread != null && procThread.asBinder() == threadBinder) {
3439                     if (!proc.isPendingFinishAttach()) {
3440                         Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
3441                                 + proc);
3442                     }
3443                     return proc;
3444                 }
3445             }
3446         }
3447 
3448         return null;
3449     }
3450 
3451     @GuardedBy("this")
appDiedLocked(ProcessRecord app, String reason)3452     final void appDiedLocked(ProcessRecord app, String reason) {
3453         appDiedLocked(app, app.getPid(), app.getThread(), false, reason);
3454     }
3455 
3456     @GuardedBy("this")
appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied, String reason)3457     final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread,
3458             boolean fromBinderDied, String reason) {
3459         // First check if this ProcessRecord is actually active for the pid.
3460         final ProcessRecord curProc;
3461         synchronized (mPidsSelfLocked) {
3462             curProc = mPidsSelfLocked.get(pid);
3463         }
3464         if (curProc != app) {
3465             if (!fromBinderDied || !mProcessList.handleDyingAppDeathLocked(app, pid)) {
3466                 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
3467             }
3468             return;
3469         }
3470 
3471         mBatteryStatsService.noteProcessDied(app.info.uid, pid);
3472 
3473         if (!app.isKilled()) {
3474             if (!fromBinderDied) {
3475                 killProcessQuiet(pid);
3476                 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_OTHER,
3477                         ApplicationExitInfo.SUBREASON_UNKNOWN, reason);
3478             }
3479             app.killProcessGroupIfNecessaryLocked(true);
3480             synchronized (mProcLock) {
3481                 app.setKilled(true);
3482             }
3483         }
3484 
3485         // Clean up already done if the process has been re-started.
3486         IApplicationThread appThread;
3487         final int setAdj = app.mState.getSetAdj();
3488         final int setProcState = app.mState.getSetProcState();
3489         if (app.getPid() == pid && (appThread = app.getThread()) != null
3490                 && appThread.asBinder() == thread.asBinder()) {
3491             boolean doLowMem = app.getActiveInstrumentation() == null;
3492             boolean doOomAdj = doLowMem;
3493             if (!app.isKilledByAm()) {
3494                 reportUidInfoMessageLocked(TAG,
3495                         "Process " + app.processName + " (pid " + pid + ") has died: "
3496                         + ProcessList.makeOomAdjString(setAdj, true) + " "
3497                         + ProcessList.makeProcStateString(setProcState), app.info.uid);
3498                 mAppProfiler.setAllowLowerMemLevelLocked(true);
3499             } else {
3500                 // Note that we always want to do oom adj to update our state with the
3501                 // new number of procs.
3502                 mAppProfiler.setAllowLowerMemLevelLocked(false);
3503                 doLowMem = false;
3504             }
3505             EventLogTags.writeAmProcDied(app.userId, pid, app.processName, setAdj, setProcState);
3506             if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
3507                 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
3508             handleAppDiedLocked(app, pid, false, true, fromBinderDied);
3509 
3510             if (doOomAdj) {
3511                 updateOomAdjLocked(OOM_ADJ_REASON_PROCESS_END);
3512             }
3513             if (doLowMem) {
3514                 mAppProfiler.doLowMemReportIfNeededLocked(app);
3515             }
3516         } else if (app.getPid() != pid) {
3517             // A new process has already been started.
3518             reportUidInfoMessageLocked(TAG,
3519                     "Process " + app.processName + " (pid " + pid
3520                             + ") has died and restarted (pid " + app.getPid() + ").", app.info.uid);
3521 
3522             EventLogTags.writeAmProcDied(app.userId, app.getPid(), app.processName,
3523                     setAdj, setProcState);
3524         } else if (DEBUG_PROCESSES) {
3525             Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
3526                     + thread.asBinder());
3527         }
3528 
3529         // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal
3530         // for pulling memory stats of other running processes when this process died.
3531         if (!hasMemcg()) {
3532             FrameworkStatsLog.write(FrameworkStatsLog.APP_DIED, SystemClock.elapsedRealtime());
3533         }
3534     }
3535 
3536     @Override
clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)3537     public boolean clearApplicationUserData(final String packageName, boolean keepState,
3538             final IPackageDataObserver observer, int userId) {
3539         return clearApplicationUserData(packageName, keepState, /*isRestore=*/ false, observer,
3540                 userId);
3541     }
3542 
clearApplicationUserData(final String packageName, boolean keepState, boolean isRestore, final IPackageDataObserver observer, int userId)3543     private boolean clearApplicationUserData(final String packageName, boolean keepState,
3544             boolean isRestore, final IPackageDataObserver observer, int userId) {
3545         enforceNotIsolatedCaller("clearApplicationUserData");
3546         int uid = Binder.getCallingUid();
3547         int pid = Binder.getCallingPid();
3548         final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false,
3549                 ALLOW_FULL_ONLY, "clearApplicationUserData", null);
3550 
3551         final ApplicationInfo appInfo;
3552         final boolean isInstantApp;
3553 
3554         final long callingId = Binder.clearCallingIdentity();
3555         try {
3556             IPackageManager pm = AppGlobals.getPackageManager();
3557             boolean permitted = true;
3558             // Instant packages are not protected
3559             if (getPackageManagerInternal().isPackageDataProtected(
3560                     resolvedUserId, packageName)) {
3561                 if (ActivityManager.checkUidPermission(android.Manifest.permission.MANAGE_USERS,
3562                         uid) == PERMISSION_GRANTED) {
3563                     // The caller has the MANAGE_USERS permission, tell them what's going on.
3564                     throw new SecurityException(
3565                             "Cannot clear data for a protected package: " + packageName);
3566                 } else {
3567                     permitted = false; // fall through and throw the SecurityException below.
3568                 }
3569             }
3570 
3571             ApplicationInfo applicationInfo = null;
3572             if (permitted) {
3573                 try {
3574                     applicationInfo = pm.getApplicationInfo(packageName,
3575                             MATCH_UNINSTALLED_PACKAGES, resolvedUserId);
3576                 } catch (RemoteException e) {
3577                     /* ignore */
3578                 }
3579                 permitted = (applicationInfo != null && applicationInfo.uid == uid) // own uid data
3580                         || (checkComponentPermission(permission.CLEAR_APP_USER_DATA,
3581                                 pid, uid, -1, true) == PackageManager.PERMISSION_GRANTED);
3582             }
3583 
3584             if (!permitted) {
3585                 throw new SecurityException("PID " + pid + " does not have permission "
3586                         + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
3587                         + " of package " + packageName);
3588             }
3589             appInfo = applicationInfo;
3590 
3591             final boolean hasInstantMetadata = getPackageManagerInternal()
3592                     .hasInstantApplicationMetadata(packageName, resolvedUserId);
3593             final boolean isUninstalledAppWithoutInstantMetadata =
3594                     (appInfo == null && !hasInstantMetadata);
3595             isInstantApp = (appInfo != null && appInfo.isInstantApp())
3596                     || hasInstantMetadata;
3597             final boolean canAccessInstantApps = checkComponentPermission(
3598                     permission.ACCESS_INSTANT_APPS, pid, uid, -1, true)
3599                     == PackageManager.PERMISSION_GRANTED;
3600 
3601             if (isUninstalledAppWithoutInstantMetadata || (isInstantApp
3602                         && !canAccessInstantApps)) {
3603                 Slog.w(TAG, "Invalid packageName: " + packageName);
3604                 if (observer != null) {
3605                     try {
3606                         observer.onRemoveCompleted(packageName, false);
3607                     } catch (RemoteException e) {
3608                         Slog.i(TAG, "Observer no longer exists.");
3609                     }
3610                 }
3611                 return false;
3612             }
3613 
3614             synchronized (this) {
3615                 if (appInfo != null) {
3616                     forceStopPackageLocked(packageName, appInfo.uid, "clear data");
3617                     mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId);
3618                 }
3619             }
3620 
3621             final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() {
3622                 @Override
3623                 public void onRemoveCompleted(String packageName, boolean succeeded)
3624                         throws RemoteException {
3625                     if (appInfo != null) {
3626                         synchronized (ActivityManagerService.this) {
3627                             finishForceStopPackageLocked(packageName, appInfo.uid);
3628                         }
3629                     }
3630 
3631                     if (succeeded) {
3632                         final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3633                                 Uri.fromParts("package", packageName, null /* fragment */));
3634                         intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3635                                 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3636                         intent.putExtra(Intent.EXTRA_UID,
3637                                 (appInfo != null) ? appInfo.uid : INVALID_UID);
3638                         intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId);
3639                         if (isRestore) {
3640                             intent.putExtra(Intent.EXTRA_IS_RESTORE, true);
3641                         }
3642                         if (isInstantApp) {
3643                             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
3644                         }
3645                         final int[] visibilityAllowList = mPackageManagerInt.getVisibilityAllowList(
3646                                 packageName, resolvedUserId);
3647 
3648                         broadcastIntentInPackage("android", null /* featureId */,
3649                                 SYSTEM_UID, uid, pid, intent, null /* resolvedType */,
3650                                 null /* resultToApp */, null /* resultTo */, 0 /* resultCode */,
3651                                 null /* resultData */, null /* resultExtras */,
3652                                 isInstantApp ? permission.ACCESS_INSTANT_APPS : null,
3653                                 null /* bOptions */, false /* serialized */, false /* sticky */,
3654                                 resolvedUserId, BackgroundStartPrivileges.NONE,
3655                                 visibilityAllowList);
3656                     }
3657 
3658                     if (observer != null) {
3659                         observer.onRemoveCompleted(packageName, succeeded);
3660                     }
3661                 }
3662             };
3663 
3664             try {
3665                 // Clear application user data
3666                 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId);
3667 
3668                 if (appInfo != null) {
3669                     // Restore already established notification state and permission grants,
3670                     // so it told us to keep those intact -- it's about to emplace app data
3671                     // that is appropriate for those bits of system state.
3672                     if (!keepState) {
3673                         // Remove all permissions granted from/to this package
3674                         mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId,
3675                                 true, false);
3676 
3677                         // Reset notification state
3678                         INotificationManager inm = NotificationManager.getService();
3679                         inm.clearData(packageName, appInfo.uid, uid == appInfo.uid);
3680                     }
3681 
3682                     // Clear its scheduled jobs
3683                     JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
3684                     // Clearing data is a user-initiated action.
3685                     js.cancelJobsForUid(appInfo.uid, /* includeProxiedJobs */ true,
3686                             JobParameters.STOP_REASON_USER,
3687                             JobParameters.INTERNAL_STOP_REASON_DATA_CLEARED, "clear data");
3688 
3689                     // Clear its pending alarms
3690                     AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class);
3691                     ami.removeAlarmsForUid(appInfo.uid);
3692                 }
3693             } catch (RemoteException e) {
3694             }
3695         } finally {
3696             Binder.restoreCallingIdentity(callingId);
3697         }
3698         return true;
3699     }
3700 
3701     @Override
killBackgroundProcesses(final String packageName, int userId)3702     public void killBackgroundProcesses(final String packageName, int userId) {
3703         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3704                 != PackageManager.PERMISSION_GRANTED &&
3705                 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3706                         != PackageManager.PERMISSION_GRANTED) {
3707             String msg = "Permission Denial: killBackgroundProcesses() from pid="
3708                     + Binder.getCallingPid()
3709                     + ", uid=" + Binder.getCallingUid()
3710                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3711             Slog.w(TAG, msg);
3712             throw new SecurityException(msg);
3713         }
3714         final boolean hasKillAllPermission = checkCallingPermission(
3715                 android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES) == PERMISSION_GRANTED;
3716         final int callingUid = Binder.getCallingUid();
3717         final int callingAppId = UserHandle.getAppId(callingUid);
3718 
3719         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid,
3720                 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
3721         final int[] userIds = mUserController.expandUserId(userId);
3722 
3723         final long callingId = Binder.clearCallingIdentity();
3724         try {
3725             IPackageManager pm = AppGlobals.getPackageManager();
3726             for (int targetUserId : userIds) {
3727                 int appId = -1;
3728                 try {
3729                     appId = UserHandle.getAppId(
3730                             pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
3731                                     targetUserId));
3732                 } catch (RemoteException e) {
3733                 }
3734                 if (appId == -1 || (!hasKillAllPermission && appId != callingAppId)) {
3735                     Slog.w(TAG, "Invalid packageName: " + packageName);
3736                     return;
3737                 }
3738                 synchronized (this) {
3739                     synchronized (mProcLock) {
3740                         mProcessList.killPackageProcessesLSP(packageName, appId, targetUserId,
3741                                 ProcessList.SERVICE_ADJ, ApplicationExitInfo.REASON_USER_REQUESTED,
3742                                 ApplicationExitInfo.SUBREASON_KILL_BACKGROUND, "kill background");
3743                     }
3744                 }
3745             }
3746         } finally {
3747             Binder.restoreCallingIdentity(callingId);
3748         }
3749     }
3750 
3751     @Override
killAllBackgroundProcesses()3752     public void killAllBackgroundProcesses() {
3753         if (checkCallingPermission(android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES)
3754                 != PackageManager.PERMISSION_GRANTED) {
3755             final String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3756                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3757                     + " requires " + android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES;
3758             Slog.w(TAG, msg);
3759             throw new SecurityException(msg);
3760         }
3761 
3762         final long callingId = Binder.clearCallingIdentity();
3763         try {
3764             synchronized (this) {
3765                 // Allow memory level to go down (the flag needs to be set before updating oom adj)
3766                 // because this method is also used to simulate low memory.
3767                 mAppProfiler.setAllowLowerMemLevelLocked(true);
3768                 synchronized (mProcLock) {
3769                     mProcessList.killPackageProcessesLSP(null /* packageName */, -1 /* appId */,
3770                             UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ,
3771                             ApplicationExitInfo.REASON_USER_REQUESTED,
3772                             ApplicationExitInfo.SUBREASON_KILL_BACKGROUND,
3773                             "kill all background");
3774                 }
3775 
3776                 mAppProfiler.doLowMemReportIfNeededLocked(null);
3777             }
3778         } finally {
3779             Binder.restoreCallingIdentity(callingId);
3780         }
3781     }
3782 
3783     /**
3784      * Kills all background processes, except those matching any of the
3785      * specified properties.
3786      *
3787      * @param minTargetSdk the target SDK version at or above which to preserve
3788      *                     processes, or {@code -1} to ignore the target SDK
3789      * @param maxProcState the process state at or below which to preserve
3790      *                     processes, or {@code -1} to ignore the process state
3791      */
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)3792     void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
3793         if (checkCallingPermission(android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES)
3794                 != PackageManager.PERMISSION_GRANTED) {
3795             final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid="
3796                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3797                     + " requires " + android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES;
3798             Slog.w(TAG, msg);
3799             throw new SecurityException(msg);
3800         }
3801 
3802         final long callingId = Binder.clearCallingIdentity();
3803         try {
3804             synchronized (this) {
3805                 synchronized (mProcLock) {
3806                     mProcessList.killAllBackgroundProcessesExceptLSP(minTargetSdk, maxProcState);
3807                 }
3808             }
3809         } finally {
3810             Binder.restoreCallingIdentity(callingId);
3811         }
3812     }
3813 
3814     @Override
stopAppForUser(final String packageName, int userId)3815     public void stopAppForUser(final String packageName, int userId) {
3816         if (checkCallingPermission(MANAGE_ACTIVITY_TASKS)
3817                 != PackageManager.PERMISSION_GRANTED) {
3818             String msg = "Permission Denial: stopAppForUser() from pid="
3819                     + Binder.getCallingPid()
3820                     + ", uid=" + Binder.getCallingUid()
3821                     + " requires " + MANAGE_ACTIVITY_TASKS;
3822             Slog.w(TAG, msg);
3823             throw new SecurityException(msg);
3824         }
3825 
3826         final int callingPid = Binder.getCallingPid();
3827         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
3828                 userId, true, ALLOW_FULL_ONLY, "stopAppForUser", null);
3829         final long callingId = Binder.clearCallingIdentity();
3830         try {
3831             stopAppForUserInternal(packageName, userId);
3832         } finally {
3833             Binder.restoreCallingIdentity(callingId);
3834         }
3835     }
3836 
3837     @Override
registerForegroundServiceObserver(IForegroundServiceObserver callback)3838     public boolean registerForegroundServiceObserver(IForegroundServiceObserver callback) {
3839         final int callingUid = Binder.getCallingUid();
3840         final int permActivityTasks = checkCallingPermission(MANAGE_ACTIVITY_TASKS);
3841         final int permAcrossUsersFull = checkCallingPermission(INTERACT_ACROSS_USERS_FULL);
3842         if (permActivityTasks != PackageManager.PERMISSION_GRANTED
3843                 || permAcrossUsersFull != PERMISSION_GRANTED) {
3844             String msg = "Permission Denial: registerForegroundServiceObserver() from pid="
3845                     + Binder.getCallingPid()
3846                     + ", uid=" + callingUid
3847                     + " requires " + MANAGE_ACTIVITY_TASKS
3848                     + " and " + INTERACT_ACROSS_USERS_FULL;
3849             Slog.w(TAG, msg);
3850             throw new SecurityException(msg);
3851         }
3852 
3853         synchronized (this) {
3854             return mServices.registerForegroundServiceObserverLocked(callingUid, callback);
3855         }
3856     }
3857 
3858     @Override
forceStopPackage(final String packageName, int userId)3859     public void forceStopPackage(final String packageName, int userId) {
3860         forceStopPackage(packageName, userId, /*flags=*/ 0);
3861     }
3862 
3863     @Override
forceStopPackageEvenWhenStopping(final String packageName, int userId)3864     public void forceStopPackageEvenWhenStopping(final String packageName, int userId) {
3865         forceStopPackage(packageName, userId, ActivityManager.FLAG_OR_STOPPED);
3866     }
3867 
forceStopPackage(final String packageName, int userId, int userRunningFlags)3868     private void forceStopPackage(final String packageName, int userId, int userRunningFlags) {
3869         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3870                 != PackageManager.PERMISSION_GRANTED) {
3871             String msg = "Permission Denial: forceStopPackage() from pid="
3872                     + Binder.getCallingPid()
3873                     + ", uid=" + Binder.getCallingUid()
3874                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3875             Slog.w(TAG, msg);
3876             throw new SecurityException(msg);
3877         }
3878         final int callingPid = Binder.getCallingPid();
3879         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
3880                 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
3881         final long callingId = Binder.clearCallingIdentity();
3882         try {
3883             IPackageManager pm = AppGlobals.getPackageManager();
3884             synchronized (this) {
3885                 int[] users = userId == UserHandle.USER_ALL
3886                         ? mUserController.getUsers() : new int[] { userId };
3887                 for (int user : users) {
3888                     if (getPackageManagerInternal().isPackageStateProtected(
3889                             packageName, user)) {
3890                         Slog.w(TAG, "Ignoring request to force stop protected package "
3891                                 + packageName + " u" + user);
3892                         return;
3893                     }
3894 
3895                     int pkgUid = -1;
3896                     try {
3897                         pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
3898                                 user);
3899                     } catch (RemoteException e) {
3900                     }
3901                     if (pkgUid == -1) {
3902                         Slog.w(TAG, "Invalid packageName: " + packageName);
3903                         continue;
3904                     }
3905                     try {
3906                         pm.setPackageStoppedState(packageName, true, user);
3907                     } catch (RemoteException e) {
3908                     } catch (IllegalArgumentException e) {
3909                         Slog.w(TAG, "Failed trying to unstop package "
3910                                 + packageName + ": " + e);
3911                     }
3912                     if (mUserController.isUserRunning(user, userRunningFlags)) {
3913                         forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
3914                         finishForceStopPackageLocked(packageName, pkgUid);
3915                     }
3916                 }
3917             }
3918         } finally {
3919             Binder.restoreCallingIdentity(callingId);
3920         }
3921     }
3922 
3923     @Override
addPackageDependency(String packageName)3924     public void addPackageDependency(String packageName) {
3925         int callingPid = Binder.getCallingPid();
3926         if (callingPid == myPid()) {
3927             //  Yeah, um, no.
3928             return;
3929         }
3930         final int callingUid = Binder.getCallingUid();
3931         final int callingUserId = UserHandle.getUserId(callingUid);
3932         if (getPackageManagerInternal().filterAppAccess(packageName, callingUid, callingUserId)) {
3933             Slog.w(TAG, "Failed trying to add dependency on non-existing package: " + packageName);
3934             return;
3935         }
3936         ProcessRecord proc;
3937         synchronized (mPidsSelfLocked) {
3938             proc = mPidsSelfLocked.get(Binder.getCallingPid());
3939         }
3940         if (proc != null) {
3941             ArraySet<String> pkgDeps = proc.getPkgDeps();
3942             synchronized (this) {
3943                 synchronized (mProcLock) {
3944                     if (pkgDeps == null) {
3945                         proc.setPkgDeps(pkgDeps = new ArraySet<String>(1));
3946                     }
3947                     pkgDeps.add(packageName);
3948                 }
3949             }
3950         }
3951     }
3952 
3953     /*
3954      * The pkg name and app id have to be specified.
3955      */
3956     @Override
killApplication(String pkg, int appId, int userId, String reason, int exitInfoReason)3957     public void killApplication(String pkg, int appId, int userId, String reason,
3958             int exitInfoReason) {
3959         if (pkg == null) {
3960             return;
3961         }
3962         // Make sure the uid is valid.
3963         if (appId < 0) {
3964             Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
3965             return;
3966         }
3967         int callerUid = Binder.getCallingUid();
3968         // Only the system server can kill an application
3969         if (UserHandle.getAppId(callerUid) == SYSTEM_UID) {
3970             // Post an aysnc message to kill the application
3971             Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3972             msg.arg1 = appId;
3973             msg.arg2 = userId;
3974             SomeArgs args = SomeArgs.obtain();
3975             args.arg1 = pkg;
3976             args.arg2 = reason;
3977             args.arg3 = exitInfoReason;
3978             msg.obj = args;
3979             mHandler.sendMessage(msg);
3980         } else {
3981             throw new SecurityException(callerUid + " cannot kill pkg: " +
3982                     pkg);
3983         }
3984     }
3985 
3986     @Override
closeSystemDialogs(String reason)3987     public void closeSystemDialogs(String reason) {
3988         mAtmInternal.closeSystemDialogs(reason);
3989     }
3990 
3991     @Override
getProcessMemoryInfo(int[] pids)3992     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
3993         enforceNotIsolatedCaller("getProcessMemoryInfo");
3994 
3995         final long now = SystemClock.uptimeMillis();
3996         final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME;
3997 
3998         final int callingPid = Binder.getCallingPid();
3999         final int callingUid = Binder.getCallingUid();
4000         final int callingUserId = UserHandle.getUserId(callingUid);
4001         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4002                 callingUid) == PackageManager.PERMISSION_GRANTED;
4003         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4004         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4005                 "getProcessMemoryInfo", callingPid, callingUid);
4006 
4007         // Check if the caller is actually instrumented and from shell, if it's true, we may lift
4008         // the throttle of PSS info sampling.
4009         boolean isCallerInstrumentedFromShell = false;
4010         synchronized (mProcLock) {
4011             synchronized (mPidsSelfLocked) {
4012                 ProcessRecord caller = mPidsSelfLocked.get(callingPid);
4013                 if (caller != null) {
4014                     final ActiveInstrumentation instr = caller.getActiveInstrumentation();
4015                     isCallerInstrumentedFromShell = instr != null
4016                             && (instr.mSourceUid == SHELL_UID || instr.mSourceUid == ROOT_UID);
4017                 }
4018             }
4019         }
4020 
4021         final Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4022         for (int i=pids.length-1; i>=0; i--) {
4023             final Debug.MemoryInfo mi = infos[i] = new Debug.MemoryInfo();
4024             final ProcessRecord proc;
4025             final int oomAdj;
4026             final ProcessProfileRecord profile;
4027             synchronized (mAppProfiler.mProfilerLock) {
4028                 synchronized (mPidsSelfLocked) {
4029                     proc = mPidsSelfLocked.get(pids[i]);
4030                     if (proc != null) {
4031                         profile = proc.mProfile;
4032                         oomAdj = profile.getSetAdj();
4033                     } else {
4034                         profile = null;
4035                         oomAdj = 0;
4036                     }
4037                 }
4038             }
4039             final int targetUid = (proc != null) ? proc.uid : -1;
4040             final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1;
4041 
4042             if (callingUid != targetUid) {
4043                 if (!allUids) {
4044                     continue; // Not allowed to see other UIDs.
4045                 }
4046 
4047                 if (!allUsers && (targetUserId != callingUserId)) {
4048                     continue; // Not allowed to see other users.
4049                 }
4050             }
4051             if (proc != null) {
4052                 synchronized (mAppProfiler.mProfilerLock) {
4053                     if (profile.getLastMemInfoTime() >= lastNow && profile.getLastMemInfo() != null
4054                             && !isCallerInstrumentedFromShell) {
4055                         // It hasn't been long enough that we want to take another sample; return
4056                         // the last one.
4057                         mi.set(profile.getLastMemInfo());
4058                         continue;
4059                     }
4060                 }
4061             }
4062             final long startTime = SystemClock.currentThreadTimeMillis();
4063             final Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
4064             Debug.getMemoryInfo(pids[i], memInfo);
4065             final long duration = SystemClock.currentThreadTimeMillis() - startTime;
4066             mi.set(memInfo);
4067             if (proc != null) {
4068                 synchronized (mAppProfiler.mProfilerLock) {
4069                     profile.setLastMemInfo(memInfo);
4070                     profile.setLastMemInfoTime(SystemClock.uptimeMillis());
4071                     if (profile.getThread() != null && profile.getSetAdj() == oomAdj) {
4072                         // Record this for posterity if the process has been stable.
4073                         profile.addPss(mi.getTotalPss(),
4074                                 mi.getTotalUss(), mi.getTotalRss(), false,
4075                                 ProcessStats.ADD_PSS_EXTERNAL_SLOW, duration);
4076                         proc.getPkgList().forEachPackageProcessStats(holder -> {
4077                             final ProcessState state = holder.state;
4078                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
4079                                     proc.info.uid,
4080                                     state != null ? state.getName() : proc.processName,
4081                                     state != null ? state.getPackage() : proc.info.packageName,
4082                                     mi.getTotalPss(),
4083                                     mi.getTotalUss(),
4084                                     mi.getTotalRss(),
4085                                     ProcessStats.ADD_PSS_EXTERNAL_SLOW,
4086                                     duration,
4087                                     holder.appVersion,
4088                                     profile.getCurrentHostingComponentTypes(),
4089                                     profile.getHistoricalHostingComponentTypes());
4090                         });
4091                     }
4092                 }
4093             }
4094         }
4095         return infos;
4096     }
4097 
4098     @Override
getProcessPss(int[] pids)4099     public long[] getProcessPss(int[] pids) {
4100         enforceNotIsolatedCaller("getProcessPss");
4101 
4102         final int callingPid = Binder.getCallingPid();
4103         final int callingUid = Binder.getCallingUid();
4104         final int userId = UserHandle.getUserId(callingUid);
4105         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4106                 callingUid) == PackageManager.PERMISSION_GRANTED;
4107         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4108         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4109                 "getProcessPss", callingPid, callingUid);
4110 
4111         final long[] pss = new long[pids.length];
4112         for (int i=pids.length-1; i>=0; i--) {
4113             ProcessRecord proc;
4114             int oomAdj;
4115             synchronized (mProcLock) {
4116                 synchronized (mPidsSelfLocked) {
4117                     proc = mPidsSelfLocked.get(pids[i]);
4118                     oomAdj = proc != null ? proc.mState.getSetAdj() : 0;
4119                 }
4120             }
4121             if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) {
4122                 // The caller is not allow to get information about this other process...
4123                 // just leave it empty.
4124                 continue;
4125             }
4126             final long[] tmpUss = new long[3];
4127             final long startTime = SystemClock.currentThreadTimeMillis();
4128             final long pi = pss[i] = Debug.getPss(pids[i], tmpUss, null);
4129             final long duration = SystemClock.currentThreadTimeMillis() - startTime;
4130             if (proc != null) {
4131                 final ProcessProfileRecord profile = proc.mProfile;
4132                 synchronized (mAppProfiler.mProfilerLock) {
4133                     if (profile.getThread() != null && profile.getSetAdj() == oomAdj) {
4134                         // Record this for posterity if the process has been stable.
4135                         profile.addPss(pi, tmpUss[0], tmpUss[2], false,
4136                                 ProcessStats.ADD_PSS_EXTERNAL, duration);
4137                         proc.getPkgList().forEachPackageProcessStats(holder -> {
4138                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
4139                                     proc.info.uid,
4140                                     holder.state.getName(),
4141                                     holder.state.getPackage(),
4142                                     pi,
4143                                     tmpUss[0],
4144                                     tmpUss[2],
4145                                     ProcessStats.ADD_PSS_EXTERNAL,
4146                                     duration,
4147                                     holder.appVersion,
4148                                     profile.getCurrentHostingComponentTypes(),
4149                                     profile.getHistoricalHostingComponentTypes());
4150                         });
4151                     }
4152                 }
4153             }
4154         }
4155         return pss;
4156     }
4157 
4158     @Override
killApplicationProcess(String processName, int uid)4159     public void killApplicationProcess(String processName, int uid) {
4160         if (processName == null) {
4161             return;
4162         }
4163 
4164         int callerUid = Binder.getCallingUid();
4165         // Only the system server can kill an application
4166         if (callerUid == SYSTEM_UID) {
4167             synchronized (this) {
4168                 ProcessRecord app = getProcessRecordLocked(processName, uid);
4169                 IApplicationThread thread;
4170                 if (app != null && (thread = app.getThread()) != null) {
4171                     try {
4172                         thread.scheduleSuicide();
4173                     } catch (RemoteException e) {
4174                         // If the other end already died, then our work here is done.
4175                     }
4176                 } else {
4177                     Slog.w(TAG, "Process/uid not found attempting kill of "
4178                             + processName + " / " + uid);
4179                 }
4180             }
4181         } else {
4182             throw new SecurityException(callerUid + " cannot kill app process: " +
4183                     processName);
4184         }
4185     }
4186 
4187     @GuardedBy("this")
forceStopPackageLocked(final String packageName, int uid, String reason)4188     private void forceStopPackageLocked(final String packageName, int uid, String reason) {
4189         forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
4190                 false, true, false, false, UserHandle.getUserId(uid), reason);
4191     }
4192 
4193     @GuardedBy("this")
finishForceStopPackageLocked(final String packageName, int uid)4194     private void finishForceStopPackageLocked(final String packageName, int uid) {
4195         Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4196                 Uri.fromParts("package", packageName, null));
4197         if (!mProcessesReady) {
4198             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
4199                     | Intent.FLAG_RECEIVER_FOREGROUND);
4200         }
4201         final int userId = UserHandle.getUserId(uid);
4202         final int[] broadcastAllowList =
4203                 getPackageManagerInternal().getVisibilityAllowList(packageName, userId);
4204         intent.putExtra(Intent.EXTRA_UID, uid);
4205         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4206         broadcastIntentLocked(null /* callerApp */, null /* callerPackage */,
4207                 null /* callerFeatureId */, intent, null /* resolvedType */,
4208                 null /* resultToApp */, null /* resultTo */,
4209                 0 /* resultCode */, null /* resultData */, null /* resultExtras */,
4210                 null /* requiredPermissions */, null /* excludedPermissions */,
4211                 null /* excludedPackages */, OP_NONE, null /* bOptions */, false /* ordered */,
4212                 false /* sticky */, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
4213                 Binder.getCallingPid(), userId, BackgroundStartPrivileges.NONE,
4214                 broadcastAllowList, null /* filterExtrasForReceiver */);
4215     }
4216 
cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4217     private void cleanupDisabledPackageComponentsLocked(
4218             String packageName, int userId, String[] changedClasses) {
4219 
4220         Set<String> disabledClasses = null;
4221         boolean packageDisabled = false;
4222         IPackageManager pm = AppGlobals.getPackageManager();
4223 
4224         if (changedClasses == null) {
4225             // Nothing changed...
4226             return;
4227         }
4228 
4229         // Determine enable/disable state of the package and its components.
4230         int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4231         for (int i = changedClasses.length - 1; i >= 0; i--) {
4232             final String changedClass = changedClasses[i];
4233 
4234             if (changedClass.equals(packageName)) {
4235                 try {
4236                     // Entire package setting changed
4237                     enabled = pm.getApplicationEnabledSetting(packageName,
4238                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4239                 } catch (Exception e) {
4240                     // No such package/component; probably racing with uninstall.  In any
4241                     // event it means we have nothing further to do here.
4242                     return;
4243                 }
4244                 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4245                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4246                 if (packageDisabled) {
4247                     // Entire package is disabled.
4248                     // No need to continue to check component states.
4249                     disabledClasses = null;
4250                     break;
4251                 }
4252             } else {
4253                 try {
4254                     enabled = pm.getComponentEnabledSetting(
4255                             new ComponentName(packageName, changedClass),
4256                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4257                 } catch (Exception e) {
4258                     // As above, probably racing with uninstall.
4259                     return;
4260                 }
4261                 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4262                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
4263                     if (disabledClasses == null) {
4264                         disabledClasses = new ArraySet<>(changedClasses.length);
4265                     }
4266                     disabledClasses.add(changedClass);
4267                 }
4268             }
4269         }
4270 
4271         if (!packageDisabled && disabledClasses == null) {
4272             // Nothing to do here...
4273             return;
4274         }
4275 
4276         mAtmInternal.cleanupDisabledPackageComponents(
4277                 packageName, disabledClasses, userId, mBooted);
4278 
4279         // Clean-up disabled services.
4280         mServices.bringDownDisabledPackageServicesLocked(
4281                 packageName, disabledClasses, userId, false /* evenPersistent */,
4282                 false /* fullStop */, true /* doIt */);
4283 
4284         // Clean-up disabled providers.
4285         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4286         mCpHelper.getProviderMap().collectPackageProvidersLocked(
4287                 packageName, disabledClasses, true, false, userId, providers);
4288         for (int i = providers.size() - 1; i >= 0; i--) {
4289             mCpHelper.removeDyingProviderLocked(null, providers.get(i), true);
4290         }
4291 
4292         // Clean-up disabled broadcast receivers.
4293         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4294             mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4295                     packageName, disabledClasses, userId);
4296         }
4297 
4298     }
4299 
clearBroadcastQueueForUserLocked(int userId)4300     final boolean clearBroadcastQueueForUserLocked(int userId) {
4301         boolean didSomething = false;
4302         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4303             didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4304                     null, null, userId);
4305         }
4306         return didSomething;
4307     }
4308 
4309     @GuardedBy("this")
forceStopAppZygoteLocked(String packageName, int appId, int userId)4310     final void forceStopAppZygoteLocked(String packageName, int appId, int userId) {
4311         if (packageName == null) {
4312             return;
4313         }
4314         if (appId < 0) {
4315             appId = UserHandle.getAppId(getPackageManagerInternal().getPackageUid(packageName,
4316                     MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM));
4317         }
4318 
4319         mProcessList.killAppZygotesLocked(packageName, appId, userId, true /* force */);
4320     }
4321 
stopAppForUserInternal(final String packageName, @UserIdInt final int userId)4322     void stopAppForUserInternal(final String packageName, @UserIdInt final int userId) {
4323         final int uid = getPackageManagerInternal().getPackageUid(packageName,
4324                 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, userId);
4325         if (uid < 0) {
4326             Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId
4327                     + " but does not exist in that user");
4328             return;
4329         }
4330 
4331         // Policy: certain classes of app are not subject to user-invoked stop
4332         if (getPackageManagerInternal().isPackageStateProtected(packageName, userId)) {
4333             Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId
4334                     + " but it is protected");
4335             return;
4336         }
4337 
4338         Slog.i(TAG, "Stopping app for user: " + packageName + "/" + userId);
4339 
4340         // A specific subset of the work done in forceStopPackageLocked(), because we are
4341         // intentionally not rendering the app nonfunctional; we're just halting its current
4342         // execution.
4343         final int appId = UserHandle.getAppId(uid);
4344         synchronized (this) {
4345             synchronized (mProcLock) {
4346                 mAtmInternal.onForceStopPackage(packageName, true, false, userId);
4347 
4348                 mProcessList.killPackageProcessesLSP(packageName, appId, userId,
4349                         ProcessList.INVALID_ADJ, true, false, true,
4350                         false, true /* setRemoved */, false,
4351                         ApplicationExitInfo.REASON_USER_REQUESTED,
4352                         ApplicationExitInfo.SUBREASON_STOP_APP,
4353                         "fully stop " + packageName + "/" + userId + " by user request");
4354             }
4355 
4356             mServices.bringDownDisabledPackageServicesLocked(
4357                     packageName, null, userId, false, true, true);
4358 
4359             if (mBooted) {
4360                 mAtmInternal.resumeTopActivities(true);
4361             }
4362         }
4363     }
4364 
4365     @GuardedBy("this")
forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reasonString)4366     final boolean forceStopPackageLocked(String packageName, int appId,
4367             boolean callerWillRestart, boolean purgeCache, boolean doit,
4368             boolean evenPersistent, boolean uninstalling, int userId, String reasonString) {
4369 
4370         int reason = packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED
4371                 : ApplicationExitInfo.REASON_USER_REQUESTED;
4372         return forceStopPackageLocked(packageName, appId, callerWillRestart, purgeCache, doit,
4373                 evenPersistent, uninstalling, userId, reasonString, reason);
4374 
4375     }
4376 
4377     @GuardedBy("this")
forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reasonString, int reason)4378     final boolean forceStopPackageLocked(String packageName, int appId,
4379             boolean callerWillRestart, boolean purgeCache, boolean doit,
4380             boolean evenPersistent, boolean uninstalling, int userId, String reasonString,
4381             int reason) {
4382         int i;
4383 
4384         if (userId == UserHandle.USER_ALL && packageName == null) {
4385             Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
4386         }
4387 
4388         if (appId < 0 && packageName != null) {
4389             appId = UserHandle.getAppId(getPackageManagerInternal().getPackageUid(packageName,
4390                     MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM));
4391         }
4392 
4393         boolean didSomething;
4394         if (doit) {
4395             if (packageName != null) {
4396                 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId
4397                         + " user=" + userId + ": " + reasonString);
4398             } else {
4399                 Slog.i(TAG, "Force stopping u" + userId + ": " + reasonString);
4400             }
4401 
4402             mAppErrors.resetProcessCrashTime(packageName == null, appId, userId);
4403         }
4404 
4405         synchronized (mProcLock) {
4406             // Notify first that the package is stopped, so its process won't be restarted
4407             // unexpectedly if there is an activity of the package without attached process
4408             // becomes visible when killing its other processes with visible activities.
4409             didSomething = mAtmInternal.onForceStopPackage(
4410                     packageName, doit, evenPersistent, userId);
4411             int subReason;
4412             if (reason == ApplicationExitInfo.REASON_USER_REQUESTED) {
4413                 subReason = ApplicationExitInfo.SUBREASON_FORCE_STOP;
4414             } else {
4415                 subReason = ApplicationExitInfo.SUBREASON_UNKNOWN;
4416             }
4417 
4418             didSomething |= mProcessList.killPackageProcessesLSP(packageName, appId, userId,
4419                     ProcessList.INVALID_ADJ, callerWillRestart, false /* allowRestart */, doit,
4420                     evenPersistent, true /* setRemoved */, uninstalling,
4421                     reason,
4422                     subReason,
4423                     (packageName == null ? ("stop user " + userId) : ("stop " + packageName))
4424                     + " due to " + reasonString);
4425         }
4426 
4427         if (mServices.bringDownDisabledPackageServicesLocked(
4428                 packageName, null /* filterByClasses */, userId, evenPersistent, true, doit)) {
4429             if (!doit) {
4430                 return true;
4431             }
4432             didSomething = true;
4433         }
4434 
4435         if (packageName == null) {
4436             // Remove all sticky broadcasts from this user.
4437             mStickyBroadcasts.remove(userId);
4438         }
4439 
4440         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4441         if (mCpHelper.getProviderMap().collectPackageProvidersLocked(packageName, null, doit,
4442                 evenPersistent, userId, providers)) {
4443             if (!doit) {
4444                 return true;
4445             }
4446             didSomething = true;
4447         }
4448         for (i = providers.size() - 1; i >= 0; i--) {
4449             mCpHelper.removeDyingProviderLocked(null, providers.get(i), true);
4450         }
4451 
4452         // Remove transient permissions granted from/to this package/user
4453         mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false);
4454 
4455         if (doit) {
4456             for (i = mBroadcastQueues.length - 1; i >= 0; i--) {
4457                 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4458                         packageName, null, userId);
4459             }
4460         }
4461 
4462         if (packageName == null || uninstalling) {
4463             didSomething |= mPendingIntentController.removePendingIntentsForPackage(
4464                     packageName, userId, appId, doit);
4465         }
4466 
4467         if (doit) {
4468             if (purgeCache && packageName != null) {
4469                 AttributeCache ac = AttributeCache.instance();
4470                 if (ac != null) {
4471                     ac.removePackage(packageName);
4472                 }
4473             }
4474             if (mBooted) {
4475                 mAtmInternal.resumeTopActivities(true /* scheduleIdle */);
4476             }
4477         }
4478 
4479         return didSomething;
4480     }
4481 
4482     @GuardedBy("this")
handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout)4483     void handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout) {
4484         final int pid = app.getPid();
4485         boolean gone = isKillTimeout || removePidLocked(pid, app);
4486 
4487         if (gone) {
4488             if (isKillTimeout) {
4489                 // It's still alive... maybe blocked at uninterruptible sleep ?
4490                 final ProcessRecord successor = app.mSuccessor;
4491                 if (successor == null) {
4492                     // There might be a race, nothing to do here.
4493                     return;
4494                 }
4495                 Slog.wtf(TAG, app.toString() + " " + app.getDyingPid()
4496                         + " refused to die while trying to launch " + successor
4497                         + ", cancelling the process start");
4498 
4499                 // It doesn't make sense to proceed with launching the new instance while the old
4500                 // instance is still alive, abort the launch.
4501                 app.mSuccessorStartRunnable = null;
4502                 app.mSuccessor = null;
4503                 successor.mPredecessor = null;
4504 
4505                 // We're going to cleanup the successor process record, which wasn't started at all.
4506                 app = successor;
4507             } else {
4508                 final String msg = "Process " + app + " failed to attach";
4509                 Slog.w(TAG, msg);
4510                 EventLogTags.writeAmProcessStartTimeout(app.userId, pid, app.uid, app.processName);
4511                 if (app.getActiveInstrumentation() != null) {
4512                     final Bundle info = new Bundle();
4513                     info.putString("shortMsg", "failed to attach");
4514                     info.putString("longMsg", msg);
4515                     finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
4516                 }
4517             }
4518             synchronized (mProcLock) {
4519                 mProcessList.removeProcessNameLocked(app.processName, app.uid);
4520                 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
4521                 // Take care of any launching providers waiting for this process.
4522                 mCpHelper.cleanupAppInLaunchingProvidersLocked(app, true);
4523                 // Take care of any services that are waiting for the process.
4524                 mServices.processStartTimedOutLocked(app);
4525                 // Take care of any broadcasts waiting for the process.
4526                 for (BroadcastQueue queue : mBroadcastQueues) {
4527                     queue.onApplicationTimeoutLocked(app);
4528                 }
4529                 if (!isKillTimeout) {
4530                     mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
4531                     app.killLocked("start timeout",
4532                             ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true);
4533                     removeLruProcessLocked(app);
4534                 }
4535                 if (app.isolated) {
4536                     mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
4537                     mProcessList.mAppExitInfoTracker.mIsolatedUidRecords.removeIsolatedUid(
4538                             app.uid, app.info.uid);
4539                     getPackageManagerInternal().removeIsolatedUid(app.uid);
4540                 }
4541             }
4542             final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4543             if (!isKillTimeout && backupTarget != null && backupTarget.app.getPid() == pid) {
4544                 Slog.w(TAG, "Unattached app died before backup, skipping");
4545                 final int userId = app.userId;
4546                 final String packageName = app.info.packageName;
4547                 mHandler.post(new Runnable() {
4548                 @Override
4549                     public void run() {
4550                         try {
4551                             IBackupManager bm = IBackupManager.Stub.asInterface(
4552                                     ServiceManager.getService(Context.BACKUP_SERVICE));
4553                             bm.agentDisconnectedForUser(userId, packageName);
4554                         } catch (RemoteException e) {
4555                             // Can't happen; the backup manager is local
4556                         }
4557                     }
4558                 });
4559             }
4560         } else {
4561             Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
4562         }
4563     }
4564 
4565     @GuardedBy("this")
attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4566     private void attachApplicationLocked(@NonNull IApplicationThread thread,
4567             int pid, int callingUid, long startSeq) {
4568 
4569         // Find the application record that is being attached...  either via
4570         // the pid if we are running in multiple processes, or just pull the
4571         // next app record if we are emulating process with anonymous threads.
4572         ProcessRecord app;
4573         long startTime = SystemClock.uptimeMillis();
4574         long bindApplicationTimeMillis;
4575         if (pid != MY_PID && pid >= 0) {
4576             synchronized (mPidsSelfLocked) {
4577                 app = mPidsSelfLocked.get(pid);
4578             }
4579             if (app != null && (app.getStartUid() != callingUid || app.getStartSeq() != startSeq)) {
4580                 String processName = null;
4581                 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4582                 if (pending != null) {
4583                     processName = pending.processName;
4584                 }
4585                 final String msg = "attachApplicationLocked process:" + processName
4586                         + " startSeq:" + startSeq
4587                         + " pid:" + pid
4588                         + " belongs to another existing app:" + app.processName
4589                         + " startSeq:" + app.getStartSeq();
4590                 Slog.wtf(TAG, msg);
4591                 // SafetyNet logging for b/131105245.
4592                 EventLog.writeEvent(0x534e4554, "131105245", app.getStartUid(), msg);
4593                 // If there is already an app occupying that pid that hasn't been cleaned up
4594                 cleanUpApplicationRecordLocked(app, pid, false, false, -1,
4595                         true /*replacingPid*/, false /* fromBinderDied */);
4596                 removePidLocked(pid, app);
4597                 app = null;
4598             }
4599         } else {
4600             app = null;
4601         }
4602 
4603         // It's possible that process called attachApplication before we got a chance to
4604         // update the internal state.
4605         if (app == null && startSeq > 0) {
4606             final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4607             if (pending != null && pending.getStartUid() == callingUid
4608                     && pending.getStartSeq() == startSeq
4609                     && mProcessList.handleProcessStartedLocked(pending, pid,
4610                         pending.isUsingWrapper(), startSeq, true)) {
4611                 app = pending;
4612             }
4613         }
4614 
4615         if (app == null) {
4616             Slog.w(TAG, "No pending application record for pid " + pid
4617                     + " (IApplicationThread " + thread + "); dropping process");
4618             EventLogTags.writeAmDropProcess(pid);
4619             if (pid > 0 && pid != MY_PID) {
4620                 killProcessQuiet(pid);
4621                 //TODO: killProcessGroup(app.info.uid, pid);
4622                 // We can't log the app kill info for this process since we don't
4623                 // know who it is, so just skip the logging.
4624             } else {
4625                 try {
4626                     thread.scheduleExit();
4627                 } catch (Exception e) {
4628                     // Ignore exceptions.
4629                 }
4630             }
4631             return;
4632         }
4633 
4634         // If this application record is still attached to a previous
4635         // process, clean it up now.
4636         if (app.getThread() != null) {
4637             handleAppDiedLocked(app, pid, true, true, false /* fromBinderDied */);
4638         }
4639 
4640         // Tell the process all about itself.
4641 
4642         if (DEBUG_ALL) Slog.v(
4643                 TAG, "Binding process pid " + pid + " to record " + app);
4644 
4645         final String processName = app.processName;
4646         try {
4647             AppDeathRecipient adr = new AppDeathRecipient(
4648                     app, pid, thread);
4649             thread.asBinder().linkToDeath(adr, 0);
4650             app.setDeathRecipient(adr);
4651         } catch (RemoteException e) {
4652             app.resetPackageList(mProcessStats);
4653             mProcessList.startProcessLocked(app,
4654                     new HostingRecord(HostingRecord.HOSTING_TYPE_LINK_FAIL, processName),
4655                     ZYGOTE_POLICY_FLAG_EMPTY);
4656             return;
4657         }
4658 
4659         EventLogTags.writeAmProcBound(app.userId, pid, app.processName);
4660 
4661         synchronized (mProcLock) {
4662             mOomAdjuster.setAttachingProcessStatesLSP(app);
4663             clearProcessForegroundLocked(app);
4664             app.setDebugging(false);
4665             app.setKilledByAm(false);
4666             app.setKilled(false);
4667             // We carefully use the same state that PackageManager uses for
4668             // filtering, since we use this flag to decide if we need to install
4669             // providers when user is unlocked later
4670             app.setUnlocked(StorageManager.isUserKeyUnlocked(app.userId));
4671         }
4672 
4673         boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
4674         List<ProviderInfo> providers = normalMode
4675                                             ? mCpHelper.generateApplicationProvidersLocked(app)
4676                                             : null;
4677 
4678         if (providers != null && mCpHelper.checkAppInLaunchingProvidersLocked(app)) {
4679             Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
4680             msg.obj = app;
4681             mHandler.sendMessageDelayed(msg,
4682                     ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS);
4683         }
4684 
4685         checkTime(startTime, "attachApplicationLocked: before bindApplication");
4686 
4687         if (!normalMode) {
4688             Slog.i(TAG, "Launching preboot mode app: " + app);
4689         }
4690 
4691         if (DEBUG_ALL) Slog.v(
4692             TAG, "New app record " + app
4693             + " thread=" + thread.asBinder() + " pid=" + pid);
4694         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4695         try {
4696             int testMode = ApplicationThreadConstants.DEBUG_OFF;
4697             if (mDebugApp != null && mDebugApp.equals(processName)) {
4698                 if (mWaitForDebugger) {
4699                     if (mSuspendUponWait) {
4700                         testMode = ApplicationThreadConstants.DEBUG_SUSPEND;
4701                     } else {
4702                         testMode = ApplicationThreadConstants.DEBUG_WAIT;
4703                     }
4704                 } else {
4705                     testMode = ApplicationThreadConstants.DEBUG_ON;
4706                 }
4707                 app.setDebugging(true);
4708                 if (mDebugTransient) {
4709                     mDebugApp = mOrigDebugApp;
4710                     mWaitForDebugger = mOrigWaitForDebugger;
4711                 }
4712             }
4713 
4714             boolean enableTrackAllocation = false;
4715             synchronized (mProcLock) {
4716                 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) {
4717                     enableTrackAllocation = true;
4718                     mTrackAllocationApp = null;
4719                 }
4720             }
4721 
4722             // If the app is being launched for restore or full backup, set it up specially
4723             boolean isRestrictedBackupMode = false;
4724             if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) {
4725                 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID
4726                         && ((backupTarget.backupMode == BackupRecord.RESTORE_FULL)
4727                                 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL));
4728             }
4729 
4730             final ActiveInstrumentation instr = app.getActiveInstrumentation();
4731 
4732             if (instr != null) {
4733                 notifyPackageUse(instr.mClass.getPackageName(),
4734                                  PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION);
4735             }
4736             ProtoLog.v(WM_DEBUG_CONFIGURATION, "Binding proc %s with config %s",
4737                     processName, app.getWindowProcessController().getConfiguration());
4738             ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info;
4739             app.setCompat(compatibilityInfoForPackage(appInfo));
4740 
4741             ProfilerInfo profilerInfo = mAppProfiler.setupProfilerInfoLocked(thread, app, instr);
4742 
4743             // We deprecated Build.SERIAL and it is not accessible to
4744             // Instant Apps and target APIs higher than O MR1. Since access to the serial
4745             // is now behind a permission we push down the value.
4746             final String buildSerial = (!appInfo.isInstantApp()
4747                     && appInfo.targetSdkVersion < Build.VERSION_CODES.P)
4748                             ? sTheRealBuildSerial : Build.UNKNOWN;
4749 
4750             // Figure out whether the app needs to run in autofill compat mode.
4751             AutofillOptions autofillOptions = null;
4752             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
4753                 final AutofillManagerInternal afm = LocalServices.getService(
4754                         AutofillManagerInternal.class);
4755                 if (afm != null) {
4756                     autofillOptions = afm.getAutofillOptions(
4757                             app.info.packageName, app.info.longVersionCode, app.userId);
4758                 }
4759             }
4760             ContentCaptureOptions contentCaptureOptions = null;
4761             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
4762                 final ContentCaptureManagerInternal ccm =
4763                         LocalServices.getService(ContentCaptureManagerInternal.class);
4764                 if (ccm != null) {
4765                     contentCaptureOptions = ccm.getOptionsForPackage(app.userId,
4766                             app.info.packageName);
4767                 }
4768             }
4769             SharedMemory serializedSystemFontMap = null;
4770             final FontManagerInternal fm = LocalServices.getService(FontManagerInternal.class);
4771             if (fm != null) {
4772                 serializedSystemFontMap = fm.getSerializedSystemFontMap();
4773             }
4774 
4775             checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
4776             bindApplicationTimeMillis = SystemClock.uptimeMillis();
4777             mAtmInternal.preBindApplication(app.getWindowProcessController());
4778             final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
4779             if (mPlatformCompat != null) {
4780                 mPlatformCompat.resetReporting(app.info);
4781             }
4782             final ProviderInfoList providerList = ProviderInfoList.fromList(providers);
4783             if (app.getIsolatedEntryPoint() != null) {
4784                 // This is an isolated process which should just call an entry point instead of
4785                 // being bound to an application.
4786                 thread.runIsolatedEntryPoint(
4787                         app.getIsolatedEntryPoint(), app.getIsolatedEntryPointArgs());
4788             } else if (instr2 != null) {
4789                 thread.bindApplication(processName, appInfo,
4790                         app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage,
4791                         providerList,
4792                         instr2.mClass,
4793                         profilerInfo, instr2.mArguments,
4794                         instr2.mWatcher,
4795                         instr2.mUiAutomationConnection, testMode,
4796                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
4797                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
4798                         new Configuration(app.getWindowProcessController().getConfiguration()),
4799                         app.getCompat(), getCommonServicesLocked(app.isolated),
4800                         mCoreSettingsObserver.getCoreSettingsLocked(),
4801                         buildSerial, autofillOptions, contentCaptureOptions,
4802                         app.getDisabledCompatChanges(), serializedSystemFontMap,
4803                         app.getStartElapsedTime(), app.getStartUptime());
4804             } else {
4805                 thread.bindApplication(processName, appInfo,
4806                         app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage,
4807                         providerList, null, profilerInfo, null, null, null, testMode,
4808                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
4809                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
4810                         new Configuration(app.getWindowProcessController().getConfiguration()),
4811                         app.getCompat(), getCommonServicesLocked(app.isolated),
4812                         mCoreSettingsObserver.getCoreSettingsLocked(),
4813                         buildSerial, autofillOptions, contentCaptureOptions,
4814                         app.getDisabledCompatChanges(), serializedSystemFontMap,
4815                         app.getStartElapsedTime(), app.getStartUptime());
4816             }
4817 
4818             Message msg = mHandler.obtainMessage(BIND_APPLICATION_TIMEOUT_MSG);
4819             msg.obj = app;
4820             mHandler.sendMessageDelayed(msg, BIND_APPLICATION_TIMEOUT);
4821             mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4822 
4823             if (profilerInfo != null) {
4824                 profilerInfo.closeFd();
4825                 profilerInfo = null;
4826             }
4827 
4828             app.setBindApplicationTime(bindApplicationTimeMillis);
4829 
4830             // Make app active after binding application or client may be running requests (e.g
4831             // starting activities) before it is ready.
4832             synchronized (mProcLock) {
4833                 app.makeActive(thread, mProcessStats);
4834                 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
4835             }
4836             app.setPendingFinishAttach(true);
4837 
4838             updateLruProcessLocked(app, false, null);
4839             checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
4840 
4841             updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN);
4842             checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
4843 
4844             final long now = SystemClock.uptimeMillis();
4845             synchronized (mAppProfiler.mProfilerLock) {
4846                 app.mProfile.setLastRequestedGc(now);
4847                 app.mProfile.setLastLowMemory(now);
4848             }
4849 
4850             // Remove this record from the list of starting applications.
4851             mPersistentStartingProcesses.remove(app);
4852             if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) {
4853                 Slog.v(TAG_PROCESSES, "Attach application locked removing on hold: " + app);
4854             }
4855             mProcessesOnHold.remove(app);
4856 
4857             if (!mConstants.mEnableWaitForFinishAttachApplication) {
4858                 finishAttachApplicationInner(startSeq, callingUid, pid);
4859             }
4860         } catch (Exception e) {
4861             // We need kill the process group here. (b/148588589)
4862             Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
4863             app.resetPackageList(mProcessStats);
4864             app.unlinkDeathRecipient();
4865             app.killLocked("error during bind", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
4866                     true);
4867             handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */);
4868             return;
4869         }
4870     }
4871 
4872     @Override
attachApplication(IApplicationThread thread, long startSeq)4873     public final void attachApplication(IApplicationThread thread, long startSeq) {
4874         if (thread == null) {
4875             throw new SecurityException("Invalid application interface");
4876         }
4877         synchronized (this) {
4878             int callingPid = Binder.getCallingPid();
4879             final int callingUid = Binder.getCallingUid();
4880             final long origId = Binder.clearCallingIdentity();
4881             attachApplicationLocked(thread, callingPid, callingUid, startSeq);
4882             Binder.restoreCallingIdentity(origId);
4883         }
4884     }
4885 
finishAttachApplicationInner(long startSeq, int uid, int pid)4886     private void finishAttachApplicationInner(long startSeq, int uid, int pid) {
4887         final long startTime = SystemClock.uptimeMillis();
4888         // Find the application record that is being attached...  either via
4889         // the pid if we are running in multiple processes, or just pull the
4890         // next app record if we are emulating process with anonymous threads.
4891         final ProcessRecord app;
4892         synchronized (mPidsSelfLocked) {
4893             app = mPidsSelfLocked.get(pid);
4894         }
4895 
4896         if (app != null && app.getStartUid() == uid && app.getStartSeq() == startSeq) {
4897             mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_MSG, app);
4898         } else {
4899             Slog.wtf(TAG, "Mismatched or missing ProcessRecord: " + app + ". Pid: " + pid
4900                     + ". Uid: " + uid);
4901             killProcess(pid);
4902             killProcessGroup(uid, pid);
4903             mProcessList.noteAppKill(pid, uid,
4904                     ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
4905                     ApplicationExitInfo.SUBREASON_UNKNOWN,
4906                     "wrong startSeq");
4907             synchronized (this) {
4908                 app.killLocked("unexpected process record",
4909                         ApplicationExitInfo.REASON_OTHER, true);
4910             }
4911             return;
4912         }
4913 
4914         synchronized (this) {
4915             // Mark the finish attach application phase as completed
4916             app.setPendingFinishAttach(false);
4917 
4918             final boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
4919             final String processName = app.processName;
4920             boolean badApp = false;
4921             boolean didSomething = false;
4922 
4923             // See if the top visible activity is waiting to run in this process...
4924             if (normalMode) {
4925                 try {
4926                     didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
4927                 } catch (Exception e) {
4928                     Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
4929                     badApp = true;
4930                 }
4931             }
4932 
4933             // Find any services that should be running in this process...
4934             if (!badApp) {
4935                 try {
4936                     didSomething |= mServices.attachApplicationLocked(app, processName);
4937                     checkTime(startTime, "finishAttachApplicationInner: "
4938                             + "after mServices.attachApplicationLocked");
4939                 } catch (Exception e) {
4940                     Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
4941                     badApp = true;
4942                 }
4943             }
4944 
4945             // Check if a next-broadcast receiver is in this process...
4946             if (!badApp) {
4947                 try {
4948                     for (BroadcastQueue queue : mBroadcastQueues) {
4949                         didSomething |= queue.onApplicationAttachedLocked(app);
4950                     }
4951                     checkTime(startTime, "finishAttachApplicationInner: "
4952                             + "after dispatching broadcasts");
4953                 } catch (BroadcastDeliveryFailedException e) {
4954                     // If the app died trying to launch the receiver we declare it 'bad'
4955                     Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
4956                     badApp = true;
4957                 }
4958             }
4959 
4960             // Check whether the next backup agent is in this process...
4961             final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4962             if (!badApp && backupTarget != null && backupTarget.app == app) {
4963                 if (DEBUG_BACKUP) {
4964                     Slog.v(TAG_BACKUP,
4965                             "New app is backup target, launching agent for " + app);
4966                 }
4967 
4968                 notifyPackageUse(backupTarget.appInfo.packageName,
4969                         PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
4970                 try {
4971                     app.getThread().scheduleCreateBackupAgent(backupTarget.appInfo,
4972                             backupTarget.backupMode, backupTarget.userId,
4973                             backupTarget.backupDestination);
4974                 } catch (Exception e) {
4975                     Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
4976                     badApp = true;
4977                 }
4978             }
4979 
4980             if (badApp) {
4981                 app.killLocked("error during init",
4982                         ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true);
4983                 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */);
4984                 return;
4985             }
4986 
4987             if (!didSomething) {
4988                 updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN);
4989                 checkTime(startTime, "finishAttachApplicationInner: after updateOomAdjLocked");
4990             }
4991 
4992             final HostingRecord hostingRecord = app.getHostingRecord();
4993             final String shortAction = getShortAction(hostingRecord.getAction());
4994             FrameworkStatsLog.write(
4995                     FrameworkStatsLog.PROCESS_START_TIME,
4996                     app.info.uid,
4997                     pid,
4998                     app.info.packageName,
4999                     FrameworkStatsLog.PROCESS_START_TIME__TYPE__COLD,
5000                     app.getStartElapsedTime(),
5001                     (int) (app.getBindApplicationTime() - app.getStartUptime()),
5002                     (int) (SystemClock.uptimeMillis() - app.getStartUptime()),
5003                     hostingRecord.getType(),
5004                     hostingRecord.getName(),
5005                     shortAction,
5006                     HostingRecord.getHostingTypeIdStatsd(hostingRecord.getType()),
5007                     HostingRecord.getTriggerTypeForStatsd(hostingRecord.getTriggerType()));
5008         }
5009     }
5010 
5011     @Override
finishAttachApplication(long startSeq)5012     public final void finishAttachApplication(long startSeq) {
5013         final int pid = Binder.getCallingPid();
5014         final int uid = Binder.getCallingUid();
5015 
5016         if (!mConstants.mEnableWaitForFinishAttachApplication) {
5017             Slog.i(TAG, "Flag disabled. Ignoring finishAttachApplication from uid: "
5018                     + uid + ". pid: " + pid);
5019             return;
5020         }
5021 
5022         if (pid == MY_PID && uid == SYSTEM_UID) {
5023             return;
5024         }
5025 
5026         final long origId = Binder.clearCallingIdentity();
5027         try {
5028             finishAttachApplicationInner(startSeq, uid, pid);
5029         } finally {
5030             Binder.restoreCallingIdentity(origId);
5031         }
5032     }
5033 
5034     /**
5035      * @return The last part of the string of an intent's action.
5036      */
getShortAction(@ullable String action)5037     static @Nullable String getShortAction(@Nullable String action) {
5038         String shortAction = action;
5039         if (action != null) {
5040             int index = action.lastIndexOf('.');
5041             if (index != -1 && index != action.length() - 1) {
5042                 shortAction = action.substring(index + 1);
5043             }
5044         }
5045         return shortAction;
5046     }
5047 
checkTime(long startTime, String where)5048     void checkTime(long startTime, String where) {
5049         long now = SystemClock.uptimeMillis();
5050         if ((now - startTime) > 50) {
5051             // If we are taking more than 50ms, log about it.
5052             Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where);
5053         }
5054     }
5055 
5056     @Override
showBootMessage(final CharSequence msg, final boolean always)5057     public void showBootMessage(final CharSequence msg, final boolean always) {
5058         if (Binder.getCallingUid() != myUid()) {
5059             throw new SecurityException();
5060         }
5061         mWindowManager.showBootMessage(msg, always);
5062     }
5063 
finishBooting()5064     final void finishBooting() {
5065         TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
5066                 Trace.TRACE_TAG_ACTIVITY_MANAGER);
5067         t.traceBegin("FinishBooting");
5068 
5069         synchronized (this) {
5070             if (!mBootAnimationComplete) {
5071                 mCallFinishBooting = true;
5072                 return;
5073             }
5074             mCallFinishBooting = false;
5075         }
5076 
5077         // Let the ART runtime in zygote and system_server know that the boot completed.
5078         ZYGOTE_PROCESS.bootCompleted();
5079         VMRuntime.bootCompleted();
5080 
5081         IntentFilter pkgFilter = new IntentFilter();
5082         pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
5083         pkgFilter.addDataScheme("package");
5084         mContext.registerReceiver(new BroadcastReceiver() {
5085             @Override
5086             public void onReceive(Context context, Intent intent) {
5087                 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
5088                 if (pkgs != null) {
5089                     for (String pkg : pkgs) {
5090                         synchronized (ActivityManagerService.this) {
5091                             if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
5092                                     0, "query restart")) {
5093                                 setResultCode(Activity.RESULT_OK);
5094                                 return;
5095                             }
5096                         }
5097                     }
5098                 }
5099             }
5100         }, pkgFilter);
5101 
5102         // Inform checkpointing systems of success
5103         try {
5104             // This line is needed to CTS test for the correct exception handling
5105             // See b/138952436#comment36 for context
5106             Slog.i(TAG, "About to commit checkpoint");
5107             IStorageManager storageManager = InstallLocationUtils.getStorageManager();
5108             storageManager.commitChanges();
5109         } catch (Exception e) {
5110             PowerManager pm = (PowerManager)
5111                      mInjector.getContext().getSystemService(Context.POWER_SERVICE);
5112             pm.reboot("Checkpoint commit failed");
5113         }
5114 
5115         // Let system services know.
5116         mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED);
5117 
5118         synchronized (this) {
5119             // Ensure that any processes we had put on hold are now started
5120             // up.
5121             final int NP = mProcessesOnHold.size();
5122             if (NP > 0) {
5123                 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mProcessesOnHold);
5124                 for (int ip = 0; ip < NP; ip++) {
5125                     if (DEBUG_PROCESSES) {
5126                         Slog.v(TAG_PROCESSES, "Starting process on hold: " + procs.get(ip));
5127                     }
5128                     mProcessList.startProcessLocked(procs.get(ip),
5129                             new HostingRecord(HostingRecord.HOSTING_TYPE_ON_HOLD),
5130                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
5131                 }
5132             }
5133             if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5134                 return;
5135             }
5136             // Start looking for apps that are abusing wake locks.
5137             Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
5138             mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
5139             // Check if we are performing userspace reboot before setting sys.boot_completed to
5140             // avoid race with init reseting sys.init.userspace_reboot.in_progress once sys
5141             // .boot_completed is 1.
5142             if (InitProperties.userspace_reboot_in_progress().orElse(false)) {
5143                 UserspaceRebootLogger.noteUserspaceRebootSuccess();
5144             }
5145             // Tell anyone interested that we are done booting!
5146             SystemProperties.set("sys.boot_completed", "1");
5147             SystemProperties.set("dev.bootcomplete", "1");
5148             mUserController.onBootComplete(
5149                     new IIntentReceiver.Stub() {
5150                         @Override
5151                         public void performReceive(Intent intent, int resultCode,
5152                                 String data, Bundle extras, boolean ordered,
5153                                 boolean sticky, int sendingUser) {
5154                             synchronized (mProcLock) {
5155                                 mAppProfiler.requestPssAllProcsLPr(
5156                                         SystemClock.uptimeMillis(), true, false);
5157                             }
5158                         }
5159                     });
5160             maybeLogUserspaceRebootEvent();
5161             mUserController.scheduleStartProfiles();
5162         }
5163         // UART is on if init's console service is running, send a warning notification.
5164         showConsoleNotificationIfActive();
5165         showMteOverrideNotificationIfActive();
5166 
5167         t.traceEnd();
5168     }
5169 
showConsoleNotificationIfActive()5170     private void showConsoleNotificationIfActive() {
5171         if (!SystemProperties.get("init.svc.console").equals("running")) {
5172             return;
5173         }
5174         String title = mContext
5175                 .getString(com.android.internal.R.string.console_running_notification_title);
5176         String message = mContext
5177                 .getString(com.android.internal.R.string.console_running_notification_message);
5178         Notification notification =
5179                 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
5180                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5181                         .setWhen(0)
5182                         .setOngoing(true)
5183                         .setTicker(title)
5184                         .setDefaults(0)  // please be quiet
5185                         .setColor(mContext.getColor(
5186                                 com.android.internal.R.color
5187                                         .system_notification_accent_color))
5188                         .setContentTitle(title)
5189                         .setContentText(message)
5190                         .setVisibility(Notification.VISIBILITY_PUBLIC)
5191                         .build();
5192 
5193         NotificationManager notificationManager =
5194                 mContext.getSystemService(NotificationManager.class);
5195         notificationManager.notifyAsUser(
5196                 null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL);
5197 
5198     }
5199 
showMteOverrideNotificationIfActive()5200     private void showMteOverrideNotificationIfActive() {
5201         String bootctl = SystemProperties.get("arm64.memtag.bootctl");
5202         // If MTE is on, there is one in three cases:
5203         // * a fullmte build: ro.arm64.memtag.bootctl_supported is not set
5204         // * memtag: arm64.memtag.bootctl contains "memtag"
5205         // * memtag-once
5206         // In the condition below we detect memtag-once by exclusion.
5207         if (Arrays.asList(bootctl.split(",")).contains("memtag")
5208             || !SystemProperties.getBoolean("ro.arm64.memtag.bootctl_supported", false)
5209             || !com.android.internal.os.Zygote.nativeSupportsMemoryTagging()) {
5210             return;
5211         }
5212         String title = mContext
5213                 .getString(com.android.internal.R.string.mte_override_notification_title);
5214         String message = mContext
5215                 .getString(com.android.internal.R.string.mte_override_notification_message);
5216         Notification notification =
5217                 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
5218                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5219                         .setOngoing(true)
5220                         .setTicker(title)
5221                         .setDefaults(0)  // please be quiet
5222                         .setColor(mContext.getColor(
5223                                 com.android.internal.R.color
5224                                         .system_notification_accent_color))
5225                         .setContentTitle(title)
5226                         .setContentText(message)
5227                         .setVisibility(Notification.VISIBILITY_PUBLIC)
5228                         .build();
5229 
5230         NotificationManager notificationManager =
5231                 mContext.getSystemService(NotificationManager.class);
5232         notificationManager.notifyAsUser(
5233                 null, SystemMessage.NOTE_MTE_OVERRIDE_ENABLED, notification, UserHandle.ALL);
5234     }
5235 
5236     @Override
bootAnimationComplete()5237     public void bootAnimationComplete() {
5238         if (DEBUG_ALL) Slog.d(TAG, "bootAnimationComplete: Callers=" + Debug.getCallers(4));
5239 
5240         final boolean callFinishBooting;
5241         synchronized (this) {
5242             callFinishBooting = mCallFinishBooting;
5243             mBootAnimationComplete = true;
5244         }
5245         if (callFinishBooting) {
5246             finishBooting();
5247         }
5248     }
5249 
5250     /**
5251      * Starts Home if there is no completion signal from ThemeOverlayController
5252      */
scheduleHomeTimeout()5253     private void scheduleHomeTimeout() {
5254         if (mHasHomeDelay.compareAndSet(false, true)) {
5255             int userId = mUserController.getCurrentUserId();
5256             mHandler.postDelayed(() -> {
5257                 if (!isThemeOverlayReady(userId)) {
5258                     Slog.d(TAG,
5259                             "ThemeHomeDelay: ThemeOverlayController not responding, launching "
5260                                     + "Home after "
5261                                     + HOME_LAUNCH_TIMEOUT_MS + "ms");
5262                     setThemeOverlayReady(userId);
5263                 }
5264             }, HOME_LAUNCH_TIMEOUT_MS);
5265         }
5266     }
5267 
5268     /**
5269      * Used by ThemeOverlayController to notify when color
5270      * palette is ready.
5271      *
5272      * @param userId The ID of the user where ThemeOverlayController is ready.
5273      *
5274      * @throws RemoteException
5275      *
5276      * @hide
5277      */
5278     @Override
setThemeOverlayReady(@serIdInt int userId)5279     public void setThemeOverlayReady(@UserIdInt int userId) {
5280         enforceCallingPermission(Manifest.permission.SET_THEME_OVERLAY_CONTROLLER_READY,
5281                 "setThemeOverlayReady");
5282 
5283         boolean updateUser;
5284         synchronized (mThemeOverlayReadyUsers) {
5285             updateUser = mThemeOverlayReadyUsers.add(userId);
5286         }
5287 
5288         if (updateUser) {
5289             mAtmInternal.startHomeOnAllDisplays(userId, "setThemeOverlayReady");
5290         }
5291     }
5292 
5293     /**
5294      * Returns current state of ThemeOverlayController color
5295      * palette readiness.
5296      *
5297      * @hide
5298      */
isThemeOverlayReady(int userId)5299     public boolean isThemeOverlayReady(int userId) {
5300         synchronized (mThemeOverlayReadyUsers) {
5301             return mThemeOverlayReadyUsers.contains(userId);
5302         }
5303     }
5304 
ensureBootCompleted()5305     final void ensureBootCompleted() {
5306         boolean booting;
5307         boolean enableScreen;
5308         synchronized (this) {
5309             booting = mBooting;
5310             mBooting = false;
5311             enableScreen = !mBooted;
5312             mBooted = true;
5313         }
5314 
5315         if (booting) {
5316             finishBooting();
5317         }
5318 
5319         if (enableScreen) {
5320             mAtmInternal.enableScreenAfterBoot(mBooted);
5321         }
5322     }
5323 
5324     /**
5325      * @deprecated Use {@link #getIntentSenderWithFeature} instead
5326      */
5327     @Deprecated
5328     @Override
getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5329     public IIntentSender getIntentSender(int type,
5330             String packageName, IBinder token, String resultWho,
5331             int requestCode, Intent[] intents, String[] resolvedTypes,
5332             int flags, Bundle bOptions, int userId) {
5333         return getIntentSenderWithFeature(type, packageName, null, token, resultWho, requestCode,
5334                 intents, resolvedTypes, flags, bOptions, userId);
5335     }
5336 
5337     @Override
getIntentSenderWithFeature(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5338     public IIntentSender getIntentSenderWithFeature(int type, String packageName, String featureId,
5339             IBinder token, String resultWho, int requestCode, Intent[] intents,
5340             String[] resolvedTypes, int flags, Bundle bOptions, int userId) {
5341         enforceNotIsolatedCaller("getIntentSender");
5342 
5343         return getIntentSenderWithFeatureAsApp(type, packageName, featureId, token, resultWho,
5344                 requestCode, intents, resolvedTypes, flags, bOptions, userId,
5345                 Binder.getCallingUid());
5346     }
5347 
5348     /**
5349      * System-internal callers can invoke this with owningUid being the app's own identity
5350      * rather than the public API's behavior of always assigning ownership to the actual
5351      * caller identity.  This will create an IntentSender as though the package/userid/uid app
5352      * were the caller, so that the ultimate PendingIntent is triggered with only the app's
5353      * capabilities and not the system's.  Used in cases like notification groups where
5354      * the OS must synthesize a PendingIntent on an app's behalf.
5355      */
getIntentSenderWithFeatureAsApp(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid)5356     public IIntentSender getIntentSenderWithFeatureAsApp(int type, String packageName,
5357             String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents,
5358             String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid) {
5359         // NOTE: The service lock isn't held in this method because nothing in the method requires
5360         // the service lock to be held.
5361 
5362         // Refuse possible leaked file descriptors
5363         if (intents != null) {
5364             if (intents.length < 1) {
5365                 throw new IllegalArgumentException("Intents array length must be >= 1");
5366             }
5367             for (int i=0; i<intents.length; i++) {
5368                 Intent intent = intents[i];
5369                 if (intent != null) {
5370                     if (intent.hasFileDescriptors()) {
5371                         throw new IllegalArgumentException("File descriptors passed in Intent");
5372                     }
5373                     if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
5374                             (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5375                         throw new IllegalArgumentException(
5376                                 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5377                     }
5378                     boolean isActivityResultType =
5379                             type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT;
5380                     if (PendingIntent.isNewMutableDisallowedImplicitPendingIntent(flags, intent,
5381                             isActivityResultType)) {
5382                         boolean isChangeEnabled = CompatChanges.isChangeEnabled(
5383                                         PendingIntent.BLOCK_MUTABLE_IMPLICIT_PENDING_INTENT,
5384                                         packageName, UserHandle.of(userId));
5385                         String resolvedType = resolvedTypes == null
5386                                 || i >= resolvedTypes.length ? null : resolvedTypes[i];
5387                         ActivityManagerUtils.logUnsafeIntentEvent(
5388                                 UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__NEW_MUTABLE_IMPLICIT_PENDING_INTENT_RETRIEVED,
5389                                 owningUid, intent, resolvedType, isChangeEnabled);
5390                         if (isChangeEnabled) {
5391                             String msg = packageName + ": Targeting U+ (version "
5392                                     + Build.VERSION_CODES.UPSIDE_DOWN_CAKE + " and above) disallows"
5393                                     + " creating or retrieving a PendingIntent with FLAG_MUTABLE,"
5394                                     + " an implicit Intent within and without FLAG_NO_CREATE and"
5395                                     + " FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT for"
5396                                     + " security reasons. To retrieve an already existing"
5397                                     + " PendingIntent, use FLAG_NO_CREATE, however, to create a"
5398                                     + " new PendingIntent with an implicit Intent use"
5399                                     + " FLAG_IMMUTABLE.";
5400                             throw new IllegalArgumentException(msg);
5401                         }
5402                     }
5403                     intents[i] = new Intent(intent);
5404                 }
5405             }
5406             if (resolvedTypes != null && resolvedTypes.length != intents.length) {
5407                 throw new IllegalArgumentException(
5408                         "Intent array length does not match resolvedTypes length");
5409             }
5410         }
5411         if (bOptions != null) {
5412             if (bOptions.hasFileDescriptors()) {
5413                 throw new IllegalArgumentException("File descriptors passed in options");
5414             }
5415         }
5416 
5417         int origUserId = userId;
5418         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), owningUid, userId,
5419                 type == ActivityManager.INTENT_SENDER_BROADCAST,
5420                 ALLOW_NON_FULL, "getIntentSender", null);
5421         if (origUserId == UserHandle.USER_CURRENT) {
5422             // We don't want to evaluate this until the pending intent is
5423             // actually executed.  However, we do want to always do the
5424             // security checking for it above.
5425             userId = UserHandle.USER_CURRENT;
5426         }
5427         try {
5428             if (owningUid != 0 && owningUid != SYSTEM_UID) {
5429                 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
5430                         MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(owningUid));
5431                 if (!UserHandle.isSameApp(owningUid, uid)) {
5432                     String msg = "Permission Denial: getIntentSender() from pid="
5433                             + Binder.getCallingPid()
5434                             + ", uid=" + owningUid
5435                             + ", (need uid=" + uid + ")"
5436                             + " is not allowed to send as package " + packageName;
5437                     Slog.w(TAG, msg);
5438                     throw new SecurityException(msg);
5439                 }
5440             }
5441 
5442             if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5443                 return mAtmInternal.getIntentSender(type, packageName, featureId, owningUid,
5444                         userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5445                         bOptions);
5446             }
5447             return mPendingIntentController.getIntentSender(type, packageName, featureId,
5448                     owningUid, userId, token, resultWho, requestCode, intents, resolvedTypes,
5449                     flags, bOptions);
5450         } catch (RemoteException e) {
5451             throw new SecurityException(e);
5452         }
5453     }
5454 
5455     @Override
sendIntentSender(IApplicationThread caller, IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5456     public int sendIntentSender(IApplicationThread caller, IIntentSender target,
5457             IBinder allowlistToken, int code, Intent intent, String resolvedType,
5458             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
5459         if (target instanceof PendingIntentRecord) {
5460             final PendingIntentRecord originalRecord = (PendingIntentRecord) target;
5461 
5462             // In multi-display scenarios, there can be background users who execute the
5463             // PendingIntent. In these scenarios, we don't want to use the foreground user as the
5464             // current user.
5465             final PendingIntentRecord.Key originalKey = originalRecord.key;
5466             final UserManagerInternal umInternal =
5467                     LocalServices.getService(UserManagerInternal.class);
5468             final int callingUserId = UserHandle.getCallingUserId();
5469             if (UserManager.isVisibleBackgroundUsersEnabled()
5470                     && originalKey.userId == UserHandle.USER_CURRENT
5471                     && callingUserId != UserHandle.USER_SYSTEM
5472                     && umInternal.isUserVisible(callingUserId)) {
5473                 EventLogTags.writeAmIntentSenderRedirectUser(callingUserId);
5474                 final PendingIntentRecord.Key key = new PendingIntentRecord.Key(originalKey.type,
5475                         originalKey.packageName, originalKey.featureId, originalKey.activity,
5476                         originalKey.who, originalKey.requestCode, originalKey.allIntents,
5477                         originalKey.allResolvedTypes, originalKey.flags, originalKey.options,
5478                         callingUserId);
5479 
5480                 final PendingIntentRecord newRecord = new PendingIntentRecord(
5481                         originalRecord.controller, key, originalRecord.uid);
5482 
5483                 return newRecord.sendWithResult(caller, code, intent, resolvedType, allowlistToken,
5484                         finishedReceiver, requiredPermission, options);
5485             }
5486 
5487             return originalRecord.sendWithResult(caller, code, intent, resolvedType, allowlistToken,
5488                     finishedReceiver, requiredPermission, options);
5489         } else {
5490             if (intent == null) {
5491                 // Weird case: someone has given us their own custom IIntentSender, and now
5492                 // they have someone else trying to send to it but of course this isn't
5493                 // really a PendingIntent, so there is no base Intent, and the caller isn't
5494                 // supplying an Intent... but we never want to dispatch a null Intent to
5495                 // a receiver, so um...  let's make something up.
5496                 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call");
5497                 intent = new Intent(Intent.ACTION_MAIN);
5498             }
5499             try {
5500                 if (allowlistToken != null) {
5501                     final int callingUid = Binder.getCallingUid();
5502                     final String packageName;
5503                     final long token = Binder.clearCallingIdentity();
5504                     try {
5505                         packageName = AppGlobals.getPackageManager().getNameForUid(callingUid);
5506                     } finally {
5507                         Binder.restoreCallingIdentity(token);
5508                     }
5509                     Slog.wtf(TAG, "Send a non-null allowlistToken to a non-PI target."
5510                             + " Calling package: " + packageName + "; intent: " + intent
5511                             + "; options: " + options);
5512                 }
5513                 target.send(code, intent, resolvedType, null, null,
5514                         requiredPermission, options);
5515             } catch (RemoteException e) {
5516             }
5517             // Platform code can rely on getting a result back when the send is done, but if
5518             // this intent sender is from outside of the system we can't rely on it doing that.
5519             // So instead we don't give it the result receiver, and instead just directly
5520             // report the finish immediately.
5521             if (finishedReceiver != null) {
5522                 try {
5523                     finishedReceiver.performReceive(intent, 0,
5524                             null, null, false, false, UserHandle.getCallingUserId());
5525                 } catch (RemoteException e) {
5526                 }
5527             }
5528             return 0;
5529         }
5530     }
5531 
5532     @Override
cancelIntentSender(IIntentSender sender)5533     public void cancelIntentSender(IIntentSender sender) {
5534         mPendingIntentController.cancelIntentSender(sender);
5535     }
5536 
5537     @Override
registerIntentSenderCancelListenerEx( IIntentSender sender, IResultReceiver receiver)5538     public boolean registerIntentSenderCancelListenerEx(
5539             IIntentSender sender, IResultReceiver receiver) {
5540         return mPendingIntentController.registerIntentSenderCancelListener(sender, receiver);
5541     }
5542 
5543     @Override
unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5544     public void unregisterIntentSenderCancelListener(IIntentSender sender,
5545             IResultReceiver receiver) {
5546         mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver);
5547     }
5548 
5549     @Override
getInfoForIntentSender(IIntentSender sender)5550     public PendingIntentInfo getInfoForIntentSender(IIntentSender sender) {
5551         if (sender instanceof PendingIntentRecord) {
5552             final PendingIntentRecord res = (PendingIntentRecord) sender;
5553             final String packageName = res.key.packageName;
5554             final int uid = res.uid;
5555             final boolean shouldFilter = getPackageManagerInternal().filterAppAccess(
5556                     packageName, Binder.getCallingUid(), UserHandle.getUserId(uid));
5557             return new PendingIntentInfo(
5558                     shouldFilter ? null : packageName,
5559                     shouldFilter ? INVALID_UID : uid,
5560                     (res.key.flags & PendingIntent.FLAG_IMMUTABLE) != 0,
5561                     res.key.type);
5562         } else {
5563             return new PendingIntentInfo(null, INVALID_UID, false,
5564                     ActivityManager.INTENT_SENDER_UNKNOWN);
5565         }
5566     }
5567 
5568     @Override
isIntentSenderTargetedToPackage(IIntentSender pendingResult)5569     public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5570         if (!(pendingResult instanceof PendingIntentRecord)) {
5571             return false;
5572         }
5573         try {
5574             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5575             if (res.key.allIntents == null) {
5576                 return false;
5577             }
5578             for (int i=0; i<res.key.allIntents.length; i++) {
5579                 Intent intent = res.key.allIntents[i];
5580                 if (intent.getPackage() != null && intent.getComponent() != null) {
5581                     return false;
5582                 }
5583             }
5584             return true;
5585         } catch (ClassCastException e) {
5586         }
5587         return false;
5588     }
5589 
5590     @Override
isIntentSenderAnActivity(IIntentSender pendingResult)5591     public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
5592         if (!(pendingResult instanceof PendingIntentRecord)) {
5593             return false;
5594         }
5595         try {
5596             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5597             if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
5598                 return true;
5599             }
5600             return false;
5601         } catch (ClassCastException e) {
5602         }
5603         return false;
5604     }
5605 
5606     @Override
getIntentForIntentSender(IIntentSender pendingResult)5607     public Intent getIntentForIntentSender(IIntentSender pendingResult) {
5608         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5609                 "getIntentForIntentSender()");
5610         if (!(pendingResult instanceof PendingIntentRecord)) {
5611             return null;
5612         }
5613         try {
5614             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5615             return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
5616         } catch (ClassCastException e) {
5617         }
5618         return null;
5619     }
5620 
5621     @Override
queryIntentComponentsForIntentSender( IIntentSender pendingResult, int matchFlags)5622     public ParceledListSlice<ResolveInfo> queryIntentComponentsForIntentSender(
5623             IIntentSender pendingResult, int matchFlags) {
5624         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5625                 "queryIntentComponentsForIntentSender()");
5626         Objects.requireNonNull(pendingResult);
5627         final PendingIntentRecord res;
5628         try {
5629             res = (PendingIntentRecord) pendingResult;
5630         } catch (ClassCastException e) {
5631             return null;
5632         }
5633         final Intent intent = res.key.requestIntent;
5634         if (intent == null) {
5635             return null;
5636         }
5637         final int userId = res.key.userId;
5638         final int uid = res.uid;
5639         final String resolvedType = res.key.requestResolvedType;
5640         switch (res.key.type) {
5641             case ActivityManager.INTENT_SENDER_ACTIVITY:
5642                 return new ParceledListSlice<>(mPackageManagerInt.queryIntentActivities(
5643                         intent, resolvedType, matchFlags, uid, userId));
5644             case ActivityManager.INTENT_SENDER_SERVICE:
5645             case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE:
5646                 return new ParceledListSlice<>(mPackageManagerInt.queryIntentServices(
5647                         intent, matchFlags, uid, userId));
5648             case ActivityManager.INTENT_SENDER_BROADCAST:
5649                 return new ParceledListSlice<>(mPackageManagerInt.queryIntentReceivers(
5650                         intent, resolvedType, matchFlags, uid, userId, false));
5651             default: // ActivityManager.INTENT_SENDER_ACTIVITY_RESULT
5652                 throw new IllegalStateException("Unsupported intent sender type: " + res.key.type);
5653         }
5654     }
5655 
5656     @Override
getTagForIntentSender(IIntentSender pendingResult, String prefix)5657     public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
5658         if (!(pendingResult instanceof PendingIntentRecord)) {
5659             return null;
5660         }
5661         try {
5662             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5663             synchronized (this) {
5664                 return getTagForIntentSenderLocked(res, prefix);
5665             }
5666         } catch (ClassCastException e) {
5667         }
5668         return null;
5669     }
5670 
getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5671     String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) {
5672         final Intent intent = res.key.requestIntent;
5673         if (intent != null) {
5674             if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
5675                     || res.lastTagPrefix.equals(prefix))) {
5676                 return res.lastTag;
5677             }
5678             res.lastTagPrefix = prefix;
5679             final StringBuilder sb = new StringBuilder(128);
5680             if (prefix != null) {
5681                 sb.append(prefix);
5682             }
5683             if (intent.getAction() != null) {
5684                 sb.append(intent.getAction());
5685             } else if (intent.getComponent() != null) {
5686                 intent.getComponent().appendShortString(sb);
5687             } else {
5688                 sb.append("?");
5689             }
5690             return res.lastTag = sb.toString();
5691         }
5692         return null;
5693     }
5694 
5695     @Override
setProcessLimit(int max)5696     public void setProcessLimit(int max) {
5697         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5698                 "setProcessLimit()");
5699         synchronized (this) {
5700             mConstants.setOverrideMaxCachedProcesses(max);
5701             trimApplicationsLocked(true, OOM_ADJ_REASON_PROCESS_END);
5702         }
5703     }
5704 
5705     @Override
getProcessLimit()5706     public int getProcessLimit() {
5707         synchronized (this) {
5708             return mConstants.getOverrideMaxCachedProcesses();
5709         }
5710     }
5711 
importanceTokenDied(ImportanceToken token)5712     void importanceTokenDied(ImportanceToken token) {
5713         synchronized (ActivityManagerService.this) {
5714             ProcessRecord pr = null;
5715             synchronized (mPidsSelfLocked) {
5716                 ImportanceToken cur
5717                     = mImportantProcesses.get(token.pid);
5718                 if (cur != token) {
5719                     return;
5720                 }
5721                 mImportantProcesses.remove(token.pid);
5722                 pr = mPidsSelfLocked.get(token.pid);
5723                 if (pr == null) {
5724                     return;
5725                 }
5726                 pr.mState.setForcingToImportant(null);
5727                 clearProcessForegroundLocked(pr);
5728             }
5729             updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY);
5730         }
5731     }
5732 
5733     @Override
setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5734     public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) {
5735         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5736                 "setProcessImportant()");
5737         synchronized(this) {
5738             boolean changed = false;
5739 
5740             ProcessRecord pr = null;
5741             synchronized (mPidsSelfLocked) {
5742                 pr = mPidsSelfLocked.get(pid);
5743                 if (pr == null && isForeground) {
5744                     Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
5745                     return;
5746                 }
5747                 ImportanceToken oldToken = mImportantProcesses.get(pid);
5748                 if (oldToken != null) {
5749                     oldToken.token.unlinkToDeath(oldToken, 0);
5750                     mImportantProcesses.remove(pid);
5751                     if (pr != null) {
5752                         pr.mState.setForcingToImportant(null);
5753                     }
5754                     changed = true;
5755                 }
5756                 if (isForeground && token != null) {
5757                     ImportanceToken newToken = new ImportanceToken(pid, token, reason) {
5758                         @Override
5759                         public void binderDied() {
5760                             importanceTokenDied(this);
5761                         }
5762                     };
5763                     try {
5764                         token.linkToDeath(newToken, 0);
5765                         mImportantProcesses.put(pid, newToken);
5766                         pr.mState.setForcingToImportant(newToken);
5767                         changed = true;
5768                     } catch (RemoteException e) {
5769                         // If the process died while doing this, we will later
5770                         // do the cleanup with the process death link.
5771                     }
5772                 }
5773             }
5774 
5775             if (changed) {
5776                 updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY);
5777             }
5778         }
5779     }
5780 
isAppForeground(int uid)5781     private boolean isAppForeground(int uid) {
5782         synchronized (mProcLock) {
5783             UidRecord uidRec = mProcessList.mActiveUids.get(uid);
5784             if (uidRec == null || uidRec.isIdle()) {
5785                 return false;
5786             }
5787             return uidRec.getCurProcState() <= PROCESS_STATE_IMPORTANT_FOREGROUND;
5788         }
5789     }
5790 
isAppBad(final String processName, final int uid)5791     private boolean isAppBad(final String processName, final int uid) {
5792         return mAppErrors.isBadProcess(processName, uid);
5793     }
5794 
5795     // NOTE: this is an internal method used by the OnShellCommand implementation only and should
5796     // be guarded by permission checking.
getUidState(int uid)5797     int getUidState(int uid) {
5798         synchronized (mProcLock) {
5799             return mProcessList.getUidProcStateLOSP(uid);
5800         }
5801     }
5802 
5803     @GuardedBy("this")
getUidStateLocked(int uid)5804     int getUidStateLocked(int uid) {
5805         return mProcessList.getUidProcStateLOSP(uid);
5806     }
5807 
5808     @GuardedBy("this")
getUidProcessCapabilityLocked(int uid)5809     int getUidProcessCapabilityLocked(int uid) {
5810         return mProcessList.getUidProcessCapabilityLOSP(uid);
5811     }
5812 
5813     // =========================================================
5814     // PROCESS INFO
5815     // =========================================================
5816 
5817     static class ProcessInfoService extends IProcessInfoService.Stub {
5818         final ActivityManagerService mActivityManagerService;
ProcessInfoService(ActivityManagerService activityManagerService)5819         ProcessInfoService(ActivityManagerService activityManagerService) {
5820             mActivityManagerService = activityManagerService;
5821         }
5822 
5823         @Override
getProcessStatesFromPids( int[] pids, int[] states)5824         public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) {
5825             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5826                     /*in*/ pids, /*out*/ states, null);
5827         }
5828 
5829         @Override
getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5830         public void getProcessStatesAndOomScoresFromPids(
5831                 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5832             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5833                     /*in*/ pids, /*out*/ states, /*out*/ scores);
5834         }
5835     }
5836 
5837     /**
5838      * For each PID in the given input array, write the current process state
5839      * for that process into the states array, or -1 to indicate that no
5840      * process with the given PID exists. If scores array is provided, write
5841      * the oom score for the process into the scores array, with INVALID_ADJ
5842      * indicating the PID doesn't exist.
5843      */
getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5844     public void getProcessStatesAndOomScoresForPIDs(
5845             /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5846         if (scores != null) {
5847             enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE,
5848                     "getProcessStatesAndOomScoresForPIDs()");
5849         }
5850 
5851         if (pids == null) {
5852             throw new NullPointerException("pids");
5853         } else if (states == null) {
5854             throw new NullPointerException("states");
5855         } else if (pids.length != states.length) {
5856             throw new IllegalArgumentException("pids and states arrays have different lengths!");
5857         } else if (scores != null && pids.length != scores.length) {
5858             throw new IllegalArgumentException("pids and scores arrays have different lengths!");
5859         }
5860 
5861         synchronized (mProcLock) {
5862             synchronized (mPidsSelfLocked) {
5863                 int newestTimeIndex = -1;
5864                 long newestTime = Long.MIN_VALUE;
5865                 for (int i = 0; i < pids.length; i++) {
5866                     ProcessRecord pr = mPidsSelfLocked.get(pids[i]);
5867                     if (pr != null) {
5868                         final long pendingTopTime =
5869                                 mPendingStartActivityUids.getPendingTopPidTime(pr.uid, pids[i]);
5870                         if (pendingTopTime != PendingStartActivityUids.INVALID_TIME) {
5871                             // The uid in mPendingStartActivityUids gets the TOP process state.
5872                             states[i] = PROCESS_STATE_TOP;
5873                             if (scores != null) {
5874                                 // The uid in mPendingStartActivityUids gets a better score.
5875                                 scores[i] = ProcessList.FOREGROUND_APP_ADJ - 1;
5876                             }
5877                             if (pendingTopTime > newestTime) {
5878                                 newestTimeIndex = i;
5879                                 newestTime = pendingTopTime;
5880                             }
5881                         } else {
5882                             states[i] = pr.mState.getCurProcState();
5883                             if (scores != null) {
5884                                 scores[i] = pr.mState.getCurAdj();
5885                             }
5886                         }
5887                     } else {
5888                         states[i] = PROCESS_STATE_NONEXISTENT;
5889                         if (scores != null) {
5890                             scores[i] = ProcessList.INVALID_ADJ;
5891                         }
5892                     }
5893                 }
5894                 // The uid with the newest timestamp in mPendingStartActivityUids gets the best
5895                 // score.
5896                 if (newestTimeIndex != -1) {
5897                     if (scores != null) {
5898                         scores[newestTimeIndex] = ProcessList.FOREGROUND_APP_ADJ - 2;
5899                     }
5900                 }
5901             }
5902         }
5903     }
5904 
5905     // =========================================================
5906     // PERMISSIONS
5907     // =========================================================
5908 
5909     static class PermissionController extends IPermissionController.Stub {
5910         ActivityManagerService mActivityManagerService;
PermissionController(ActivityManagerService activityManagerService)5911         PermissionController(ActivityManagerService activityManagerService) {
5912             mActivityManagerService = activityManagerService;
5913         }
5914 
5915         @Override
checkPermission(String permission, int pid, int uid)5916         public boolean checkPermission(String permission, int pid, int uid) {
5917             return mActivityManagerService.checkPermission(permission, pid,
5918                     uid) == PackageManager.PERMISSION_GRANTED;
5919         }
5920 
5921         @Override
noteOp(String op, int uid, String packageName)5922         public int noteOp(String op, int uid, String packageName) {
5923             // TODO moltmann: Allow to specify featureId
5924             return mActivityManagerService.mAppOpsService
5925                     .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName, null,
5926                             false, "", false).getOpMode();
5927         }
5928 
5929         @Override
getPackagesForUid(int uid)5930         public String[] getPackagesForUid(int uid) {
5931             return mActivityManagerService.mContext.getPackageManager()
5932                     .getPackagesForUid(uid);
5933         }
5934 
5935         @Override
isRuntimePermission(String permission)5936         public boolean isRuntimePermission(String permission) {
5937             try {
5938                 PermissionInfo info = mActivityManagerService.mContext.getPackageManager()
5939                         .getPermissionInfo(permission, 0);
5940                 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
5941                         == PermissionInfo.PROTECTION_DANGEROUS;
5942             } catch (NameNotFoundException nnfe) {
5943                 Slog.e(TAG, "No such permission: "+ permission, nnfe);
5944             }
5945             return false;
5946         }
5947 
5948         @Override
getPackageUid(String packageName, int flags)5949         public int getPackageUid(String packageName, int flags) {
5950             try {
5951                 return mActivityManagerService.mContext.getPackageManager()
5952                         .getPackageUid(packageName, flags);
5953             } catch (NameNotFoundException nnfe) {
5954                 return -1;
5955             }
5956         }
5957     }
5958 
5959     class IntentFirewallInterface implements IntentFirewall.AMSInterface {
5960         @Override
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5961         public int checkComponentPermission(String permission, int pid, int uid,
5962                 int owningUid, boolean exported) {
5963             return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
5964                     owningUid, exported);
5965         }
5966 
5967         @Override
getAMSLock()5968         public Object getAMSLock() {
5969             return ActivityManagerService.this;
5970         }
5971     }
5972 
5973     /**
5974      * Allows if {@code pid} is {@link #MY_PID}, then denies if the {@code pid} has been denied
5975      * provided non-{@code null} {@code permission} before. Otherwise calls into
5976      * {@link ActivityManager#checkComponentPermission(String, int, int, boolean)}.
5977      */
5978     @PackageManager.PermissionResult
5979     @PermissionMethod
checkComponentPermission(@ermissionName String permission, int pid, int uid, int owningUid, boolean exported)5980     public static int checkComponentPermission(@PermissionName String permission, int pid, int uid,
5981             int owningUid, boolean exported) {
5982         if (pid == MY_PID) {
5983             return PackageManager.PERMISSION_GRANTED;
5984         }
5985         // If there is an explicit permission being checked, and this is coming from a process
5986         // that has been denied access to that permission, then just deny.  Ultimately this may
5987         // not be quite right -- it means that even if the caller would have access for another
5988         // reason (such as being the owner of the component it is trying to access), it would still
5989         // fail.  This also means the system and root uids would be able to deny themselves
5990         // access to permissions, which...  well okay. ¯\_(ツ)_/¯
5991         if (permission != null) {
5992             synchronized (sActiveProcessInfoSelfLocked) {
5993                 ProcessInfo procInfo = sActiveProcessInfoSelfLocked.get(pid);
5994                 if (procInfo != null && procInfo.deniedPermissions != null
5995                         && procInfo.deniedPermissions.contains(permission)) {
5996                     return PackageManager.PERMISSION_DENIED;
5997                 }
5998             }
5999         }
6000         return ActivityManager.checkComponentPermission(permission, uid,
6001                 owningUid, exported);
6002     }
6003 
enforceDebuggable(ProcessRecord proc)6004     private void enforceDebuggable(ProcessRecord proc) {
6005         if (!Build.IS_DEBUGGABLE && !proc.isDebuggable()) {
6006             throw new SecurityException("Process not debuggable: " + proc.info.packageName);
6007         }
6008     }
6009 
enforceDebuggable(ApplicationInfo info)6010     private void enforceDebuggable(ApplicationInfo info) {
6011         if (!Build.IS_DEBUGGABLE && (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6012             throw new SecurityException("Process not debuggable: " + info.packageName);
6013         }
6014     }
6015 
6016     /**
6017      * As the only public entry point for permissions checking, this method
6018      * can enforce the semantic that requesting a check on a null global
6019      * permission is automatically denied.  (Internally a null permission
6020      * string is used when calling {@link #checkComponentPermission} in cases
6021      * when only uid-based security is needed.)
6022      *
6023      * This can be called with or without the global lock held.
6024      */
6025     @Override
6026     @PackageManager.PermissionResult
6027     @PermissionMethod
checkPermission(@ermissionName String permission, int pid, int uid)6028     public int checkPermission(@PermissionName String permission, int pid, int uid) {
6029         if (permission == null) {
6030             return PackageManager.PERMISSION_DENIED;
6031         }
6032         return checkComponentPermission(permission, pid, uid, -1, true);
6033     }
6034 
6035     /**
6036      * Binder IPC calls go through the public entry point.
6037      * This can be called with or without the global lock held.
6038      */
6039     @PackageManager.PermissionResult
6040     @PermissionMethod
checkCallingPermission(@ermissionName String permission)6041     int checkCallingPermission(@PermissionName String permission) {
6042         return checkPermission(permission,
6043                 Binder.getCallingPid(),
6044                 Binder.getCallingUid());
6045     }
6046 
6047     /**
6048      * This can be called with or without the global lock held.
6049      */
6050     @PermissionMethod
enforceCallingPermission(@ermissionName String permission, String func)6051     void enforceCallingPermission(@PermissionName String permission, String func) {
6052         if (checkCallingPermission(permission)
6053                 == PackageManager.PERMISSION_GRANTED) {
6054             return;
6055         }
6056 
6057         String msg = "Permission Denial: " + func + " from pid="
6058                 + Binder.getCallingPid()
6059                 + ", uid=" + Binder.getCallingUid()
6060                 + " requires " + permission;
6061         Slog.w(TAG, msg);
6062         throw new SecurityException(msg);
6063     }
6064 
6065     /**
6066      * This can be called with or without the global lock held.
6067      */
6068     @PermissionMethod(anyOf = true)
enforceCallingHasAtLeastOnePermission(String func, String... permissions)6069     private void enforceCallingHasAtLeastOnePermission(String func, String... permissions) {
6070         for (String permission : permissions) {
6071             if (checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
6072                 return;
6073             }
6074         }
6075 
6076         String msg = "Permission Denial: " + func + " from pid="
6077                 + Binder.getCallingPid()
6078                 + ", uid=" + Binder.getCallingUid()
6079                 + " requires one of " + Arrays.toString(permissions);
6080         Slog.w(TAG, msg);
6081         throw new SecurityException(msg);
6082     }
6083 
6084     /**
6085      * This can be called with or without the global lock held.
6086      */
6087     @PermissionMethod
enforcePermission(@ermissionName String permission, int pid, int uid, String func)6088     void enforcePermission(@PermissionName String permission, int pid, int uid, String func) {
6089         if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) {
6090             return;
6091         }
6092 
6093         String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid
6094                 + " requires " + permission;
6095         Slog.w(TAG, msg);
6096         throw new SecurityException(msg);
6097     }
6098 
isAppStartModeDisabled(int uid, String packageName)6099     public boolean isAppStartModeDisabled(int uid, String packageName) {
6100         synchronized (mProcLock) {
6101             return getAppStartModeLOSP(uid, packageName, 0, -1, false, true, false)
6102                     == ActivityManager.APP_START_MODE_DISABLED;
6103         }
6104     }
6105 
isInRestrictedBucket(int userId, String packageName, long nowElapsed)6106     private boolean isInRestrictedBucket(int userId, String packageName, long nowElapsed) {
6107         return UsageStatsManager.STANDBY_BUCKET_RESTRICTED
6108                 <= mUsageStatsService.getAppStandbyBucket(packageName, userId, nowElapsed);
6109     }
6110 
6111     // Unified app-op and target sdk check
6112     @GuardedBy(anyOf = {"this", "mProcLock"})
appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6113     int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) {
6114         // Apps that target O+ are always subject to background check
6115         if (packageTargetSdk >= Build.VERSION_CODES.O) {
6116             if (DEBUG_BACKGROUND_CHECK) {
6117                 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
6118             }
6119             return ActivityManager.APP_START_MODE_DELAYED_RIGID;
6120         }
6121         // It's a legacy app. If it's in the RESTRICTED bucket, always restrict on battery.
6122         if (mOnBattery // Short-circuit in common case.
6123                 && mConstants.FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS
6124                 && isInRestrictedBucket(
6125                         UserHandle.getUserId(uid), packageName, SystemClock.elapsedRealtime())) {
6126             if (DEBUG_BACKGROUND_CHECK) {
6127                 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " in RESTRICTED bucket");
6128             }
6129             return ActivityManager.APP_START_MODE_DELAYED;
6130         }
6131         // Not in the RESTRICTED bucket so policy is based on AppOp check.
6132         int appop = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_RUN_IN_BACKGROUND,
6133                 uid, packageName, null, "");
6134         if (DEBUG_BACKGROUND_CHECK) {
6135             Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop);
6136         }
6137         switch (appop) {
6138             case AppOpsManager.MODE_ALLOWED:
6139                 // If force-background-check is enabled, restrict all apps that aren't allowlisted.
6140                 if (mForceBackgroundCheck &&
6141                         !UserHandle.isCore(uid) &&
6142                         !isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ true)) {
6143                     if (DEBUG_BACKGROUND_CHECK) {
6144                         Slog.i(TAG, "Force background check: " +
6145                                 uid + "/" + packageName + " restricted");
6146                     }
6147                     return ActivityManager.APP_START_MODE_DELAYED;
6148                 }
6149                 return ActivityManager.APP_START_MODE_NORMAL;
6150             case AppOpsManager.MODE_IGNORED:
6151                 return ActivityManager.APP_START_MODE_DELAYED;
6152             default:
6153                 return ActivityManager.APP_START_MODE_DELAYED_RIGID;
6154         }
6155     }
6156 
6157     // Service launch is available to apps with run-in-background exemptions but
6158     // some other background operations are not.  If we're doing a check
6159     // of service-launch policy, allow those callers to proceed unrestricted.
6160     @GuardedBy(anyOf = {"this", "mProcLock"})
appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6161     int appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) {
6162         // Persistent app?
6163         if (mPackageManagerInt.isPackagePersistent(packageName)) {
6164             if (DEBUG_BACKGROUND_CHECK) {
6165                 Slog.i(TAG, "App " + uid + "/" + packageName
6166                         + " is persistent; not restricted in background");
6167             }
6168             return ActivityManager.APP_START_MODE_NORMAL;
6169         }
6170 
6171         // Non-persistent but background whitelisted?
6172         if (uidOnBackgroundAllowlistLOSP(uid)) {
6173             if (DEBUG_BACKGROUND_CHECK) {
6174                 Slog.i(TAG, "App " + uid + "/" + packageName
6175                         + " on background allowlist; not restricted in background");
6176             }
6177             return ActivityManager.APP_START_MODE_NORMAL;
6178         }
6179 
6180         // Is this app on the battery whitelist?
6181         if (isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ false)) {
6182             if (DEBUG_BACKGROUND_CHECK) {
6183                 Slog.i(TAG, "App " + uid + "/" + packageName
6184                         + " on idle allowlist; not restricted in background");
6185             }
6186             return ActivityManager.APP_START_MODE_NORMAL;
6187         }
6188 
6189         // None of the service-policy criteria apply, so we apply the common criteria
6190         return appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk);
6191     }
6192 
6193     @GuardedBy(anyOf = {"this", "mProcLock"})
getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6194     int getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk,
6195             int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) {
6196         if (mInternal.isPendingTopUid(uid)) {
6197             return ActivityManager.APP_START_MODE_NORMAL;
6198         }
6199         UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
6200         if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg="
6201                 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle="
6202                 + (uidRec != null ? uidRec.isIdle() : false));
6203         if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.isIdle()) {
6204             boolean ephemeral;
6205             if (uidRec == null) {
6206                 ephemeral = getPackageManagerInternal().isPackageEphemeral(
6207                         UserHandle.getUserId(uid), packageName);
6208             } else {
6209                 ephemeral = uidRec.isEphemeral();
6210             }
6211 
6212             if (ephemeral) {
6213                 // We are hard-core about ephemeral apps not running in the background.
6214                 return ActivityManager.APP_START_MODE_DISABLED;
6215             } else {
6216                 if (disabledOnly) {
6217                     // The caller is only interested in whether app starts are completely
6218                     // disabled for the given package (that is, it is an instant app).  So
6219                     // we don't need to go further, which is all just seeing if we should
6220                     // apply a "delayed" mode for a regular app.
6221                     return ActivityManager.APP_START_MODE_NORMAL;
6222                 }
6223                 final int startMode = (alwaysRestrict)
6224                         ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk)
6225                         : appServicesRestrictedInBackgroundLOSP(uid, packageName,
6226                                 packageTargetSdk);
6227                 if (DEBUG_BACKGROUND_CHECK) {
6228                     Slog.d(TAG, "checkAllowBackground: uid=" + uid
6229                             + " pkg=" + packageName + " startMode=" + startMode
6230                             + " onallowlist=" + isOnDeviceIdleAllowlistLOSP(uid, false)
6231                             + " onallowlist(ei)=" + isOnDeviceIdleAllowlistLOSP(uid, true));
6232                 }
6233                 if (startMode == ActivityManager.APP_START_MODE_DELAYED) {
6234                     // This is an old app that has been forced into a "compatible as possible"
6235                     // mode of background check.  To increase compatibility, we will allow other
6236                     // foreground apps to cause its services to start.
6237                     if (callingPid >= 0) {
6238                         ProcessRecord proc;
6239                         synchronized (mPidsSelfLocked) {
6240                             proc = mPidsSelfLocked.get(callingPid);
6241                         }
6242                         if (proc != null && !ActivityManager.isProcStateBackground(
6243                                 proc.mState.getCurProcState())) {
6244                             // Whoever is instigating this is in the foreground, so we will allow it
6245                             // to go through.
6246                             return ActivityManager.APP_START_MODE_NORMAL;
6247                         }
6248                     }
6249                 }
6250                 return startMode;
6251             }
6252         }
6253         return ActivityManager.APP_START_MODE_NORMAL;
6254     }
6255 
6256     /**
6257      * @return whether a UID is in the system, user or temp doze allowlist.
6258      */
6259     @GuardedBy(anyOf = {"this", "mProcLock"})
isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo)6260     boolean isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo) {
6261         final int appId = UserHandle.getAppId(uid);
6262 
6263         final int[] allowlist = allowExceptIdleToo
6264                 ? mDeviceIdleExceptIdleAllowlist
6265                 : mDeviceIdleAllowlist;
6266 
6267         return Arrays.binarySearch(allowlist, appId) >= 0
6268                 || Arrays.binarySearch(mDeviceIdleTempAllowlist, appId) >= 0
6269                 || mPendingTempAllowlist.get(uid) != null;
6270     }
6271 
6272     /**
6273      * Is the uid allowlisted to start FGS?
6274      * @param uid
6275      * @return a TempAllowListEntry if the uid is allowed.
6276      *         null if the uid is not allowed.
6277      */
6278     @Nullable
6279     @GuardedBy(anyOf = {"this", "mProcLock"})
isAllowlistedForFgsStartLOSP(int uid)6280     FgsTempAllowListItem isAllowlistedForFgsStartLOSP(int uid) {
6281         if (Arrays.binarySearch(mDeviceIdleExceptIdleAllowlist, UserHandle.getAppId(uid)) >= 0) {
6282             return FAKE_TEMP_ALLOW_LIST_ITEM;
6283         }
6284         final Pair<Long, FgsTempAllowListItem> entry = mFgsStartTempAllowList.get(uid);
6285         return entry == null ? null : entry.second;
6286     }
6287 
6288     private static class GetBackgroundStartPrivilegesFunctor implements Consumer<ProcessRecord> {
6289         private BackgroundStartPrivileges mBackgroundStartPrivileges =
6290                 BackgroundStartPrivileges.NONE;
6291         private int mUid;
6292 
prepare(int uid)6293         void prepare(int uid) {
6294             mUid = uid;
6295             mBackgroundStartPrivileges = BackgroundStartPrivileges.NONE;
6296         }
6297 
6298         @NonNull
getResult()6299         BackgroundStartPrivileges getResult() {
6300             return mBackgroundStartPrivileges;
6301         }
6302 
accept(ProcessRecord pr)6303         public void accept(ProcessRecord pr) {
6304             if (pr.uid == mUid) {
6305                 mBackgroundStartPrivileges =
6306                         mBackgroundStartPrivileges.merge(pr.getBackgroundStartPrivileges());
6307             }
6308         }
6309     }
6310 
6311     private final GetBackgroundStartPrivilegesFunctor mGetBackgroundStartPrivilegesFunctor =
6312             new GetBackgroundStartPrivilegesFunctor();
6313 
6314     /**
6315      * Returns the current complete {@link BackgroundStartPrivileges} of the UID.
6316      */
6317     @NonNull
getBackgroundStartPrivileges(int uid)6318     private BackgroundStartPrivileges getBackgroundStartPrivileges(int uid) {
6319         synchronized (mProcLock) {
6320             final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
6321             if (uidRecord == null) {
6322                 return BackgroundStartPrivileges.NONE;
6323             }
6324             mGetBackgroundStartPrivilegesFunctor.prepare(uid);
6325             uidRecord.forEachProcess(mGetBackgroundStartPrivilegesFunctor);
6326             return mGetBackgroundStartPrivilegesFunctor.getResult();
6327         }
6328     }
6329 
6330     /**
6331      * Returns true if the reasonCode is included in the base set of reasons an app may be
6332      * allowed to schedule a
6333      * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}.
6334      * This is a shortcut and <b>DOES NOT</b> include all reasons.
6335      * Use {@link #canScheduleUserInitiatedJobs(int, int, String)} to cover all cases.
6336      */
doesReasonCodeAllowSchedulingUserInitiatedJobs(int reasonCode)6337     static boolean doesReasonCodeAllowSchedulingUserInitiatedJobs(int reasonCode) {
6338         switch (reasonCode) {
6339             case REASON_PROC_STATE_PERSISTENT:
6340             case REASON_PROC_STATE_PERSISTENT_UI:
6341             case REASON_PROC_STATE_TOP:
6342             case REASON_PROC_STATE_BTOP:
6343             case REASON_UID_VISIBLE:
6344             case REASON_SYSTEM_UID:
6345             case REASON_START_ACTIVITY_FLAG:
6346             case REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD:
6347             case REASON_SYSTEM_ALERT_WINDOW_PERMISSION:
6348             case REASON_COMPANION_DEVICE_MANAGER:
6349             case REASON_BACKGROUND_ACTIVITY_PERMISSION:
6350             case REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION:
6351                 return true;
6352         }
6353         return false;
6354     }
6355 
6356     /**
6357      * Returns true if the ProcessRecord has some conditions that allow the app to schedule a
6358      * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}.
6359      * This is a shortcut and <b>DOES NOT</b> include all reasons.
6360      * Use {@link #canScheduleUserInitiatedJobs(int, int, String)} to cover all cases.
6361      */
6362     @GuardedBy(anyOf = {"this", "mProcLock"})
isProcessInStateToScheduleUserInitiatedJobsLocked( @ullable ProcessRecord pr, long nowElapsed)6363     private boolean isProcessInStateToScheduleUserInitiatedJobsLocked(
6364             @Nullable ProcessRecord pr, long nowElapsed) {
6365         if (pr == null) {
6366             return false;
6367         }
6368 
6369         final BackgroundStartPrivileges backgroundStartPrivileges =
6370                 pr.getBackgroundStartPrivileges();
6371         // Is the allow activity background start flag on?
6372         if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) {
6373             // REASON_START_ACTIVITY_FLAG;
6374             return true;
6375         }
6376 
6377         final ProcessStateRecord state = pr.mState;
6378         final int procstate = state.getCurProcState();
6379         if (procstate <= PROCESS_STATE_BOUND_TOP) {
6380             if (doesReasonCodeAllowSchedulingUserInitiatedJobs(
6381                     getReasonCodeFromProcState(procstate))) {
6382                 return true;
6383             }
6384         }
6385 
6386         final long lastInvisibleTime = state.getLastInvisibleTime();
6387         if (lastInvisibleTime > 0 && lastInvisibleTime < Long.MAX_VALUE) {
6388             final long timeSinceVisibleMs = nowElapsed - lastInvisibleTime;
6389             if (timeSinceVisibleMs < mConstants.mVisibleToInvisibleUijScheduleGraceDurationMs) {
6390                 // REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD
6391                 return true;
6392             }
6393         }
6394 
6395         final ProcessServiceRecord psr = pr.mServices;
6396         if (psr != null && psr.hasForegroundServices()) {
6397             for (int s = psr.numberOfRunningServices() - 1; s >= 0; --s) {
6398                 final ServiceRecord sr = psr.getRunningServiceAt(s);
6399                 if (sr.isForeground && sr.mAllowUiJobScheduling) {
6400                     return true;
6401                 }
6402             }
6403         }
6404 
6405         return false;
6406     }
6407 
6408     /**
6409      * Returns whether the app in question is in a state where we allow scheduling a
6410      * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}.
6411      */
6412     // TODO(262260570): log allow reason to an atom
canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)6413     boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName) {
6414         synchronized (this) {
6415             final ProcessRecord processRecord;
6416             synchronized (mPidsSelfLocked) {
6417                 processRecord = mPidsSelfLocked.get(pid);
6418             }
6419 
6420             final long nowElapsed = SystemClock.elapsedRealtime();
6421             final BackgroundStartPrivileges backgroundStartPrivileges;
6422             if (processRecord != null) {
6423                 if (isProcessInStateToScheduleUserInitiatedJobsLocked(processRecord, nowElapsed)) {
6424                     return true;
6425                 }
6426                 backgroundStartPrivileges = processRecord.getBackgroundStartPrivileges();
6427             } else {
6428                 backgroundStartPrivileges = getBackgroundStartPrivileges(uid);
6429             }
6430             // Is the allow activity background start flag on?
6431             if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) {
6432                 // REASON_START_ACTIVITY_FLAG;
6433                 return true;
6434             }
6435 
6436             // We allow scheduling a user-initiated job when the app is in the TOP or a
6437             // Background Activity Launch approved state. These are cases that indicate the user
6438             // has interacted with the app and therefore it is reasonable to believe the app may
6439             // attempt to schedule a user-initiated job in response to the user interaction.
6440             // As of Android UDC, the conditions required to grant a while-in-use permission
6441             // covers the majority of those cases, and so we piggyback on that logic as the base.
6442             // Missing cases are added after.
6443             if (mServices.canAllowWhileInUsePermissionInFgsLocked(
6444                     pid, uid, pkgName, processRecord, backgroundStartPrivileges)) {
6445                 return true;
6446             }
6447 
6448             final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
6449             if (uidRecord != null) {
6450                 for (int i = uidRecord.getNumOfProcs() - 1; i >= 0; --i) {
6451                     ProcessRecord pr = uidRecord.getProcessRecordByIndex(i);
6452                     if (isProcessInStateToScheduleUserInitiatedJobsLocked(pr, nowElapsed)) {
6453                         return true;
6454                     }
6455                 }
6456             }
6457 
6458             if (mAtmInternal.hasSystemAlertWindowPermission(uid, pid, pkgName)) {
6459                 // REASON_SYSTEM_ALERT_WINDOW_PERMISSION;
6460                 return true;
6461             }
6462 
6463             final int userId = UserHandle.getUserId(uid);
6464             final boolean isCompanionApp = mInternal.isAssociatedCompanionApp(userId, uid);
6465             if (isCompanionApp) {
6466                 if (checkPermission(REQUEST_COMPANION_RUN_IN_BACKGROUND, pid, uid)
6467                         == PERMISSION_GRANTED) {
6468                     // REASON_COMPANION_DEVICE_MANAGER;
6469                     return true;
6470                 }
6471             }
6472         }
6473 
6474         return false;
6475     }
6476 
6477     /**
6478      * @return allowlist tag for a uid from mPendingTempAllowlist, null if not currently on
6479      * the allowlist
6480      */
6481     @GuardedBy(anyOf = {"this", "mProcLock"})
getPendingTempAllowlistTagForUidLOSP(int uid)6482     String getPendingTempAllowlistTagForUidLOSP(int uid) {
6483         final PendingTempAllowlist ptw = mPendingTempAllowlist.get(uid);
6484         return ptw != null ? ptw.tag : null;
6485     }
6486 
6487     @VisibleForTesting
grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId)6488     public void grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId) {
6489         getPackageManagerInternal()
6490                 .grantImplicitAccess(userId, intent, recipientAppId, visibleUid, true /*direct*/);
6491     }
6492 
6493     /**
6494      * @param uri This uri must NOT contain an embedded userId.
6495      * @param userId The userId in which the uri is to be resolved.
6496      */
6497     @Override
checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6498     public int checkUriPermission(Uri uri, int pid, int uid,
6499             final int modeFlags, int userId, IBinder callerToken) {
6500         enforceNotIsolatedCaller("checkUriPermission");
6501 
6502         // Our own process gets to do everything.
6503         if (pid == MY_PID) {
6504             return PackageManager.PERMISSION_GRANTED;
6505         }
6506         if (uid != ROOT_UID) { // bypass the root
6507             if (mPackageManagerInt.filterAppAccess(uid, Binder.getCallingUid())) {
6508                 return PackageManager.PERMISSION_DENIED;
6509             }
6510         }
6511         return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, modeFlags), uid, modeFlags)
6512                 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED;
6513     }
6514 
6515     @Override
checkUriPermissions(@onNull List<Uri> uris, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6516     public int[] checkUriPermissions(@NonNull List<Uri> uris, int pid, int uid,
6517             final int modeFlags, int userId, IBinder callerToken) {
6518         final int size = uris.size();
6519         int[] res = new int[size];
6520         // Default value DENIED.
6521         Arrays.fill(res, PackageManager.PERMISSION_DENIED);
6522 
6523         for (int i = 0; i < size; i++) {
6524             final Uri uri = uris.get(i);
6525             final int userIdFromUri = ContentProvider.getUserIdFromUri(uri, userId);
6526             res[i] = checkUriPermission(ContentProvider.getUriWithoutUserId(uri), pid, uid,
6527                     modeFlags, userIdFromUri, callerToken);
6528         }
6529         return res;
6530     }
6531 
6532     /**
6533      * @param uri This uri must NOT contain an embedded userId.
6534      * @param userId The userId in which the uri is to be resolved.
6535      */
6536     @Override
grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6537     public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
6538             final int modeFlags, int userId) {
6539         enforceNotIsolatedCaller("grantUriPermission");
6540         GrantUri grantUri = new GrantUri(userId, uri, modeFlags);
6541         synchronized (this) {
6542             final ProcessRecord r = getRecordForAppLOSP(caller);
6543             if (r == null) {
6544                 throw new SecurityException("Unable to find app for caller "
6545                         + caller
6546                         + " when granting permission to uri " + grantUri);
6547             }
6548             if (targetPkg == null) {
6549                 throw new IllegalArgumentException("null target");
6550             }
6551             final int callingUserId = UserHandle.getUserId(r.uid);
6552             if (mPackageManagerInt.filterAppAccess(targetPkg, r.uid, callingUserId)) {
6553                 return;
6554             }
6555 
6556             Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
6557                     | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
6558                     | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
6559                     | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
6560 
6561             final Intent intent = new Intent();
6562             intent.setData(uri);
6563             intent.setFlags(modeFlags);
6564 
6565             final NeededUriGrants needed = mUgmInternal.checkGrantUriPermissionFromIntent(intent,
6566                     r.uid, targetPkg, callingUserId);
6567             mUgmInternal.grantUriPermissionUncheckedFromIntent(needed, null);
6568         }
6569     }
6570 
6571     /**
6572      * @param uri This uri must NOT contain an embedded userId.
6573      * @param userId The userId in which the uri is to be resolved.
6574      */
6575     @Override
revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6576     public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri,
6577             final int modeFlags, int userId) {
6578         enforceNotIsolatedCaller("revokeUriPermission");
6579         synchronized (this) {
6580             final ProcessRecord r = getRecordForAppLOSP(caller);
6581             if (r == null) {
6582                 throw new SecurityException("Unable to find app for caller "
6583                         + caller
6584                         + " when revoking permission to uri " + uri);
6585             }
6586             if (uri == null) {
6587                 Slog.w(TAG, "revokeUriPermission: null uri");
6588                 return;
6589             }
6590 
6591             if (!Intent.isAccessUriMode(modeFlags)) {
6592                 return;
6593             }
6594 
6595             final String authority = uri.getAuthority();
6596             final ProviderInfo pi = mCpHelper.getProviderInfoLocked(authority, userId,
6597                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
6598             if (pi == null) {
6599                 Slog.w(TAG, "No content provider found for permission revoke: "
6600                         + uri.toSafeString());
6601                 return;
6602             }
6603 
6604             mUgmInternal.revokeUriPermission(targetPackage, r.uid,
6605                     new GrantUri(userId, uri, modeFlags), modeFlags);
6606         }
6607     }
6608 
6609     @Override
showWaitingForDebugger(IApplicationThread who, boolean waiting)6610     public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
6611         synchronized (mProcLock) {
6612             final ProcessRecord app = who != null ? getRecordForAppLOSP(who) : null;
6613             if (app == null) return;
6614 
6615             Message msg = Message.obtain();
6616             msg.what = WAIT_FOR_DEBUGGER_UI_MSG;
6617             msg.obj = app;
6618             msg.arg1 = waiting ? 1 : 0;
6619             mUiHandler.sendMessage(msg);
6620         }
6621     }
6622 
6623     @Override
getMemoryInfo(ActivityManager.MemoryInfo outInfo)6624     public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
6625         mProcessList.getMemoryInfo(outInfo);
6626     }
6627 
6628     // =========================================================
6629     // TASK MANAGEMENT
6630     // =========================================================
6631 
6632     @Override
getTasks(int maxNum)6633     public List<RunningTaskInfo> getTasks(int maxNum) {
6634         return mActivityTaskManager.getTasks(maxNum);
6635     }
6636 
6637     @Override
cancelTaskWindowTransition(int taskId)6638     public void cancelTaskWindowTransition(int taskId) {
6639         mActivityTaskManager.cancelTaskWindowTransition(taskId);
6640     }
6641 
6642     @Override
setTaskResizeable(int taskId, int resizeableMode)6643     public void setTaskResizeable(int taskId, int resizeableMode) {
6644         mActivityTaskManager.setTaskResizeable(taskId, resizeableMode);
6645     }
6646 
6647     @Override
resizeTask(int taskId, Rect bounds, int resizeMode)6648     public void resizeTask(int taskId, Rect bounds, int resizeMode) {
6649         mActivityTaskManager.resizeTask(taskId, bounds, resizeMode);
6650     }
6651 
6652     @Override
getTaskBounds(int taskId)6653     public Rect getTaskBounds(int taskId) {
6654         return mActivityTaskManager.getTaskBounds(taskId);
6655     }
6656 
6657     @Override
removeTask(int taskId)6658     public boolean removeTask(int taskId) {
6659         return mActivityTaskManager.removeTask(taskId);
6660     }
6661 
6662     @Override
moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6663     public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
6664             int flags, Bundle bOptions) {
6665         mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions);
6666     }
6667 
6668     /**
6669      * Attempts to move a task backwards in z-order (the order of activities within the task is
6670      * unchanged).
6671      *
6672      * There are several possible results of this call:
6673      * - if the task is locked, then we will show the lock toast
6674      * - if there is a task behind the provided task, then that task is made visible and resumed as
6675      *   this task is moved to the back
6676      * - otherwise, if there are no other tasks in the stack:
6677      *     - if this task is in the pinned stack, then we remove the stack completely, which will
6678      *       have the effect of moving the task to the top or bottom of the fullscreen stack
6679      *       (depending on whether it is visible)
6680      *     - otherwise, we simply return home and hide this task
6681      *
6682      * @param token A reference to the activity we wish to move
6683      * @param nonRoot If false then this only works if the activity is the root
6684      *                of a task; if true it will work for any activity in a task.
6685      * @return Returns true if the move completed, false if not.
6686      */
6687     @Override
moveActivityTaskToBack(IBinder token, boolean nonRoot)6688     public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
6689         return ActivityClient.getInstance().moveActivityTaskToBack(token, nonRoot);
6690     }
6691 
6692     @Override
moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)6693     public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) {
6694         mActivityTaskManager.moveTaskToRootTask(taskId, rootTaskId, toTop);
6695     }
6696 
6697     @Override
getRecentTasks(int maxNum, int flags, int userId)6698     public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
6699             int userId) {
6700         return mActivityTaskManager.getRecentTasks(maxNum, flags, userId);
6701     }
6702 
6703     @Override
getAllRootTaskInfos()6704     public List<RootTaskInfo> getAllRootTaskInfos() {
6705         return mActivityTaskManager.getAllRootTaskInfos();
6706     }
6707 
6708     @Override
getTaskForActivity(IBinder token, boolean onlyRoot)6709     public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6710         return ActivityClient.getInstance().getTaskForActivity(token, onlyRoot);
6711     }
6712 
6713     @Override
updateLockTaskPackages(int userId, String[] packages)6714     public void updateLockTaskPackages(int userId, String[] packages) {
6715         mActivityTaskManager.updateLockTaskPackages(userId, packages);
6716     }
6717 
6718     @Override
isInLockTaskMode()6719     public boolean isInLockTaskMode() {
6720         return mActivityTaskManager.isInLockTaskMode();
6721     }
6722 
6723     @Override
getLockTaskModeState()6724     public int getLockTaskModeState() {
6725         return mActivityTaskManager.getLockTaskModeState();
6726     }
6727 
6728     @Override
startSystemLockTaskMode(int taskId)6729     public void startSystemLockTaskMode(int taskId) throws RemoteException {
6730         mActivityTaskManager.startSystemLockTaskMode(taskId);
6731     }
6732 
6733     /**
6734      * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The
6735      * PackageManager could be unavailable at construction time and therefore needs to be accessed
6736      * on demand.
6737      */
6738     @VisibleForTesting
getPackageManager()6739     public IPackageManager getPackageManager() {
6740         return AppGlobals.getPackageManager();
6741     }
6742 
6743     @VisibleForTesting
getPackageManagerInternal()6744     public PackageManagerInternal getPackageManagerInternal() {
6745         // Intentionally hold no locks: in case of race conditions, the mPackageManagerInt will
6746         // be set to the same value anyway.
6747         if (mPackageManagerInt == null) {
6748             mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
6749         }
6750         return mPackageManagerInt;
6751     }
6752 
getPermissionManagerInternal()6753     private PermissionManagerServiceInternal getPermissionManagerInternal() {
6754         // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will
6755         // be set to the same value anyway.
6756         if (mPermissionManagerInt == null) {
6757             mPermissionManagerInt =
6758                     LocalServices.getService(PermissionManagerServiceInternal.class);
6759         }
6760         return mPermissionManagerInt;
6761     }
6762 
getTestUtilityServiceLocked()6763     private TestUtilityService getTestUtilityServiceLocked() {
6764         if (mTestUtilityService == null) {
6765             mTestUtilityService =
6766                     LocalServices.getService(TestUtilityService.class);
6767         }
6768         return mTestUtilityService;
6769     }
6770 
6771     @Override
appNotResponding(final String reason)6772     public void appNotResponding(final String reason) {
6773         appNotResponding(reason, /*isContinuousAnr*/ false);
6774     }
6775 
appNotResponding(final String reason, boolean isContinuousAnr)6776     public void appNotResponding(final String reason, boolean isContinuousAnr) {
6777         TimeoutRecord timeoutRecord = TimeoutRecord.forApp("App requested: " + reason);
6778         final int callingPid = Binder.getCallingPid();
6779 
6780         timeoutRecord.mLatencyTracker.waitingOnPidLockStarted();
6781         synchronized (mPidsSelfLocked) {
6782             timeoutRecord.mLatencyTracker.waitingOnPidLockEnded();
6783             final ProcessRecord app = mPidsSelfLocked.get(callingPid);
6784             if (app == null) {
6785                 throw new SecurityException("Unknown process: " + callingPid);
6786             }
6787 
6788             mAnrHelper.appNotResponding(app, null, app.info, null, null, false,
6789                     timeoutRecord, isContinuousAnr);
6790         }
6791     }
6792 
appNotResponding(@onNull ProcessRecord anrProcess, @NonNull TimeoutRecord timeoutRecord)6793     void appNotResponding(@NonNull ProcessRecord anrProcess, @NonNull TimeoutRecord timeoutRecord) {
6794         mAnrHelper.appNotResponding(anrProcess, timeoutRecord);
6795     }
6796 
appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)6797     private void appNotResponding(@NonNull String processName, int uid,
6798             @NonNull TimeoutRecord timeoutRecord) {
6799         Objects.requireNonNull(processName);
6800         Objects.requireNonNull(timeoutRecord);
6801 
6802         synchronized (this) {
6803             final ProcessRecord app = getProcessRecordLocked(processName, uid);
6804             if (app == null) {
6805                 Slog.e(TAG, "Unknown process: " + processName);
6806                 return;
6807             }
6808             mAnrHelper.appNotResponding(app, timeoutRecord);
6809         }
6810     }
6811 
startPersistentApps(int matchFlags)6812     void startPersistentApps(int matchFlags) {
6813         if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
6814 
6815         synchronized (this) {
6816             try {
6817                 final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
6818                         .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
6819                 for (ApplicationInfo app : apps) {
6820                     if (!"android".equals(app.packageName)) {
6821                         final ProcessRecord proc = addAppLocked(
6822                                 app, null, false, null /* ABI override */,
6823                                 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
6824                         if (proc != null) {
6825                             proc.mProfile.addHostingComponentType(
6826                                     HOSTING_COMPONENT_TYPE_PERSISTENT);
6827                         }
6828                     }
6829                 }
6830             } catch (RemoteException ex) {
6831             }
6832         }
6833     }
6834 
6835     // =========================================================
6836     // CONTENT PROVIDERS
6837     // =========================================================
6838 
getContentProviderHelper()6839     public ContentProviderHelper getContentProviderHelper() {
6840         return mCpHelper;
6841     }
6842 
6843     @Override
getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)6844     public final ContentProviderHolder getContentProvider(
6845             IApplicationThread caller, String callingPackage, String name, int userId,
6846             boolean stable) {
6847         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProvider: ", name);
6848         try {
6849             return mCpHelper.getContentProvider(caller, callingPackage, name, userId, stable);
6850         } finally {
6851             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6852         }
6853     }
6854 
6855     @Override
getContentProviderExternal( String name, int userId, IBinder token, String tag)6856     public ContentProviderHolder getContentProviderExternal(
6857             String name, int userId, IBinder token, String tag) {
6858         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProviderExternal: ", name);
6859         try {
6860             return mCpHelper.getContentProviderExternal(name, userId, token, tag);
6861         } finally {
6862             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6863         }
6864     }
6865 
6866     /**
6867      * Drop a content provider from a ProcessRecord's bookkeeping
6868      */
6869     @Override
removeContentProvider(IBinder connection, boolean stable)6870     public void removeContentProvider(IBinder connection, boolean stable) {
6871         mCpHelper.removeContentProvider(connection, stable);
6872     }
6873 
6874     /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */
6875     @Deprecated
6876     @Override
removeContentProviderExternal(String name, IBinder token)6877     public void removeContentProviderExternal(String name, IBinder token) {
6878         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternal: ", name);
6879         try {
6880             removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId());
6881         } finally {
6882             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6883         }
6884     }
6885 
6886     @Override
removeContentProviderExternalAsUser(String name, IBinder token, int userId)6887     public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) {
6888         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternalAsUser: ", name);
6889         try {
6890             mCpHelper.removeContentProviderExternalAsUser(name, token, userId);
6891         } finally {
6892             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6893         }
6894     }
6895 
6896     @Override
publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)6897     public final void publishContentProviders(IApplicationThread caller,
6898             List<ContentProviderHolder> providers) {
6899         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
6900             final int maxLength = 256;
6901             final StringBuilder sb = new StringBuilder(maxLength);
6902             sb.append("publishContentProviders: ");
6903             if (providers != null) {
6904                 boolean first = true;
6905                 for (int i = 0, size = providers.size(); i < size; i++) {
6906                     final ContentProviderHolder holder = providers.get(i);
6907                     if (holder != null && holder.info != null && holder.info.authority != null) {
6908                         final int len = holder.info.authority.length();
6909                         if (sb.length() + len > maxLength) {
6910                             sb.append("[[TRUNCATED]]");
6911                             break;
6912                         }
6913                         if (!first) {
6914                             sb.append(';');
6915                         } else {
6916                             first = false;
6917                         }
6918                         sb.append(holder.info.authority);
6919                     }
6920                 }
6921             }
6922             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString());
6923         }
6924         try {
6925             mCpHelper.publishContentProviders(caller, providers);
6926         } finally {
6927             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6928         }
6929     }
6930 
6931     @Override
refContentProvider(IBinder connection, int stable, int unstable)6932     public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6933         return mCpHelper.refContentProvider(connection, stable, unstable);
6934     }
6935 
6936     @Override
unstableProviderDied(IBinder connection)6937     public void unstableProviderDied(IBinder connection) {
6938         mCpHelper.unstableProviderDied(connection);
6939     }
6940 
6941     @Override
appNotRespondingViaProvider(IBinder connection)6942     public void appNotRespondingViaProvider(IBinder connection) {
6943         mCpHelper.appNotRespondingViaProvider(connection);
6944     }
6945 
6946     /**
6947      * Filters calls to getType based on permission. If the caller has required permission,
6948      * then it returns the contentProvider#getType.
6949      * Else, it returns the contentProvider#getTypeAnonymous, which does not
6950      * reveal any internal information which should be protected by any permission.
6951      */
6952     @Override
getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback)6953     public void getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback) {
6954         mCpHelper.getMimeTypeFilterAsync(uri, userId, resultCallback);
6955     }
6956 
6957     // =========================================================
6958     // GLOBAL MANAGEMENT
6959     // =========================================================
6960 
6961     @GuardedBy(anyOf = {"this", "mProcLock"})
uidOnBackgroundAllowlistLOSP(final int uid)6962     private boolean uidOnBackgroundAllowlistLOSP(final int uid) {
6963         final int appId = UserHandle.getAppId(uid);
6964         final int[] allowlist = mBackgroundAppIdAllowlist;
6965         for (int i = 0, len = allowlist.length; i < len; i++) {
6966             if (appId == allowlist[i]) {
6967                 return true;
6968             }
6969         }
6970         return false;
6971     }
6972 
6973     @Override
isBackgroundRestricted(String packageName)6974     public boolean isBackgroundRestricted(String packageName) {
6975         final int callingUid = Binder.getCallingUid();
6976         final IPackageManager pm = AppGlobals.getPackageManager();
6977         try {
6978             final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
6979                     UserHandle.getUserId(callingUid));
6980             if (packageUid != callingUid) {
6981                 throw new IllegalArgumentException("Uid " + callingUid
6982                         + " cannot query restriction state for package " + packageName);
6983             }
6984         } catch (RemoteException exc) {
6985             // Ignore.
6986         }
6987         return isBackgroundRestrictedNoCheck(callingUid, packageName);
6988     }
6989 
6990     @VisibleForTesting
isBackgroundRestrictedNoCheck(final int uid, final String packageName)6991     public boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) {
6992         final int mode = getAppOpsManager().checkOpNoThrow(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
6993                 uid, packageName);
6994         return mode != AppOpsManager.MODE_ALLOWED;
6995     }
6996 
6997     @Override
backgroundAllowlistUid(final int uid)6998     public void backgroundAllowlistUid(final int uid) {
6999         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7000             throw new SecurityException("Only the OS may call backgroundAllowlistUid()");
7001         }
7002 
7003         if (DEBUG_BACKGROUND_CHECK) {
7004             Slog.i(TAG, "Adding uid " + uid + " to bg uid allowlist");
7005         }
7006         synchronized (this) {
7007             synchronized (mProcLock) {
7008                 final int num = mBackgroundAppIdAllowlist.length;
7009                 int[] newList = new int[num + 1];
7010                 System.arraycopy(mBackgroundAppIdAllowlist, 0, newList, 0, num);
7011                 newList[num] = UserHandle.getAppId(uid);
7012                 mBackgroundAppIdAllowlist = newList;
7013             }
7014         }
7015     }
7016 
7017     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)7018     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
7019             String abiOverride, int zygotePolicyFlags) {
7020         return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */,
7021                 abiOverride, zygotePolicyFlags);
7022     }
7023 
7024     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags)7025     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
7026             boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags) {
7027         return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks,
7028                 false /* disableTestApiChecks */, abiOverride, zygotePolicyFlags);
7029     }
7030 
7031     // TODO: Move to ProcessList?
7032     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)7033     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
7034             boolean disableHiddenApiChecks, boolean disableTestApiChecks,
7035             String abiOverride, int zygotePolicyFlags) {
7036         return addAppLocked(
7037                 info,
7038                 customProcess,
7039                 isolated,
7040                 /* isSdkSandbox= */ false,
7041                 /* sdkSandboxUid= */ 0,
7042                 /* sdkSandboxClientAppPackage= */ null,
7043                 disableHiddenApiChecks,
7044                 disableTestApiChecks,
7045                 abiOverride,
7046                 zygotePolicyFlags);
7047     }
7048 
addAppLocked( ApplicationInfo info, String customProcess, boolean isolated, boolean isSdkSandbox, int sdkSandboxUid, @Nullable String sdkSandboxClientAppPackage, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)7049     final ProcessRecord addAppLocked(
7050             ApplicationInfo info,
7051             String customProcess,
7052             boolean isolated,
7053             boolean isSdkSandbox,
7054             int sdkSandboxUid,
7055             @Nullable String sdkSandboxClientAppPackage,
7056             boolean disableHiddenApiChecks,
7057             boolean disableTestApiChecks,
7058             String abiOverride,
7059             int zygotePolicyFlags) {
7060         ProcessRecord app;
7061         if (!isolated) {
7062             app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
7063                     info.uid);
7064         } else {
7065             app = null;
7066         }
7067 
7068         if (app == null) {
7069             app = mProcessList.newProcessRecordLocked(
7070                     info,
7071                     customProcess,
7072                     isolated,
7073                     /* isolatedUid= */0,
7074                     isSdkSandbox,
7075                     sdkSandboxUid,
7076                     sdkSandboxClientAppPackage,
7077                     new HostingRecord(HostingRecord.HOSTING_TYPE_ADDED_APPLICATION,
7078                             customProcess != null ? customProcess : info.processName));
7079             updateLruProcessLocked(app, false, null);
7080             updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN);
7081         }
7082 
7083         // Report usage as process is persistent and being started.
7084         mUsageStatsService.reportEvent(info.packageName, UserHandle.getUserId(app.uid),
7085                 Event.APP_COMPONENT_USED);
7086 
7087         // This package really, really can not be stopped.
7088         // TODO: how set package stopped state should work for sdk sandboxes?
7089         if (!isSdkSandbox) {
7090             try {
7091                 mPackageManagerInt.setPackageStoppedState(
7092                         info.packageName, false, UserHandle.getUserId(app.uid));
7093             } catch (IllegalArgumentException e) {
7094                 Slog.w(TAG, "Failed trying to unstop package "
7095                         + info.packageName + ": " + e);
7096             }
7097         }
7098 
7099         if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
7100             app.setPersistent(true);
7101             app.mState.setMaxAdj(ProcessList.PERSISTENT_PROC_ADJ);
7102         }
7103         if (app.getThread() == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7104             mPersistentStartingProcesses.add(app);
7105             mProcessList.startProcessLocked(app, new HostingRecord(
7106                     HostingRecord.HOSTING_TYPE_ADDED_APPLICATION,
7107                     customProcess != null ? customProcess : app.processName),
7108                     zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks,
7109                     abiOverride);
7110         }
7111 
7112         return app;
7113     }
7114 
unhandledBack()7115     public void unhandledBack() {
7116         mActivityTaskManager.unhandledBack();
7117     }
7118 
7119     // TODO: Replace this method with one that returns a bound IContentProvider.
openContentUri(String uriString)7120     public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException {
7121         enforceNotIsolatedCaller("openContentUri");
7122         final int userId = UserHandle.getCallingUserId();
7123         final Uri uri = Uri.parse(uriString);
7124         String name = uri.getAuthority();
7125         ContentProviderHolder cph = mCpHelper.getContentProviderExternalUnchecked(name, null,
7126                 Binder.getCallingUid(), "*opencontent*", userId);
7127         ParcelFileDescriptor pfd = null;
7128         if (cph != null) {
7129             try {
7130                 // This method is exposed to the VNDK and to avoid changing its
7131                 // signature we just use the first package in the UID. For shared
7132                 // UIDs we may blame the wrong app but that is Okay as they are
7133                 // in the same security/privacy sandbox.
7134                 final int uid = Binder.getCallingUid();
7135                 // Here we handle some of the special UIDs (mediaserver, systemserver, etc)
7136                 final String packageName = AppOpsManager.resolvePackageName(uid,
7137                         /*packageName*/ null);
7138                 final AndroidPackage androidPackage;
7139                 if (packageName != null) {
7140                     androidPackage = mPackageManagerInt.getPackage(packageName);
7141                 } else {
7142                     androidPackage = mPackageManagerInt.getPackage(uid);
7143                 }
7144                 if (androidPackage == null) {
7145                     Log.e(TAG, "Cannot find package for uid: " + uid);
7146                     return null;
7147                 }
7148 
7149                 final ApplicationInfo appInfo = mPackageManagerInt.getApplicationInfo(
7150                         androidPackage.getPackageName(), /*flags*/0, Process.SYSTEM_UID,
7151                         UserHandle.USER_SYSTEM);
7152                 if (!appInfo.isVendor() && !appInfo.isSystemApp() && !appInfo.isSystemExt()
7153                         && !appInfo.isProduct()) {
7154                     Log.e(TAG, "openContentUri may only be used by vendor/system/product.");
7155                     return null;
7156                 }
7157 
7158                 final AttributionSource attributionSource = new AttributionSource(
7159                         Binder.getCallingUid(), androidPackage.getPackageName(), null);
7160                 pfd = cph.provider.openFile(attributionSource, uri, "r", null);
7161             } catch (FileNotFoundException e) {
7162                 // do nothing; pfd will be returned null
7163             } finally {
7164                 // Ensure we're done with the provider.
7165                 mCpHelper.removeContentProviderExternalUnchecked(name, null, userId);
7166             }
7167         } else {
7168             Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
7169         }
7170         return pfd;
7171     }
7172 
reportGlobalUsageEvent(int event)7173     void reportGlobalUsageEvent(int event) {
7174         final int currentUserId = mUserController.getCurrentUserId();
7175         mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, currentUserId, event);
7176         int[] profiles = mUserController.getCurrentProfileIds();
7177         if (profiles != null) {
7178             for (int i = profiles.length - 1; i >= 0; i--) {
7179                 if (profiles[i] == currentUserId) {
7180                     continue;
7181                 }
7182                 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, profiles[i], event);
7183             }
7184         }
7185     }
7186 
reportCurWakefulnessUsageEvent()7187     void reportCurWakefulnessUsageEvent() {
7188         reportGlobalUsageEvent(mWakefulness.get() == PowerManagerInternal.WAKEFULNESS_AWAKE
7189                 ? UsageEvents.Event.SCREEN_INTERACTIVE
7190                 : UsageEvents.Event.SCREEN_NON_INTERACTIVE);
7191     }
7192 
onWakefulnessChanged(int wakefulness)7193     void onWakefulnessChanged(int wakefulness) {
7194         synchronized (this) {
7195             boolean wasAwake = mWakefulness.getAndSet(wakefulness)
7196                     == PowerManagerInternal.WAKEFULNESS_AWAKE;
7197             boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
7198 
7199             if (wasAwake != isAwake) {
7200                 // Also update state in a special way for running foreground services UI.
7201                 mServices.updateScreenStateLocked(isAwake);
7202                 reportCurWakefulnessUsageEvent();
7203                 mActivityTaskManager.onScreenAwakeChanged(isAwake);
7204                 mOomAdjProfiler.onWakefulnessChanged(wakefulness);
7205                 mOomAdjuster.onWakefulnessChanged(wakefulness);
7206 
7207                 updateOomAdjLocked(OOM_ADJ_REASON_UI_VISIBILITY);
7208             }
7209         }
7210     }
7211 
7212     @Override
notifyCleartextNetwork(int uid, byte[] firstPacket)7213     public void notifyCleartextNetwork(int uid, byte[] firstPacket) {
7214         mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget();
7215     }
7216 
7217     @Override
shutdown(int timeout)7218     public boolean shutdown(int timeout) {
7219         if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7220                 != PackageManager.PERMISSION_GRANTED) {
7221             throw new SecurityException("Requires permission "
7222                     + android.Manifest.permission.SHUTDOWN);
7223         }
7224 
7225         final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout);
7226 
7227         mAppOpsService.shutdown();
7228         if (mUsageStatsService != null) {
7229             mUsageStatsService.prepareShutdown();
7230         }
7231         mBatteryStatsService.shutdown();
7232         mProcessStats.shutdown();
7233 
7234         return timedout;
7235     }
7236 
7237     @Override
notifyLockedProfile(@serIdInt int userId)7238     public void notifyLockedProfile(@UserIdInt int userId) {
7239         mAtmInternal.notifyLockedProfile(userId);
7240     }
7241 
7242     @Override
startConfirmDeviceCredentialIntent(Intent intent, Bundle options)7243     public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7244         mAtmInternal.startConfirmDeviceCredentialIntent(intent, options);
7245     }
7246 
7247     @Override
stopAppSwitches()7248     public void stopAppSwitches() {
7249         mActivityTaskManager.stopAppSwitches();
7250     }
7251 
7252     @Override
resumeAppSwitches()7253     public void resumeAppSwitches() {
7254         mActivityTaskManager.resumeAppSwitches();
7255     }
7256 
setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)7257     public void setDebugApp(String packageName, boolean waitForDebugger,
7258             boolean persistent) {
7259         setDebugApp(packageName, waitForDebugger, persistent, false);
7260     }
7261 
setDebugApp(String packageName, boolean waitForDebugger, boolean persistent, boolean suspendUponWait)7262     private void setDebugApp(String packageName, boolean waitForDebugger,
7263             boolean persistent, boolean suspendUponWait) {
7264         enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7265                 "setDebugApp()");
7266 
7267         final long ident = Binder.clearCallingIdentity();
7268         try {
7269             // Note that this is not really thread safe if there are multiple
7270             // callers into it at the same time, but that's not a situation we
7271             // care about.
7272             if (persistent) {
7273                 final ContentResolver resolver = mContext.getContentResolver();
7274                 Settings.Global.putString(
7275                     resolver, Settings.Global.DEBUG_APP,
7276                     packageName);
7277                 Settings.Global.putInt(
7278                     resolver, Settings.Global.WAIT_FOR_DEBUGGER,
7279                     waitForDebugger ? 1 : 0);
7280             }
7281 
7282             synchronized (this) {
7283                 if (!persistent) {
7284                     mOrigDebugApp = mDebugApp;
7285                     mOrigWaitForDebugger = mWaitForDebugger;
7286                 }
7287                 mDebugApp = packageName;
7288                 mWaitForDebugger = waitForDebugger;
7289                 mSuspendUponWait = suspendUponWait;
7290                 mDebugTransient = !persistent;
7291                 if (packageName != null) {
7292                     forceStopPackageLocked(packageName, -1, false, false, true, true,
7293                             false, UserHandle.USER_ALL, "set debug app");
7294                 }
7295             }
7296         } finally {
7297             Binder.restoreCallingIdentity(ident);
7298         }
7299     }
7300 
7301     /**
7302      * Set or remove an agent to be run whenever an app with the given process name starts.
7303      *
7304      * This method will not check whether the given process name matches a debuggable app. That
7305      * would require scanning all current packages, and a rescan when new packages are installed
7306      * or updated.
7307      *
7308      * Instead, do the check when an application is started and matched to a stored agent.
7309      *
7310      * @param packageName the process name of the app.
7311      * @param agent the agent string to be used, or null to remove any previously set agent.
7312      */
7313     @Override
setAgentApp(@onNull String packageName, @Nullable String agent)7314     public void setAgentApp(@NonNull String packageName, @Nullable String agent) {
7315         // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
7316         // its own permission.
7317         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
7318                 != PackageManager.PERMISSION_GRANTED) {
7319             throw new SecurityException(
7320                     "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER);
7321         }
7322 
7323         synchronized (mAppProfiler.mProfilerLock) {
7324             mAppProfiler.setAgentAppLPf(packageName, agent);
7325         }
7326     }
7327 
setTrackAllocationApp(ApplicationInfo app, String processName)7328     void setTrackAllocationApp(ApplicationInfo app, String processName) {
7329         enforceDebuggable(app);
7330 
7331         synchronized (mProcLock) {
7332             mTrackAllocationApp = processName;
7333         }
7334     }
7335 
setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo, ApplicationInfo sdkSandboxClientApp)7336     void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo,
7337             ApplicationInfo sdkSandboxClientApp) {
7338         synchronized (mAppProfiler.mProfilerLock) {
7339             if (!Build.IS_DEBUGGABLE) {
7340                 boolean isAppDebuggable = (app.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7341                 boolean isAppProfileable = app.isProfileableByShell();
7342 
7343                 if (sdkSandboxClientApp != null) {
7344                     isAppDebuggable |=
7345                             (sdkSandboxClientApp.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7346                     isAppProfileable |= sdkSandboxClientApp.isProfileableByShell();
7347                 }
7348                 if (!isAppDebuggable && !isAppProfileable) {
7349                     throw new SecurityException("Process not debuggable, "
7350                             + "and not profileable by shell: " + app.packageName);
7351                 }
7352             }
7353             mAppProfiler.setProfileAppLPf(processName, profilerInfo);
7354         }
7355     }
7356 
setNativeDebuggingAppLocked(ApplicationInfo app, String processName)7357     void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) {
7358         enforceDebuggable(app);
7359         mNativeDebuggingApp = processName;
7360     }
7361 
7362     @Override
setAlwaysFinish(boolean enabled)7363     public void setAlwaysFinish(boolean enabled) {
7364         enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7365                 "setAlwaysFinish()");
7366 
7367         final long ident = Binder.clearCallingIdentity();
7368         try {
7369             Settings.Global.putInt(
7370                     mContext.getContentResolver(),
7371                     Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7372 
7373             synchronized (this) {
7374                 mAlwaysFinishActivities = enabled;
7375             }
7376         } finally {
7377             Binder.restoreCallingIdentity(ident);
7378         }
7379     }
7380 
7381     @Override
setActivityController(IActivityController controller, boolean imAMonkey)7382     public void setActivityController(IActivityController controller, boolean imAMonkey) {
7383         if (controller != null) {
7384             Binder.allowBlocking(controller.asBinder());
7385         }
7386         mActivityTaskManager.setActivityController(controller, imAMonkey);
7387     }
7388 
7389     @Override
setUserIsMonkey(boolean userIsMonkey)7390     public void setUserIsMonkey(boolean userIsMonkey) {
7391         synchronized (mProcLock) {
7392             synchronized (mPidsSelfLocked) {
7393                 final int callingPid = Binder.getCallingPid();
7394                 ProcessRecord proc = mPidsSelfLocked.get(callingPid);
7395                 if (proc == null) {
7396                     throw new SecurityException("Unknown process: " + callingPid);
7397                 }
7398                 if (proc.getActiveInstrumentation() == null
7399                         || proc.getActiveInstrumentation().mUiAutomationConnection == null) {
7400                     throw new SecurityException("Only an instrumentation process "
7401                             + "with a UiAutomation can call setUserIsMonkey");
7402                 }
7403             }
7404             mUserIsMonkey = userIsMonkey;
7405         }
7406     }
7407 
7408     @Override
isUserAMonkey()7409     public boolean isUserAMonkey() {
7410         synchronized (mProcLock) {
7411             // If there is a controller also implies the user is a monkey.
7412             return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey();
7413         }
7414     }
7415 
7416     @Override
requestSystemServerHeapDump()7417     public void requestSystemServerHeapDump() {
7418         if (!Build.IS_DEBUGGABLE) {
7419             Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build");
7420             return;
7421         }
7422         if (Binder.getCallingUid() != SYSTEM_UID) {
7423             // This also intentionally excludes secondary profiles from calling this.
7424             throw new SecurityException(
7425                     "Only the system process is allowed to request a system heap dump");
7426         }
7427         ProcessRecord pr;
7428         synchronized (mPidsSelfLocked) {
7429             pr = mPidsSelfLocked.get(myPid());
7430         }
7431         if (pr == null) {
7432             Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid());
7433             return;
7434         }
7435         synchronized (mAppProfiler.mProfilerLock) {
7436             mAppProfiler.startHeapDumpLPf(pr.mProfile, true);
7437         }
7438     }
7439 
7440     /**
7441      * Takes a bugreport using bug report API ({@code BugreportManager}) with no pre-set
7442      * title and description
7443      */
7444     @Override
requestBugReport(@ugreportParams.BugreportMode int bugreportType)7445     public void requestBugReport(@BugreportParams.BugreportMode int bugreportType) {
7446         requestBugReportWithDescription(null, null, bugreportType, 0L);
7447     }
7448 
7449     /**
7450      * Takes a bugreport using bug report API ({@code BugreportManager}) which gets
7451      * triggered by sending a broadcast to Shell.
7452      */
7453     @Override
requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType)7454     public void requestBugReportWithDescription(@Nullable String shareTitle,
7455             @Nullable String shareDescription, int bugreportType) {
7456         requestBugReportWithDescription(shareTitle, shareDescription, bugreportType, /*nonce*/ 0L);
7457     }
7458 
7459     /**
7460      * Takes a bugreport using bug report API ({@code BugreportManager}) which gets
7461      * triggered by sending a broadcast to Shell.
7462      */
requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType, long nonce)7463     public void requestBugReportWithDescription(@Nullable String shareTitle,
7464             @Nullable String shareDescription, int bugreportType, long nonce) {
7465         String type = null;
7466         switch (bugreportType) {
7467             case BugreportParams.BUGREPORT_MODE_FULL:
7468                 type = "bugreportfull";
7469                 break;
7470             case BugreportParams.BUGREPORT_MODE_INTERACTIVE:
7471                 type = "bugreportplus";
7472                 break;
7473             case BugreportParams.BUGREPORT_MODE_REMOTE:
7474                 type = "bugreportremote";
7475                 break;
7476             case BugreportParams.BUGREPORT_MODE_WEAR:
7477                 type = "bugreportwear";
7478                 break;
7479             case BugreportParams.BUGREPORT_MODE_TELEPHONY:
7480                 type = "bugreporttelephony";
7481                 break;
7482             case BugreportParams.BUGREPORT_MODE_WIFI:
7483                 type = "bugreportwifi";
7484                 break;
7485             default:
7486                 throw new IllegalArgumentException(
7487                     "Provided bugreport type is not correct, value: "
7488                         + bugreportType);
7489         }
7490         // Always log caller, even if it does not have permission to dump.
7491         Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid());
7492         enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
7493 
7494         if (!TextUtils.isEmpty(shareTitle)) {
7495             if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) {
7496                 String errorStr = "shareTitle should be less than "
7497                         + MAX_BUGREPORT_TITLE_SIZE + " characters";
7498                 throw new IllegalArgumentException(errorStr);
7499             }
7500             if (!TextUtils.isEmpty(shareDescription)) {
7501                 if (shareDescription.length() > MAX_BUGREPORT_DESCRIPTION_SIZE) {
7502                     String errorStr = "shareDescription should be less than "
7503                             + MAX_BUGREPORT_DESCRIPTION_SIZE + " characters";
7504                     throw new IllegalArgumentException(errorStr);
7505                 }
7506             }
7507             Slog.d(TAG, "Bugreport notification title " + shareTitle
7508                     + " description " + shareDescription);
7509         }
7510         // Create intent to trigger Bugreport API via Shell
7511         Intent triggerShellBugreport = new Intent();
7512         triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED);
7513         triggerShellBugreport.setPackage(SHELL_APP_PACKAGE);
7514         triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType);
7515         triggerShellBugreport.putExtra(EXTRA_BUGREPORT_NONCE, nonce);
7516         triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
7517         triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
7518         if (shareTitle != null) {
7519             triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle);
7520         }
7521         if (shareDescription != null) {
7522             triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription);
7523         }
7524         final long identity = Binder.clearCallingIdentity();
7525         try {
7526             // Send broadcast to shell to trigger bugreport using Bugreport API
7527             // Always start the shell process on the current user to ensure that
7528             // the foreground user can see all bugreport notifications.
7529             // In case of BUGREPORT_MODE_REMOTE send the broadcast to SYSTEM user as the device
7530             // owner apps are running on the SYSTEM user.
7531             if (bugreportType == BugreportParams.BUGREPORT_MODE_REMOTE) {
7532                 mContext.sendBroadcastAsUser(triggerShellBugreport, UserHandle.SYSTEM);
7533             } else {
7534                 mContext.sendBroadcastAsUser(triggerShellBugreport,
7535                         getCurrentUser().getUserHandle());
7536             }
7537         } finally {
7538             Binder.restoreCallingIdentity(identity);
7539         }
7540     }
7541 
7542     /**
7543      * Takes a telephony bugreport with title and description
7544      */
7545     @Override
requestTelephonyBugReport(String shareTitle, String shareDescription)7546     public void requestTelephonyBugReport(String shareTitle, String shareDescription) {
7547         requestBugReportWithDescription(shareTitle, shareDescription,
7548                 BugreportParams.BUGREPORT_MODE_TELEPHONY);
7549     }
7550 
7551     /**
7552      * Takes a minimal bugreport of Wifi-related state with pre-set title and description
7553      */
7554     @Override
requestWifiBugReport(String shareTitle, String shareDescription)7555     public void requestWifiBugReport(String shareTitle, String shareDescription) {
7556         requestBugReportWithDescription(shareTitle, shareDescription,
7557                 BugreportParams.BUGREPORT_MODE_WIFI);
7558     }
7559 
7560     /**
7561      * Takes an interactive bugreport with a progress notification
7562      */
7563     @Override
requestInteractiveBugReport()7564     public void requestInteractiveBugReport() {
7565         requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE);
7566     }
7567 
7568     /**
7569      * Takes an interactive bugreport with a progress notification. Also, shows the given title and
7570      * description on the final share notification
7571      */
7572     @Override
requestInteractiveBugReportWithDescription(String shareTitle, String shareDescription)7573     public void requestInteractiveBugReportWithDescription(String shareTitle,
7574             String shareDescription) {
7575         requestBugReportWithDescription(shareTitle, shareDescription,
7576                 BugreportParams.BUGREPORT_MODE_INTERACTIVE);
7577     }
7578 
7579     /**
7580      * Takes a bugreport with minimal user interference
7581      */
7582     @Override
requestFullBugReport()7583     public void requestFullBugReport() {
7584         requestBugReportWithDescription(null, null,  BugreportParams.BUGREPORT_MODE_FULL);
7585     }
7586 
7587     /**
7588      * Takes a bugreport remotely
7589      */
7590     @Override
requestRemoteBugReport(long nonce)7591     public void requestRemoteBugReport(long nonce) {
7592         requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE, nonce);
7593     }
7594 
7595     /**
7596      * Launches a bugreport-whitelisted app to handle a bugreport.
7597      *
7598      * <p>Allows a bug report handler app to take bugreports on the user's behalf. The handler can
7599      * be predefined in the config, meant to be launched with the primary user. The user can
7600      * override this with a different (or same) handler app on possibly a different user. This is
7601      * useful for capturing bug reports from work profile, for instance.
7602      *
7603      * @return true if there is a bugreport-whitelisted app to handle a bugreport, or false
7604      * otherwise.
7605      */
7606     @Override
launchBugReportHandlerApp()7607     public boolean launchBugReportHandlerApp() {
7608 
7609         Context currentUserContext = mContext.createContextAsUser(getCurrentUser().getUserHandle(),
7610                 /* flags= */ 0);
7611         if (!BugReportHandlerUtil.isBugReportHandlerEnabled(currentUserContext)) {
7612             return false;
7613         }
7614 
7615         // Always log caller, even if it does not have permission to dump.
7616         Slog.i(TAG, "launchBugReportHandlerApp requested by UID " + Binder.getCallingUid());
7617         enforceCallingPermission(android.Manifest.permission.DUMP,
7618                 "launchBugReportHandlerApp");
7619 
7620         return BugReportHandlerUtil.launchBugReportHandlerApp(currentUserContext);
7621     }
7622 
7623     /**
7624      * Get packages of bugreport-whitelisted apps to handle a bug report.
7625      *
7626      * @return packages of bugreport-whitelisted apps to handle a bug report.
7627      */
7628     @Override
getBugreportWhitelistedPackages()7629     public List<String> getBugreportWhitelistedPackages() {
7630         enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING,
7631                 "getBugreportWhitelistedPackages");
7632         return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages());
7633     }
7634 
registerProcessObserver(IProcessObserver observer)7635     public void registerProcessObserver(IProcessObserver observer) {
7636         enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7637                 "registerProcessObserver()");
7638         mProcessList.registerProcessObserver(observer);
7639     }
7640 
7641     @Override
unregisterProcessObserver(IProcessObserver observer)7642     public void unregisterProcessObserver(IProcessObserver observer) {
7643         mProcessList.unregisterProcessObserver(observer);
7644     }
7645 
7646     @Override
getUidProcessState(int uid, String callingPackage)7647     public int getUidProcessState(int uid, String callingPackage) {
7648         if (!hasUsageStatsPermission(callingPackage)) {
7649             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7650                     "getUidProcessState");
7651         }
7652         // In case the caller is requesting processState of an app in a different user,
7653         // then verify the caller has INTERACT_ACROSS_USERS_FULL permission
7654         mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
7655                 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY,
7656                 "getUidProcessState", callingPackage); // Ignore return value
7657 
7658         synchronized (mProcLock) {
7659             if (mPendingStartActivityUids.isPendingTopUid(uid)) {
7660                 return PROCESS_STATE_TOP;
7661             }
7662             return mProcessList.getUidProcStateLOSP(uid);
7663         }
7664     }
7665 
7666     @Override
getUidProcessCapabilities(int uid, String callingPackage)7667     public @ProcessCapability int getUidProcessCapabilities(int uid, String callingPackage) {
7668         if (!hasUsageStatsPermission(callingPackage)) {
7669             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7670                     "getUidProcessState");
7671         }
7672         // In case the caller is requesting processCapabilities of an app in a different user,
7673         // then verify the caller has INTERACT_ACROSS_USERS_FULL permission
7674         mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
7675                 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY,
7676                 "getUidProcessCapabilities", callingPackage); // Ignore return value
7677 
7678         synchronized (mProcLock) {
7679             return mProcessList.getUidProcessCapabilityLOSP(uid);
7680         }
7681     }
7682 
7683     @Override
registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)7684     public void registerUidObserver(IUidObserver observer, int which, int cutpoint,
7685             String callingPackage) {
7686         if (!hasUsageStatsPermission(callingPackage)) {
7687             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7688                     "registerUidObserver");
7689         }
7690         mUidObserverController.register(observer, which, cutpoint, callingPackage,
7691                 Binder.getCallingUid(), /*uids*/null);
7692     }
7693 
7694     /**
7695      * Registers a UidObserver with a uid filter.
7696      *
7697      * @param observer The UidObserver implementation to register.
7698      * @param which    A bitmask of events to observe. See ActivityManager.UID_OBSERVER_*.
7699      * @param cutpoint The cutpoint for onUidStateChanged events. When the state crosses this
7700      *                 threshold in either direction, onUidStateChanged will be called.
7701      * @param callingPackage The name of the calling package.
7702      * @param uids     A list of uids to watch. If all uids are to be watched, use
7703      *                 registerUidObserver instead.
7704      * @throws RemoteException
7705      * @return Returns A binder token identifying the UidObserver registration.
7706      */
7707     @Override
registerUidObserverForUids(IUidObserver observer, int which, int cutpoint, String callingPackage, int[] uids)7708     public IBinder registerUidObserverForUids(IUidObserver observer, int which, int cutpoint,
7709             String callingPackage, int[] uids) {
7710         if (!hasUsageStatsPermission(callingPackage)) {
7711             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7712                     "registerUidObserver");
7713         }
7714         return mUidObserverController.register(observer, which, cutpoint, callingPackage,
7715                 Binder.getCallingUid(), uids);
7716     }
7717 
7718     @Override
unregisterUidObserver(IUidObserver observer)7719     public void unregisterUidObserver(IUidObserver observer) {
7720         mUidObserverController.unregister(observer);
7721     }
7722 
7723     /**
7724      * Adds a uid to the list of uids that a UidObserver will receive updates about.
7725      *
7726      * @param observerToken  The binder token identifying the UidObserver registration.
7727      * @param callingPackage The name of the calling package.
7728      * @param uid            The uid to watch.
7729      * @throws RemoteException
7730      */
7731     @Override
addUidToObserver(IBinder observerToken, String callingPackage, int uid)7732     public void addUidToObserver(IBinder observerToken, String callingPackage, int uid) {
7733         if (!hasUsageStatsPermission(callingPackage)) {
7734             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7735                     "registerUidObserver");
7736         }
7737         mUidObserverController.addUidToObserver(observerToken, uid);
7738     }
7739 
7740     /**
7741      * Removes a uid from the list of uids that a UidObserver will receive updates about.
7742      *
7743      * @param observerToken  The binder token identifying the UidObserver registration.
7744      * @param callingPackage The name of the calling package.
7745      * @param uid            The uid to stop watching.
7746      * @throws RemoteException
7747      */
7748     @Override
removeUidFromObserver(IBinder observerToken, String callingPackage, int uid)7749     public void removeUidFromObserver(IBinder observerToken, String callingPackage, int uid) {
7750         if (!hasUsageStatsPermission(callingPackage)) {
7751             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7752                     "registerUidObserver");
7753         }
7754         mUidObserverController.removeUidFromObserver(observerToken, uid);
7755     }
7756 
7757     @Override
isUidActive(int uid, String callingPackage)7758     public boolean isUidActive(int uid, String callingPackage) {
7759         if (!hasUsageStatsPermission(callingPackage)) {
7760             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7761                     "isUidActive");
7762         }
7763         synchronized (mProcLock) {
7764             if (isUidActiveLOSP(uid)) {
7765                 return true;
7766             }
7767         }
7768         return mInternal.isPendingTopUid(uid);
7769     }
7770 
7771     @GuardedBy(anyOf = {"this", "mProcLock"})
isUidActiveLOSP(int uid)7772     boolean isUidActiveLOSP(int uid) {
7773         final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
7774         return uidRecord != null && !uidRecord.isSetIdle();
7775     }
7776 
7777     @GuardedBy("mUidFrozenStateChangedCallbackList")
7778     private final RemoteCallbackList<IUidFrozenStateChangedCallback>
7779             mUidFrozenStateChangedCallbackList = new RemoteCallbackList<>();
7780 
7781     /**
7782      * Register a {@link IUidFrozenStateChangedCallback} to receive Uid frozen state events.
7783      *
7784      * @param callback remote callback object to be registered
7785      */
7786     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
7787     @Override
registerUidFrozenStateChangedCallback( @onNull IUidFrozenStateChangedCallback callback)7788     public void registerUidFrozenStateChangedCallback(
7789             @NonNull IUidFrozenStateChangedCallback callback) {
7790         Preconditions.checkNotNull(callback, "callback cannot be null");
7791         enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7792                 "registerUidFrozenStateChangedCallback()");
7793         synchronized (mUidFrozenStateChangedCallbackList) {
7794             final boolean registered = mUidFrozenStateChangedCallbackList.register(callback);
7795             if (!registered) {
7796                 Slog.w(TAG, "Failed to register with RemoteCallbackList!");
7797             }
7798         }
7799     }
7800 
7801     /**
7802      * Unregister a {@link IUidFrozenStateChangedCallback}.
7803      *
7804      * @param callback remote callback object to be unregistered
7805      */
7806     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
7807     @Override
unregisterUidFrozenStateChangedCallback( @onNull IUidFrozenStateChangedCallback callback)7808     public void unregisterUidFrozenStateChangedCallback(
7809             @NonNull IUidFrozenStateChangedCallback callback) {
7810         Preconditions.checkNotNull(callback, "callback cannot be null");
7811         enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7812                 "unregisterUidFrozenStateChangedCallback()");
7813         synchronized (mUidFrozenStateChangedCallbackList) {
7814             mUidFrozenStateChangedCallbackList.unregister(callback);
7815         }
7816     }
7817 
7818     /**
7819      * Query the frozen state of a list of UIDs.
7820      *
7821      * @param uids the array of UIDs which the client would like to know the frozen state of.
7822      * @return An array containing the frozen state for each requested UID, by index. Will be set
7823      *               to {@link UidFrozenStateChangedCallback#UID_FROZEN_STATE_FROZEN}
7824      *               if the UID is frozen. If the UID is not frozen or not found,
7825      *               {@link UidFrozenStateChangedCallback#UID_FROZEN_STATE_UNFROZEN}
7826      *               will be set.
7827      *
7828      * @hide
7829      */
7830     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
7831     @Override
getUidFrozenState(@onNull int[] uids)7832     public @NonNull int[] getUidFrozenState(@NonNull int[] uids) {
7833         Preconditions.checkNotNull(uids, "uid array cannot be null");
7834         enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7835                 "getUidFrozenState()");
7836 
7837         final int[] frozenStates = new int[uids.length];
7838         synchronized (mProcLock) {
7839             for (int i = 0; i < uids.length; i++) {
7840                 final UidRecord uidRec = mProcessList.mActiveUids.get(uids[i]);
7841                 if (uidRec != null && uidRec.areAllProcessesFrozen()) {
7842                     frozenStates[i] = UID_FROZEN_STATE_FROZEN;
7843                 } else {
7844                     frozenStates[i] = UID_FROZEN_STATE_UNFROZEN;
7845                 }
7846             }
7847         }
7848         return frozenStates;
7849     }
7850 
7851     /**
7852      * Notify the system that a UID has been frozen or unfrozen.
7853      *
7854      * @param uids The Uid(s) in question
7855      * @param frozenStates Frozen state for each UID index
7856      *
7857      * @hide
7858      */
reportUidFrozenStateChanged(@onNull int[] uids, @UidFrozenState int[] frozenStates)7859     public void reportUidFrozenStateChanged(@NonNull int[] uids,
7860             @UidFrozenState int[] frozenStates) {
7861         synchronized (mUidFrozenStateChangedCallbackList) {
7862             final int n = mUidFrozenStateChangedCallbackList.beginBroadcast();
7863             for (int i = 0; i < n; i++) {
7864                 try {
7865                     mUidFrozenStateChangedCallbackList.getBroadcastItem(i).onUidFrozenStateChanged(
7866                             uids, frozenStates);
7867                 } catch (RemoteException e) {
7868                     /*
7869                     * The process at the other end has died or otherwise gone away.
7870                     * According to spec, RemoteCallbacklist will take care of unregistering any
7871                     * object associated with that process - we are safe to ignore the exception
7872                     * here.
7873                     */
7874                 }
7875             }
7876             mUidFrozenStateChangedCallbackList.finishBroadcast();
7877         }
7878     }
7879 
7880     @Override
setPersistentVrThread(int tid)7881     public void setPersistentVrThread(int tid) {
7882         mActivityTaskManager.setPersistentVrThread(tid);
7883     }
7884 
7885     /**
7886      * Schedule the given thread a normal scheduling priority.
7887      *
7888      * @param tid the tid of the thread to adjust the scheduling of.
7889      * @param suppressLogs {@code true} if any error logging should be disabled.
7890      *
7891      * @return {@code true} if this succeeded.
7892      */
scheduleAsRegularPriority(int tid, boolean suppressLogs)7893     public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
7894         try {
7895             Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
7896             return true;
7897         } catch (IllegalArgumentException e) {
7898             if (!suppressLogs) {
7899                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
7900             }
7901         } catch (SecurityException e) {
7902             if (!suppressLogs) {
7903                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
7904             }
7905         }
7906         return false;
7907     }
7908 
7909     /**
7910      * Schedule the given thread an FIFO scheduling priority.
7911      *
7912      * @param tid the tid of the thread to adjust the scheduling of.
7913      * @param suppressLogs {@code true} if any error logging should be disabled.
7914      *
7915      * @return {@code true} if this succeeded.
7916      */
scheduleAsFifoPriority(int tid, boolean suppressLogs)7917     public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
7918         try {
7919             Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
7920             return true;
7921         } catch (IllegalArgumentException e) {
7922             if (!suppressLogs) {
7923                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
7924             }
7925         } catch (SecurityException e) {
7926             if (!suppressLogs) {
7927                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
7928             }
7929         }
7930         return false;
7931     }
7932 
7933     @Override
setRenderThread(int tid)7934     public void setRenderThread(int tid) {
7935         synchronized (mProcLock) {
7936             ProcessRecord proc;
7937             int pid = Binder.getCallingPid();
7938             if (pid == Process.myPid()) {
7939                 demoteSystemServerRenderThread(tid);
7940                 return;
7941             }
7942             synchronized (mPidsSelfLocked) {
7943                 proc = mPidsSelfLocked.get(pid);
7944             }
7945             if (proc != null && proc.getRenderThreadTid() == 0 && tid > 0) {
7946                 // ensure the tid belongs to the process
7947                 if (!isThreadInProcess(pid, tid)) {
7948                     throw new IllegalArgumentException(
7949                             "Render thread does not belong to process");
7950                 }
7951                 proc.setRenderThreadTid(tid);
7952                 if (DEBUG_OOM_ADJ) {
7953                     Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid);
7954                 }
7955                 // promote to FIFO now
7956                 if (proc.mState.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) {
7957                     if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band");
7958                     if (mUseFifoUiScheduling) {
7959                         setThreadScheduler(proc.getRenderThreadTid(),
7960                                 SCHED_FIFO | SCHED_RESET_ON_FORK, 1);
7961                     } else {
7962                         setThreadPriority(proc.getRenderThreadTid(), THREAD_PRIORITY_TOP_APP_BOOST);
7963                     }
7964                 }
7965             } else {
7966                 if (DEBUG_OOM_ADJ) {
7967                     Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? "
7968                             + "PID: " + pid + ", TID: " + tid + " FIFO: " + mUseFifoUiScheduling);
7969                 }
7970             }
7971         }
7972     }
7973 
7974     /**
7975      * We only use RenderThread in system_server to store task snapshots to the disk, which should
7976      * happen in the background. Thus, demote render thread from system_server to a lower priority.
7977      *
7978      * @param tid the tid of the RenderThread
7979      */
demoteSystemServerRenderThread(int tid)7980     private void demoteSystemServerRenderThread(int tid) {
7981         setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND);
7982     }
7983 
7984     @Override
isVrModePackageEnabled(ComponentName packageName)7985     public boolean isVrModePackageEnabled(ComponentName packageName) {
7986         mActivityTaskManager.enforceSystemHasVrFeature();
7987 
7988         final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
7989 
7990         return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) ==
7991                 VrManagerInternal.NO_ERROR;
7992     }
7993 
isTopActivityImmersive()7994     public boolean isTopActivityImmersive() {
7995         return mActivityTaskManager.isTopActivityImmersive();
7996     }
7997 
7998     @Override
isTopOfTask(IBinder token)7999     public boolean isTopOfTask(IBinder token) {
8000         return ActivityClient.getInstance().isTopOfTask(token);
8001     }
8002 
8003     @Override
setHasTopUi(boolean hasTopUi)8004     public void setHasTopUi(boolean hasTopUi) throws RemoteException {
8005         if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) {
8006             String msg = "Permission Denial: setHasTopUi() from pid="
8007                     + Binder.getCallingPid()
8008                     + ", uid=" + Binder.getCallingUid()
8009                     + " requires " + permission.INTERNAL_SYSTEM_WINDOW;
8010             Slog.w(TAG, msg);
8011             throw new SecurityException(msg);
8012         }
8013         final int pid = Binder.getCallingPid();
8014         final long origId = Binder.clearCallingIdentity();
8015         try {
8016             synchronized (this) {
8017                 boolean changed = false;
8018                 ProcessRecord pr;
8019                 synchronized (mPidsSelfLocked) {
8020                     pr = mPidsSelfLocked.get(pid);
8021                     if (pr == null) {
8022                         Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid);
8023                         return;
8024                     }
8025                     if (pr.mState.hasTopUi() != hasTopUi) {
8026                         if (DEBUG_OOM_ADJ) {
8027                             Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid);
8028                         }
8029                         pr.mState.setHasTopUi(hasTopUi);
8030                         changed = true;
8031                     }
8032                 }
8033                 if (changed) {
8034                     updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY);
8035                 }
8036             }
8037         } finally {
8038             Binder.restoreCallingIdentity(origId);
8039         }
8040     }
8041 
enterSafeMode()8042     public final void enterSafeMode() {
8043         synchronized(this) {
8044             // It only makes sense to do this before the system is ready
8045             // and started launching other packages.
8046             if (!mSystemReady) {
8047                 try {
8048                     AppGlobals.getPackageManager().enterSafeMode();
8049                 } catch (RemoteException e) {
8050                 }
8051             }
8052 
8053             mSafeMode = true;
8054         }
8055     }
8056 
showSafeModeOverlay()8057     public final void showSafeModeOverlay() {
8058         View v = LayoutInflater.from(mContext).inflate(
8059                 com.android.internal.R.layout.safe_mode, null);
8060         WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
8061         lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
8062         lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
8063         lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
8064         lp.gravity = Gravity.BOTTOM | Gravity.START;
8065         lp.format = v.getBackground().getOpacity();
8066         lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
8067                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
8068         lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
8069         ((WindowManager)mContext.getSystemService(
8070                 Context.WINDOW_SERVICE)).addView(v, lp);
8071     }
8072 
8073     @Override
noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)8074     public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid,
8075             String sourcePkg, String tag) {
8076         if (workSource != null && workSource.isEmpty()) {
8077             workSource = null;
8078         }
8079 
8080         if (sourceUid <= 0 && workSource == null) {
8081             // Try and derive a UID to attribute things to based on the caller.
8082             if (sender != null) {
8083                 if (!(sender instanceof PendingIntentRecord)) {
8084                     return;
8085                 }
8086 
8087                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8088                 final int callerUid = Binder.getCallingUid();
8089                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8090             } else {
8091                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8092                 // haven't been able to derive a UID to attribute things to.
8093                 return;
8094             }
8095         }
8096 
8097         int standbyBucket = 0;
8098 
8099         mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag);
8100         if (workSource != null) {
8101             String workSourcePackage = workSource.getPackageName(0);
8102             int workSourceUid = workSource.getAttributionUid();
8103             if (workSourcePackage == null) {
8104                 workSourcePackage = sourcePkg;
8105                 workSourceUid = sourceUid;
8106             }
8107 
8108             if (mUsageStatsService != null) {
8109                 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage,
8110                         UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime());
8111             }
8112 
8113             FrameworkStatsLog.write(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag,
8114                     sourcePkg, standbyBucket);
8115             if (DEBUG_POWER) {
8116                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
8117                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
8118                         + standbyBucket + " wsName=" + workSourcePackage + ")]");
8119             }
8120         } else {
8121             if (mUsageStatsService != null) {
8122                 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg,
8123                         UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime());
8124             }
8125             FrameworkStatsLog.write_non_chained(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, sourceUid,
8126                     null, tag, sourcePkg, standbyBucket);
8127             if (DEBUG_POWER) {
8128                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
8129                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
8130                         + standbyBucket + "]");
8131             }
8132         }
8133 
8134     }
8135 
8136     @Override
noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8137     public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid,
8138             String tag) {
8139         if (workSource != null && workSource.isEmpty()) {
8140             workSource = null;
8141         }
8142 
8143         if (sourceUid <= 0 && workSource == null) {
8144             // Try and derive a UID to attribute things to based on the caller.
8145             if (sender != null) {
8146                 if (!(sender instanceof PendingIntentRecord)) {
8147                     return;
8148                 }
8149 
8150                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8151                 final int callerUid = Binder.getCallingUid();
8152                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8153             } else {
8154                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8155                 // haven't been able to derive a UID to attribute things to.
8156                 return;
8157             }
8158         }
8159 
8160         if (DEBUG_POWER) {
8161             Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource +
8162                     ", tag=" + tag + "]");
8163         }
8164 
8165         mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid);
8166     }
8167 
8168     @Override
noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8169     public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid,
8170             String tag) {
8171         if (workSource != null && workSource.isEmpty()) {
8172             workSource = null;
8173         }
8174 
8175         if (sourceUid <= 0 && workSource == null) {
8176             // Try and derive a UID to attribute things to based on the caller.
8177             if (sender != null) {
8178                 if (!(sender instanceof PendingIntentRecord)) {
8179                     return;
8180                 }
8181 
8182                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8183                 final int callerUid = Binder.getCallingUid();
8184                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8185             } else {
8186                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8187                 // haven't been able to derive a UID to attribute things to.
8188                 return;
8189             }
8190         }
8191 
8192         if (DEBUG_POWER) {
8193             Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource +
8194                     ", tag=" + tag + "]");
8195         }
8196 
8197         mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid);
8198     }
8199 
killPids(int[] pids, String pReason, boolean secure)8200     public boolean killPids(int[] pids, String pReason, boolean secure) {
8201         if (Binder.getCallingUid() != SYSTEM_UID) {
8202             throw new SecurityException("killPids only available to the system");
8203         }
8204         final String reason = (pReason == null) ? "Unknown" : pReason;
8205         // XXX Note: don't acquire main activity lock here, because the window
8206         // manager calls in with its locks held.
8207 
8208         boolean killed = false;
8209         final ArrayList<ProcessRecord> killCandidates = new ArrayList<>();
8210         synchronized (mPidsSelfLocked) {
8211             int worstType = 0;
8212             for (int i = 0; i < pids.length; i++) {
8213                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8214                 if (proc != null) {
8215                     int type = proc.mState.getSetAdj();
8216                     if (type > worstType) {
8217                         worstType = type;
8218                     }
8219                 }
8220             }
8221 
8222             // If the worst oom_adj is somewhere in the cached proc LRU range,
8223             // then constrain it so we will kill all cached procs.
8224             if (worstType < ProcessList.CACHED_APP_MAX_ADJ
8225                     && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
8226                 worstType = ProcessList.CACHED_APP_MIN_ADJ;
8227             }
8228 
8229             // If this is not a secure call, don't let it kill processes that
8230             // are important.
8231             if (!secure && worstType < ProcessList.SERVICE_ADJ) {
8232                 worstType = ProcessList.SERVICE_ADJ;
8233             }
8234 
8235             Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
8236             for (int i = 0; i < pids.length; i++) {
8237                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8238                 if (proc == null) {
8239                     continue;
8240                 }
8241                 int adj = proc.mState.getSetAdj();
8242                 if (adj >= worstType && !proc.isKilledByAm()) {
8243                     killCandidates.add(proc);
8244                     killed = true;
8245                 }
8246             }
8247         }
8248         if (!killCandidates.isEmpty()) {
8249             mHandler.post(() -> {
8250                 synchronized (ActivityManagerService.this) {
8251                     for (int i = 0, size = killCandidates.size(); i < size; i++) {
8252                         killCandidates.get(i).killLocked(reason,
8253                                 ApplicationExitInfo.REASON_OTHER,
8254                                 ApplicationExitInfo.SUBREASON_KILL_PID, true);
8255                     }
8256                 }
8257             });
8258         }
8259         return killed;
8260     }
8261 
8262     @Override
killUid(int appId, int userId, String reason)8263     public void killUid(int appId, int userId, String reason) {
8264         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
8265         synchronized (this) {
8266             final long identity = Binder.clearCallingIdentity();
8267             try {
8268                 synchronized (mProcLock) {
8269                     mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId,
8270                             ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
8271                             true /* callerWillRestart */, true /* doit */,
8272                             true /* evenPersistent */, false /* setRemoved */,
8273                             false /* uninstalling */,
8274                             ApplicationExitInfo.REASON_OTHER,
8275                             ApplicationExitInfo.SUBREASON_KILL_UID,
8276                             reason != null ? reason : "kill uid");
8277                 }
8278             } finally {
8279                 Binder.restoreCallingIdentity(identity);
8280             }
8281         }
8282     }
8283 
8284     @Override
killUidForPermissionChange(int appId, int userId, String reason)8285     public void killUidForPermissionChange(int appId, int userId, String reason) {
8286         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
8287         synchronized (this) {
8288             final long identity = Binder.clearCallingIdentity();
8289             try {
8290                 synchronized (mProcLock) {
8291                     mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId,
8292                             ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
8293                             true /* callerWillRestart */, true /* doit */,
8294                             true /* evenPersistent */, false /* setRemoved */,
8295                             false /* uninstalling */,
8296                             ApplicationExitInfo.REASON_PERMISSION_CHANGE,
8297                             ApplicationExitInfo.SUBREASON_UNKNOWN,
8298                             reason != null ? reason : "kill uid");
8299                 }
8300             } finally {
8301                 Binder.restoreCallingIdentity(identity);
8302             }
8303         }
8304     }
8305 
8306     @Override
killProcessesBelowForeground(String reason)8307     public boolean killProcessesBelowForeground(String reason) {
8308         if (Binder.getCallingUid() != SYSTEM_UID) {
8309             throw new SecurityException("killProcessesBelowForeground() only available to system");
8310         }
8311 
8312         return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
8313     }
8314 
killProcessesBelowAdj(int belowAdj, String reason)8315     private boolean killProcessesBelowAdj(int belowAdj, String reason) {
8316         if (Binder.getCallingUid() != SYSTEM_UID) {
8317             throw new SecurityException("killProcessesBelowAdj() only available to system");
8318         }
8319 
8320         boolean killed = false;
8321         synchronized (this) {
8322             synchronized (mProcLock) {
8323                 synchronized (mPidsSelfLocked) {
8324                     final int size = mPidsSelfLocked.size();
8325                     for (int i = 0; i < size; i++) {
8326                         final int pid = mPidsSelfLocked.keyAt(i);
8327                         final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8328                         if (proc == null) continue;
8329 
8330                         final int adj = proc.mState.getSetAdj();
8331                         if (adj > belowAdj && !proc.isKilledByAm()) {
8332                             proc.killLocked(reason, ApplicationExitInfo.REASON_PERMISSION_CHANGE,
8333                                     true);
8334                             killed = true;
8335                         }
8336                     }
8337                 }
8338             }
8339         }
8340         return killed;
8341     }
8342 
8343     /**
8344      * Similar to {@link #killPids} but killing will be delayed until the device is idle
8345      * and the given process is imperceptible.
8346      */
8347     @Override
killProcessesWhenImperceptible(int[] pids, String reason)8348     public void killProcessesWhenImperceptible(int[] pids, String reason) {
8349         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
8350                 != PackageManager.PERMISSION_GRANTED) {
8351             throw new SecurityException("Requires permission "
8352                     + android.Manifest.permission.FORCE_STOP_PACKAGES);
8353         }
8354         int callerUid = Binder.getCallingUid();
8355         final long iden = Binder.clearCallingIdentity();
8356         try {
8357             mProcessList.killProcessesWhenImperceptible(pids, reason, callerUid);
8358         } finally {
8359             Binder.restoreCallingIdentity(iden);
8360         }
8361     }
8362 
8363     @Override
hang(final IBinder who, boolean allowRestart)8364     public void hang(final IBinder who, boolean allowRestart) {
8365         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8366                 != PackageManager.PERMISSION_GRANTED) {
8367             throw new SecurityException("Requires permission "
8368                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8369         }
8370 
8371         final IBinder.DeathRecipient death = new DeathRecipient() {
8372             @Override
8373             public void binderDied() {
8374                 synchronized (this) {
8375                     notifyAll();
8376                 }
8377             }
8378         };
8379 
8380         try {
8381             who.linkToDeath(death, 0);
8382         } catch (RemoteException e) {
8383             Slog.w(TAG, "hang: given caller IBinder is already dead.");
8384             return;
8385         }
8386 
8387         synchronized (this) {
8388             Watchdog.getInstance().setAllowRestart(allowRestart);
8389             Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
8390             synchronized (death) {
8391                 while (who.isBinderAlive()) {
8392                     try {
8393                         death.wait();
8394                     } catch (InterruptedException e) {
8395                     }
8396                 }
8397             }
8398             Watchdog.getInstance().setAllowRestart(true);
8399         }
8400     }
8401 
8402     @Override
restart()8403     public void restart() {
8404         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8405                 != PackageManager.PERMISSION_GRANTED) {
8406             throw new SecurityException("Requires permission "
8407                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8408         }
8409 
8410         Log.i(TAG, "Sending shutdown broadcast...");
8411 
8412         BroadcastReceiver br = new BroadcastReceiver() {
8413             @Override public void onReceive(Context context, Intent intent) {
8414                 // Now the broadcast is done, finish up the low-level shutdown.
8415                 Log.i(TAG, "Shutting down activity manager...");
8416                 shutdown(10000);
8417                 Log.i(TAG, "Shutdown complete, restarting!");
8418                 killProcess(myPid());
8419                 System.exit(10);
8420             }
8421         };
8422 
8423         // First send the high-level shut down broadcast.
8424         Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
8425         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8426         intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
8427         /* For now we are not doing a clean shutdown, because things seem to get unhappy.
8428         mContext.sendOrderedBroadcastAsUser(intent,
8429                 UserHandle.ALL, null, br, mHandler, 0, null, null);
8430         */
8431         br.onReceive(mContext, intent);
8432     }
8433 
8434     @Override
performIdleMaintenance()8435     public void performIdleMaintenance() {
8436         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8437                 != PackageManager.PERMISSION_GRANTED) {
8438             throw new SecurityException("Requires permission "
8439                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8440         }
8441 
8442         synchronized (mProcLock) {
8443             final long now = SystemClock.uptimeMillis();
8444             final long timeSinceLastIdle = now - mLastIdleTime;
8445 
8446             // Compact all non-zygote processes to freshen up the page cache.
8447             mOomAdjuster.mCachedAppOptimizer.compactAllSystem();
8448 
8449             final long lowRamSinceLastIdle = mAppProfiler.getLowRamTimeSinceIdleLPr(now);
8450             mLastIdleTime = now;
8451             mAppProfiler.updateLowRamTimestampLPr(now);
8452 
8453             StringBuilder sb = new StringBuilder(128);
8454             sb.append("Idle maintenance over ");
8455             TimeUtils.formatDuration(timeSinceLastIdle, sb);
8456             sb.append(" low RAM for ");
8457             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
8458             Slog.i(TAG, sb.toString());
8459 
8460             // If at least 1/3 of our time since the last idle period has been spent
8461             // with RAM low, then we want to kill processes.
8462             boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
8463             // If the processes' memory has increased by more than 1% of the total memory,
8464             // or 10 MB, whichever is greater, then the processes' are eligible to be killed.
8465             final long totalMemoryInKb = getTotalMemory() / 1000;
8466             final long memoryGrowthThreshold =
8467                     Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD);
8468             mProcessList.forEachLruProcessesLOSP(false, proc -> {
8469                 if (proc.getThread() == null) {
8470                     return;
8471                 }
8472                 final ProcessProfileRecord pr = proc.mProfile;
8473                 final ProcessStateRecord state = proc.mState;
8474                 final int setProcState = state.getSetProcState();
8475                 if (state.isNotCachedSinceIdle()) {
8476                     if (setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
8477                             && setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
8478                         final long initialIdlePss, lastPss, lastSwapPss;
8479                         synchronized (mAppProfiler.mProfilerLock) {
8480                             initialIdlePss = pr.getInitialIdlePss();
8481                             lastPss = pr.getLastPss();
8482                             lastSwapPss = pr.getLastSwapPss();
8483                         }
8484                         if (doKilling && initialIdlePss != 0
8485                                 && lastPss > (initialIdlePss * 3 / 2)
8486                                 && lastPss > (initialIdlePss + memoryGrowthThreshold)) {
8487                             final StringBuilder sb2 = new StringBuilder(128);
8488                             sb2.append("Kill");
8489                             sb2.append(proc.processName);
8490                             sb2.append(" in idle maint: pss=");
8491                             sb2.append(lastPss);
8492                             sb2.append(", swapPss=");
8493                             sb2.append(lastSwapPss);
8494                             sb2.append(", initialPss=");
8495                             sb2.append(initialIdlePss);
8496                             sb2.append(", period=");
8497                             TimeUtils.formatDuration(timeSinceLastIdle, sb2);
8498                             sb2.append(", lowRamPeriod=");
8499                             TimeUtils.formatDuration(lowRamSinceLastIdle, sb2);
8500                             Slog.wtfQuiet(TAG, sb2.toString());
8501                             mHandler.post(() -> {
8502                                 synchronized (ActivityManagerService.this) {
8503                                     proc.killLocked("idle maint (pss " + lastPss
8504                                             + " from " + initialIdlePss + ")",
8505                                             ApplicationExitInfo.REASON_OTHER,
8506                                             ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE,
8507                                             true);
8508                                 }
8509                             });
8510                         }
8511                     }
8512                 } else if (setProcState < ActivityManager.PROCESS_STATE_HOME
8513                         && setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) {
8514                     state.setNotCachedSinceIdle(true);
8515                     synchronized (mAppProfiler.mProfilerLock) {
8516                         pr.setInitialIdlePss(0);
8517                         mAppProfiler.updateNextPssTimeLPf(
8518                                 state.getSetProcState(), proc.mProfile, now, true);
8519                     }
8520                 }
8521             });
8522         }
8523     }
8524 
8525     @Override
sendIdleJobTrigger()8526     public void sendIdleJobTrigger() {
8527         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8528                 != PackageManager.PERMISSION_GRANTED) {
8529             throw new SecurityException("Requires permission "
8530                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8531         }
8532 
8533         final long ident = Binder.clearCallingIdentity();
8534         try {
8535             Intent intent = new Intent(ACTION_TRIGGER_IDLE)
8536                     .setPackage("android")
8537                     .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8538             broadcastIntent(null, intent, null, null, 0, null, null, null,
8539                     OP_NONE, null, false, false, UserHandle.USER_ALL);
8540         } finally {
8541             Binder.restoreCallingIdentity(ident);
8542         }
8543     }
8544 
retrieveSettings()8545     private void retrieveSettings() {
8546         final ContentResolver resolver = mContext.getContentResolver();
8547         mActivityTaskManager.retrieveSettings(resolver);
8548 
8549         final String debugApp = Settings.Global.getString(resolver, DEBUG_APP);
8550         final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0;
8551         final boolean alwaysFinishActivities =
8552                 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
8553         mHiddenApiBlacklist.registerObserver();
8554         mPlatformCompat.registerContentObserver();
8555 
8556         mAppProfiler.retrieveSettings();
8557 
8558         final Resources res;
8559         synchronized (this) {
8560             mDebugApp = mOrigDebugApp = debugApp;
8561             mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
8562             mAlwaysFinishActivities = alwaysFinishActivities;
8563             // Load resources only after the current configuration has been set.
8564             res = mContext.getResources();
8565             final boolean userSwitchUiEnabled = !res.getBoolean(
8566                     com.android.internal.R.bool.config_customUserSwitchUi);
8567             final int maxRunningUsers = res.getInteger(
8568                     com.android.internal.R.integer.config_multiuserMaxRunningUsers);
8569             final boolean delayUserDataLocking = res.getBoolean(
8570                     com.android.internal.R.bool.config_multiuserDelayUserDataLocking);
8571             mUserController.setInitialConfig(userSwitchUiEnabled, maxRunningUsers,
8572                     delayUserDataLocking);
8573         }
8574         mAppErrors.loadAppsNotReportingCrashesFromConfig(res.getString(
8575                 com.android.internal.R.string.config_appsNotReportingCrashes));
8576     }
8577 
8578     /**
8579      * Ready. Set. Go!
8580      */
systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t)8581     public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
8582         t.traceBegin("PhaseActivityManagerReady");
8583         mSystemServiceManager.preSystemReady();
8584         synchronized(this) {
8585             if (mSystemReady) {
8586                 // If we're done calling all the receivers, run the next "boot phase" passed in
8587                 // by the SystemServer
8588                 if (goingCallback != null) {
8589                     goingCallback.run();
8590                 }
8591                 t.traceEnd(); // PhaseActivityManagerReady
8592                 return;
8593             }
8594 
8595             t.traceBegin("controllersReady");
8596             mLocalDeviceIdleController =
8597                     LocalServices.getService(DeviceIdleInternal.class);
8598             mActivityTaskManager.onSystemReady();
8599             // Make sure we have the current profile info, since it is needed for security checks.
8600             mUserController.onSystemReady();
8601             mAppOpsService.systemReady();
8602             mProcessList.onSystemReady();
8603             mAppRestrictionController.onSystemReady();
8604             mSystemReady = true;
8605             t.traceEnd();
8606         }
8607 
8608         try {
8609             sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
8610                     ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
8611                     .getSerial();
8612         } catch (RemoteException e) {}
8613 
8614         t.traceBegin("killProcesses");
8615         ArrayList<ProcessRecord> procsToKill = null;
8616         synchronized(mPidsSelfLocked) {
8617             for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
8618                 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8619                 if (!isAllowedWhileBooting(proc.info)) {
8620                     if (procsToKill == null) {
8621                         procsToKill = new ArrayList<ProcessRecord>();
8622                     }
8623                     procsToKill.add(proc);
8624                 }
8625             }
8626         }
8627 
8628         synchronized(this) {
8629             if (procsToKill != null) {
8630                 for (int i = procsToKill.size() - 1; i >= 0; i--) {
8631                     ProcessRecord proc = procsToKill.get(i);
8632                     Slog.i(TAG, "Removing system update proc: " + proc);
8633                     mProcessList.removeProcessLocked(proc, true, false,
8634                             ApplicationExitInfo.REASON_OTHER,
8635                             ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
8636                             "system update done");
8637                 }
8638             }
8639 
8640             // Now that we have cleaned up any update processes, we
8641             // are ready to start launching real processes and know that
8642             // we won't trample on them any more.
8643             mProcessesReady = true;
8644         }
8645         t.traceEnd(); // KillProcesses
8646 
8647         Slog.i(TAG, "System now ready");
8648 
8649         EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis());
8650 
8651         t.traceBegin("updateTopComponentForFactoryTest");
8652         mAtmInternal.updateTopComponentForFactoryTest();
8653         t.traceEnd();
8654 
8655         t.traceBegin("registerActivityLaunchObserver");
8656         mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
8657         t.traceEnd();
8658 
8659         t.traceBegin("watchDeviceProvisioning");
8660         watchDeviceProvisioning(mContext);
8661         t.traceEnd();
8662 
8663         t.traceBegin("retrieveSettings");
8664         retrieveSettings();
8665         t.traceEnd();
8666 
8667         t.traceBegin("Ugm.onSystemReady");
8668         mUgmInternal.onSystemReady();
8669         t.traceEnd();
8670 
8671         t.traceBegin("updateForceBackgroundCheck");
8672         final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
8673         if (pmi != null) {
8674             pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
8675                     state -> updateForceBackgroundCheck(state.batterySaverEnabled));
8676             updateForceBackgroundCheck(
8677                     pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
8678         } else {
8679             Slog.wtf(TAG, "PowerManagerInternal not found.");
8680         }
8681         t.traceEnd();
8682 
8683         if (goingCallback != null) goingCallback.run();
8684 
8685         t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks
8686         // Check the current user here as a user can be started inside goingCallback.run() from
8687         // other system services.
8688         final int currentUserId = mUserController.getCurrentUserId();
8689         Slog.i(TAG, "Current user:" + currentUserId);
8690         if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
8691             // User other than system user has started. Make sure that system user is already
8692             // started before switching user.
8693             throw new RuntimeException("System user not started while current user is:"
8694                     + currentUserId);
8695         }
8696         t.traceEnd();
8697 
8698         t.traceBegin("ActivityManagerStartApps");
8699         mBatteryStatsService.onSystemReady();
8700         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
8701                 Integer.toString(currentUserId), currentUserId);
8702         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
8703                 Integer.toString(currentUserId), currentUserId);
8704 
8705         // On Automotive / Headless System User Mode, at this point the system user has already been
8706         // started and unlocked, and some of the tasks we do here have already been done. So skip
8707         // those in that case. The duplicate system user start is guarded in SystemServiceManager.
8708         // TODO(b/266158156): this workaround shouldn't be necessary once we move the headless-user
8709         // start logic to UserManager-land.
8710         mUserController.onSystemUserStarting();
8711 
8712         synchronized (this) {
8713             // Only start up encryption-aware persistent apps; once user is
8714             // unlocked we'll come back around and start unaware apps
8715             t.traceBegin("startPersistentApps");
8716             startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
8717             t.traceEnd();
8718 
8719             // Start up initial activity.
8720             mBooting = true;
8721             // Enable home activity for system user, so that the system can always boot. We don't
8722             // do this when the system user is not setup since the setup wizard should be the one
8723             // to handle home activity in this case.
8724             if (SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
8725                 t.traceBegin("enableHomeActivity");
8726                 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
8727                 try {
8728                     AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
8729                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
8730                             UserHandle.USER_SYSTEM, "am");
8731                 } catch (RemoteException e) {
8732                     throw e.rethrowAsRuntimeException();
8733                 }
8734                 t.traceEnd();
8735             }
8736 
8737             boolean isBootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
8738 
8739             // Some systems - like automotive - will explicitly unlock system user then switch
8740             // to a secondary user.
8741             // TODO(b/266158156): this workaround shouldn't be necessary once we move
8742             // the headless-user start logic to UserManager-land.
8743             if (isBootingSystemUser && !UserManager.isHeadlessSystemUserMode()) {
8744                 t.traceBegin("startHomeOnAllDisplays");
8745                 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
8746                 t.traceEnd();
8747             }
8748 
8749             t.traceBegin("showSystemReadyErrorDialogs");
8750             mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
8751             t.traceEnd();
8752 
8753 
8754             if (isBootingSystemUser) {
8755                 // Need to send the broadcasts for the system user here because
8756                 // UserController#startUserInternal will not send them for the system user starting,
8757                 // It checks if the user state already exists, which is always the case for the
8758                 // system user.
8759                 t.traceBegin("sendUserStartBroadcast");
8760                 final int callingUid = Binder.getCallingUid();
8761                 final int callingPid = Binder.getCallingPid();
8762                 final long ident = Binder.clearCallingIdentity();
8763                 try {
8764                     mUserController.sendUserStartedBroadcast(
8765                             currentUserId, callingUid, callingPid);
8766                     mUserController.sendUserStartingBroadcast(
8767                             currentUserId, callingUid, callingPid);
8768                 } catch (Throwable e) {
8769                     Slog.wtf(TAG, "Failed sending first user broadcasts", e);
8770                 } finally {
8771                     Binder.restoreCallingIdentity(ident);
8772                 }
8773                 t.traceEnd();
8774             } else {
8775                 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
8776                         + currentUserId);
8777             }
8778 
8779             t.traceBegin("resumeTopActivities");
8780             mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
8781             t.traceEnd();
8782 
8783             if (isBootingSystemUser) {
8784                 t.traceBegin("sendUserSwitchBroadcasts");
8785                 mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
8786                 t.traceEnd();
8787             }
8788 
8789             t.traceBegin("setBinderProxies");
8790             BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
8791                     BINDER_PROXY_LOW_WATERMARK);
8792             BinderInternal.nSetBinderProxyCountEnabled(true);
8793             BinderInternal.setBinderProxyCountCallback(
8794                     (uid) -> {
8795                         Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
8796                                 + Process.myUid());
8797                         BinderProxy.dumpProxyDebugInfo();
8798                         if (uid == Process.SYSTEM_UID) {
8799                             Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
8800                         } else {
8801                             killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
8802                                     "Too many Binders sent to SYSTEM");
8803                             // We need to run a GC here, because killing the processes involved
8804                             // actually isn't guaranteed to free up the proxies; in fact, if the
8805                             // GC doesn't run for a long time, we may even exceed the global
8806                             // proxy limit for a process (20000), resulting in system_server itself
8807                             // being killed.
8808                             // Note that the GC here might not actually clean up all the proxies,
8809                             // because the binder reference decrements will come in asynchronously;
8810                             // but if new processes belonging to the UID keep adding proxies, we
8811                             // will get another callback here, and run the GC again - this time
8812                             // cleaning up the old proxies.
8813                             VMRuntime.getRuntime().requestConcurrentGC();
8814                         }
8815                     }, mHandler);
8816             t.traceEnd(); // setBinderProxies
8817 
8818             t.traceEnd(); // ActivityManagerStartApps
8819 
8820             // Load the component aliases.
8821             t.traceBegin("componentAlias");
8822             mComponentAliasResolver.onSystemReady(mConstants.mEnableComponentAlias,
8823                     mConstants.mComponentAliasOverrides);
8824             t.traceEnd(); // componentAlias
8825 
8826             t.traceEnd(); // PhaseActivityManagerReady
8827         }
8828     }
8829 
watchDeviceProvisioning(Context context)8830     private void watchDeviceProvisioning(Context context) {
8831         // setting system property based on whether device is provisioned
8832 
8833         if (isDeviceProvisioned(context)) {
8834             SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
8835         } else {
8836             // watch for device provisioning change
8837             context.getContentResolver().registerContentObserver(
8838                     Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false,
8839                     new ContentObserver(new Handler(Looper.getMainLooper())) {
8840                         @Override
8841                         public void onChange(boolean selfChange) {
8842                             if (isDeviceProvisioned(context)) {
8843                                 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
8844                                 context.getContentResolver().unregisterContentObserver(this);
8845                             }
8846                         }
8847                     });
8848         }
8849     }
8850 
isDeviceProvisioned(Context context)8851     private boolean isDeviceProvisioned(Context context) {
8852         return Settings.Global.getInt(context.getContentResolver(),
8853                 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
8854     }
8855 
startBroadcastObservers()8856     private void startBroadcastObservers() {
8857         for (BroadcastQueue queue : mBroadcastQueues) {
8858             queue.start(mContext.getContentResolver());
8859         }
8860     }
8861 
updateForceBackgroundCheck(boolean enabled)8862     private void updateForceBackgroundCheck(boolean enabled) {
8863         synchronized (this) {
8864             synchronized (mProcLock) {
8865                 if (mForceBackgroundCheck != enabled) {
8866                     mForceBackgroundCheck = enabled;
8867 
8868                     if (DEBUG_BACKGROUND_CHECK) {
8869                         Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled"));
8870                     }
8871 
8872                     if (mForceBackgroundCheck) {
8873                         // Stop background services for idle UIDs.
8874                         mProcessList.doStopUidForIdleUidsLocked();
8875                     }
8876                 }
8877             }
8878         }
8879     }
8880 
killAppAtUsersRequest(ProcessRecord app)8881     void killAppAtUsersRequest(ProcessRecord app) {
8882         synchronized (this) {
8883             mAppErrors.killAppAtUserRequestLocked(app);
8884         }
8885     }
8886 
8887     /**
8888      * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8889      * The application process will exit immediately after this call returns.
8890      * @param app object of the crashing app, null for the system server
8891      * @param crashInfo describing the exception
8892      */
handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)8893     public void handleApplicationCrash(IBinder app,
8894             ApplicationErrorReport.ParcelableCrashInfo crashInfo) {
8895         ProcessRecord r = findAppProcess(app, "Crash");
8896         final String processName = app == null ? "system_server"
8897                 : (r == null ? "unknown" : r.processName);
8898 
8899         handleApplicationCrashInner("crash", r, processName, crashInfo);
8900     }
8901 
8902     /* Native crash reporting uses this inner version because it needs to be somewhat
8903      * decoupled from the AM-managed cleanup lifecycle
8904      */
handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)8905     void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
8906             ApplicationErrorReport.CrashInfo crashInfo) {
8907         float loadingProgress = 1;
8908         IncrementalMetrics incrementalMetrics = null;
8909         // Obtain Incremental information if available
8910         if (r != null && r.info != null && r.info.packageName != null) {
8911             IncrementalStatesInfo incrementalStatesInfo =
8912                     mPackageManagerInt.getIncrementalStatesInfo(r.info.packageName, SYSTEM_UID,
8913                             r.userId);
8914             if (incrementalStatesInfo != null) {
8915                 loadingProgress = incrementalStatesInfo.getProgress();
8916             }
8917             final String codePath = r.info.getCodePath();
8918             if (codePath != null && !codePath.isEmpty()
8919                     && IncrementalManager.isIncrementalPath(codePath)) {
8920                 // Report in the main log about the incremental package
8921                 Slog.e(TAG, "App crashed on incremental package " + r.info.packageName
8922                         + " which is " + ((int) (loadingProgress * 100)) + "% loaded.");
8923                 final IBinder incrementalService = ServiceManager.getService(
8924                         Context.INCREMENTAL_SERVICE);
8925                 if (incrementalService != null) {
8926                     final IncrementalManager incrementalManager = new IncrementalManager(
8927                             IIncrementalService.Stub.asInterface(incrementalService));
8928                     incrementalMetrics = incrementalManager.getMetrics(codePath);
8929                 }
8930             }
8931         }
8932 
8933         boolean recoverable = eventType.equals("native_recoverable_crash");
8934 
8935         EventLogTags.writeAmCrash(Binder.getCallingPid(),
8936                 UserHandle.getUserId(Binder.getCallingUid()), processName,
8937                 r == null ? -1 : r.info.flags,
8938                 crashInfo.exceptionClassName,
8939                 crashInfo.exceptionMessage,
8940                 crashInfo.throwFileName,
8941                 crashInfo.throwLineNumber,
8942                 recoverable ? 1 : 0);
8943 
8944         int processClassEnum = processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER
8945                 : (r != null) ? r.getProcessClassEnum()
8946                         : ServerProtoEnums.ERROR_SOURCE_UNKNOWN;
8947         int uid = (r != null) ? r.uid : -1;
8948         int pid = (r != null) ? r.getPid() : -1;
8949         FrameworkStatsLog.write(FrameworkStatsLog.APP_CRASH_OCCURRED,
8950                 uid,
8951                 eventType,
8952                 processName,
8953                 pid,
8954                 (r != null && r.info != null) ? r.info.packageName : "",
8955                 (r != null && r.info != null) ? (r.info.isInstantApp()
8956                         ? FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE
8957                         : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE)
8958                         : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE,
8959                 r != null ? (r.isInterestingToUserLocked()
8960                         ? FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND
8961                         : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND)
8962                         : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN,
8963                 processClassEnum,
8964                 incrementalMetrics != null /* isIncremental */, loadingProgress,
8965                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceOldestPendingRead()
8966                         : -1,
8967                 incrementalMetrics != null ? incrementalMetrics.getStorageHealthStatusCode()
8968                         : -1,
8969                 incrementalMetrics != null ? incrementalMetrics.getDataLoaderStatusCode()
8970                         : -1,
8971                 incrementalMetrics != null && incrementalMetrics.getReadLogsEnabled(),
8972                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastDataLoaderBind()
8973                         : -1,
8974                 incrementalMetrics != null ? incrementalMetrics.getDataLoaderBindDelayMillis()
8975                         : -1,
8976                 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReads()
8977                         : -1,
8978                 incrementalMetrics != null ? incrementalMetrics.getTotalFailedReads()
8979                         : -1,
8980                 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorUid()
8981                         : -1,
8982                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastReadError()
8983                         : -1,
8984                 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorNumber()
8985                         : 0,
8986                 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReadsDurationMillis()
8987                         : -1
8988         );
8989 
8990         if (eventType.equals("native_crash")) {
8991             CriticalEventLog.getInstance().logNativeCrash(processClassEnum, processName, uid, pid);
8992         } else if (eventType.equals("crash")) {
8993             CriticalEventLog.getInstance().logJavaCrash(crashInfo.exceptionClassName,
8994                     processClassEnum, processName, uid, pid);
8995         }
8996 
8997         final int relaunchReason = r == null ? RELAUNCH_REASON_NONE
8998                         : r.getWindowProcessController().computeRelaunchReason();
8999         final String relaunchReasonString = relaunchReasonToString(relaunchReason);
9000         if (crashInfo.crashTag == null) {
9001             crashInfo.crashTag = relaunchReasonString;
9002         } else {
9003             crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString;
9004         }
9005 
9006         addErrorToDropBox(
9007                 eventType, r, processName, null, null, null, null, null, null, crashInfo,
9008                 new Float(loadingProgress), incrementalMetrics, null, null);
9009 
9010         // For GWP-ASan recoverable crashes, don't make the app crash (the whole point of
9011         // 'recoverable' is that the app doesn't crash). Normally, for nonrecoreable native crashes,
9012         // debuggerd will terminate the process, but there's a backup where ActivityManager will
9013         // also kill it. Avoid that.
9014         if (recoverable) {
9015             mAppErrors.sendRecoverableCrashToAppExitInfo(r, crashInfo);
9016         } else {
9017             mAppErrors.crashApplication(r, crashInfo);
9018         }
9019     }
9020 
handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)9021     public void handleApplicationStrictModeViolation(
9022             IBinder app,
9023             int penaltyMask,
9024             StrictMode.ViolationInfo info) {
9025         // We're okay if the ProcessRecord is missing; it probably means that
9026         // we're reporting a violation from the system process itself.
9027         final ProcessRecord r = findAppProcess(app, "StrictMode");
9028 
9029         if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) {
9030             Integer stackFingerprint = info.hashCode();
9031             boolean logIt = true;
9032             synchronized (mAlreadyLoggedViolatedStacks) {
9033                 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
9034                     logIt = false;
9035                     // TODO: sub-sample into EventLog for these, with
9036                     // the info.durationMillis?  Then we'd get
9037                     // the relative pain numbers, without logging all
9038                     // the stack traces repeatedly.  We'd want to do
9039                     // likewise in the client code, which also does
9040                     // dup suppression, before the Binder call.
9041                 } else {
9042                     if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
9043                         mAlreadyLoggedViolatedStacks.clear();
9044                     }
9045                     mAlreadyLoggedViolatedStacks.add(stackFingerprint);
9046                 }
9047             }
9048             if (logIt) {
9049                 logStrictModeViolationToDropBox(r, info);
9050             }
9051         }
9052 
9053         if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) {
9054             AppErrorResult result = new AppErrorResult();
9055             final long origId = Binder.clearCallingIdentity();
9056             try {
9057                 Message msg = Message.obtain();
9058                 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG;
9059                 HashMap<String, Object> data = new HashMap<String, Object>();
9060                 data.put("result", result);
9061                 data.put("app", r);
9062                 data.put("info", info);
9063                 msg.obj = data;
9064                 mUiHandler.sendMessage(msg);
9065             } finally {
9066                 Binder.restoreCallingIdentity(origId);
9067             }
9068             int res = result.get();
9069             Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
9070         }
9071     }
9072 
9073     /**
9074      * Register a callback to raise strict mode violations.
9075      * @param callback The binder used to communicate the violations.
9076      */
9077     @Override
registerStrictModeCallback(IBinder callback)9078     public void registerStrictModeCallback(IBinder callback) {
9079         int callingPid = Binder.getCallingPid();
9080         mStrictModeCallbacks.put(callingPid,
9081                 IUnsafeIntentStrictModeCallback.Stub.asInterface(callback));
9082         try {
9083             callback.linkToDeath(new DeathRecipient() {
9084                 @Override
9085                 public void binderDied() {
9086                     mStrictModeCallbacks.remove(callingPid);
9087                 }
9088             }, 0);
9089         } catch (RemoteException e) {
9090             mStrictModeCallbacks.remove(callingPid);
9091         }
9092     }
9093 
9094     // Depending on the policy in effect, there could be a bunch of
9095     // these in quick succession so we try to batch these together to
9096     // minimize disk writes, number of dropbox entries, and maximize
9097     // compression, by having more fewer, larger records.
logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)9098     private void logStrictModeViolationToDropBox(
9099             ProcessRecord process,
9100             StrictMode.ViolationInfo info) {
9101         if (info == null) {
9102             return;
9103         }
9104         final boolean isSystemApp = process == null ||
9105                 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
9106                                        ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
9107         final String processName = process == null ? "unknown" : process.processName;
9108         final DropBoxManager dbox = (DropBoxManager)
9109                 mContext.getSystemService(Context.DROPBOX_SERVICE);
9110 
9111         // Exit early if the dropbox isn't configured to accept this report type.
9112         final String dropboxTag = processClass(process) + "_strictmode";
9113         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9114 
9115         final StringBuilder sb = new StringBuilder(1024);
9116         synchronized (sb) {
9117             appendDropBoxProcessHeaders(process, processName, null, sb);
9118             sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9119             sb.append("System-App: ").append(isSystemApp).append("\n");
9120             sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
9121             if (info.violationNumThisLoop != 0) {
9122                 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
9123             }
9124             if (info.numAnimationsRunning != 0) {
9125                 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
9126             }
9127             if (info.broadcastIntentAction != null) {
9128                 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
9129             }
9130             if (info.durationMillis != -1) {
9131                 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
9132             }
9133             if (info.numInstances != -1) {
9134                 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
9135             }
9136             if (info.tags != null) {
9137                 for (String tag : info.tags) {
9138                     sb.append("Span-Tag: ").append(tag).append("\n");
9139                 }
9140             }
9141             sb.append("\n");
9142             sb.append(info.getStackTrace());
9143             sb.append("\n");
9144             if (info.getViolationDetails() != null) {
9145                 sb.append(info.getViolationDetails());
9146                 sb.append("\n");
9147             }
9148         }
9149 
9150         final String res = sb.toString();
9151         IoThread.getHandler().post(() -> {
9152             dbox.addText(dropboxTag, res);
9153         });
9154     }
9155 
9156     /**
9157      * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
9158      * @param app object of the crashing app, null for the system server
9159      * @param tag reported by the caller
9160      * @param system whether this wtf is coming from the system
9161      * @param crashInfo describing the context of the error
9162      * @return true if the process should exit immediately (WTF is fatal)
9163      */
9164     @Override
handleApplicationWtf(@ullable final IBinder app, @Nullable final String tag, boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)9165     public boolean handleApplicationWtf(@Nullable final IBinder app, @Nullable final String tag,
9166             boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo,
9167             int immediateCallerPid) {
9168         final int callingUid = Binder.getCallingUid();
9169         final int callingPid = Binder.getCallingPid();
9170 
9171         // Internal callers in RuntimeInit should always generate a crashInfo.
9172         Preconditions.checkNotNull(crashInfo);
9173 
9174         // If this is coming from the system, we could very well have low-level
9175         // system locks held, so we want to do this all asynchronously.  And we
9176         // never want this to become fatal, so there is that too.
9177         //
9178         // Note: "callingPid == Process.myPid())" wouldn't be reliable because even if the caller
9179         // is within the system server, if it calls Log.wtf() without clearning the calling
9180         // identity, callingPid would still be of a remote caller. So we explicltly pass the
9181         // process PID from the caller.
9182         if (system || (immediateCallerPid == Process.myPid())) {
9183             mHandler.post(new Runnable() {
9184                 @Override public void run() {
9185                     handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo);
9186                 }
9187             });
9188             return false;
9189         }
9190 
9191         final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag,
9192                 crashInfo);
9193 
9194         final boolean isFatal = Build.IS_ENG || Settings.Global
9195                 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0;
9196         final boolean isSystem = (r == null) || r.isPersistent();
9197 
9198         if (isFatal && !isSystem) {
9199             mAppErrors.crashApplication(r, crashInfo);
9200             return true;
9201         } else {
9202             return false;
9203         }
9204     }
9205 
handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo)9206     ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app,
9207             @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo) {
9208         final ProcessRecord r = findAppProcess(app, "WTF");
9209         final String processName = app == null ? "system_server"
9210                 : (r == null ? "unknown" : r.processName);
9211 
9212         EventLogTags.writeAmWtf(UserHandle.getUserId(callingUid), callingPid,
9213                 processName, r == null ? -1 : r.info.flags, tag,
9214                 crashInfo == null ? "unknown" : crashInfo.exceptionMessage);
9215 
9216         FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, callingUid, tag, processName,
9217                 callingPid, (r != null) ? r.getProcessClassEnum() : 0);
9218 
9219         addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo,
9220                 null, null, null, null);
9221 
9222         return r;
9223     }
9224 
9225     /**
9226      * Schedule to handle any pending system_server WTFs.
9227      */
schedulePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)9228     public void schedulePendingSystemServerWtfs(
9229             final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) {
9230         mHandler.post(() -> handlePendingSystemServerWtfs(list));
9231     }
9232 
9233     /**
9234      * Handle any pending system_server WTFs, add into the dropbox
9235      */
handlePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)9236     private void handlePendingSystemServerWtfs(
9237             final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) {
9238         ProcessRecord proc;
9239         synchronized (mPidsSelfLocked) {
9240             proc = mPidsSelfLocked.get(MY_PID);
9241         }
9242         for (Pair<String, ApplicationErrorReport.CrashInfo> p = list.poll();
9243                 p != null; p = list.poll()) {
9244             addErrorToDropBox("wtf", proc, "system_server", null, null, null, p.first, null, null,
9245                     p.second, null, null, null, null);
9246         }
9247     }
9248 
9249     /**
9250      * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
9251      * @return the corresponding {@link ProcessRecord} object, or null if none could be found
9252      */
findAppProcess(IBinder app, String reason)9253     private ProcessRecord findAppProcess(IBinder app, String reason) {
9254         if (app == null) {
9255             return null;
9256         }
9257 
9258         synchronized (mProcLock) {
9259             return mProcessList.findAppProcessLOSP(app, reason);
9260         }
9261     }
9262 
9263     /**
9264      * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
9265      * to append various headers to the dropbox log text.
9266      */
appendDropBoxProcessHeaders(ProcessRecord process, String processName, final VolatileDropboxEntryStates volatileStates, final StringBuilder sb)9267     void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
9268             final VolatileDropboxEntryStates volatileStates, final StringBuilder sb) {
9269         // Watchdog thread ends up invoking this function (with
9270         // a null ProcessRecord) to add the stack file to dropbox.
9271         // Do not acquire a lock on this (am) in such cases, as it
9272         // could cause a potential deadlock, if and when watchdog
9273         // is invoked due to unavailability of lock on am and it
9274         // would prevent watchdog from killing system_server.
9275         if (process == null) {
9276             sb.append("Process: ").append(processName).append("\n");
9277             return;
9278         }
9279         // Note: ProcessRecord 'process' is guarded by the service
9280         // instance.  (notably process.pkgList, which could otherwise change
9281         // concurrently during execution of this method)
9282         synchronized (mProcLock) {
9283             sb.append("Process: ").append(processName).append("\n");
9284             sb.append("PID: ").append(process.getPid()).append("\n");
9285             sb.append("UID: ").append(process.uid).append("\n");
9286             if (process.mOptRecord != null) {
9287                 // Use 'isProcessFrozen' from 'volatileStates' if it'snon-null (present),
9288                 // otherwise use 'isFrozen' from 'mOptRecord'.
9289                 sb.append("Frozen: ").append(
9290                     (volatileStates != null && volatileStates.isProcessFrozen() != null)
9291                     ? volatileStates.isProcessFrozen() : process.mOptRecord.isFrozen()
9292                 ).append("\n");
9293             }
9294             int flags = process.info.flags;
9295             final IPackageManager pm = AppGlobals.getPackageManager();
9296             sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n");
9297             final int callingUserId = UserHandle.getCallingUserId();
9298             process.getPkgList().forEachPackage(pkg -> {
9299                 sb.append("Package: ").append(pkg);
9300                 try {
9301                     final PackageInfo pi = pm.getPackageInfo(pkg, 0, callingUserId);
9302                     if (pi != null) {
9303                         sb.append(" v").append(pi.getLongVersionCode());
9304                         if (pi.versionName != null) {
9305                             sb.append(" (").append(pi.versionName).append(")");
9306                         }
9307                     }
9308                 } catch (RemoteException e) {
9309                     Slog.e(TAG, "Error getting package info: " + pkg, e);
9310                 }
9311                 sb.append("\n");
9312             });
9313             if (process.info.isInstantApp()) {
9314                 sb.append("Instant-App: true\n");
9315             }
9316 
9317             if (process.isSdkSandbox) {
9318                 final String clientPackage = process.sdkSandboxClientAppPackage;
9319                 try {
9320                     final PackageInfo pi = pm.getPackageInfo(clientPackage,
9321                             PackageManager.GET_SHARED_LIBRARY_FILES, callingUserId);
9322                     if (pi != null) {
9323                         appendSdkSandboxClientPackageHeader(sb, pi);
9324                         appendSdkSandboxLibraryHeaders(sb, pi);
9325                     } else {
9326                         Slog.e(TAG,
9327                                 "PackageInfo is null for SDK sandbox client: " + clientPackage);
9328                     }
9329                 } catch (RemoteException e) {
9330                     Slog.e(TAG,
9331                             "Error getting package info for SDK sandbox client: " + clientPackage,
9332                             e);
9333                 }
9334                 sb.append("SdkSandbox: true\n");
9335             }
9336         }
9337     }
9338 
appendSdkSandboxClientPackageHeader(StringBuilder sb, PackageInfo clientPackageInfo)9339     private void appendSdkSandboxClientPackageHeader(StringBuilder sb,
9340             PackageInfo clientPackageInfo) {
9341         sb.append("SdkSandbox-Client-Package: ").append(clientPackageInfo.packageName);
9342         sb.append(" v").append(clientPackageInfo.getLongVersionCode());
9343         if (clientPackageInfo.versionName != null) {
9344             sb.append(" (").append(clientPackageInfo.versionName).append(")");
9345         }
9346         sb.append("\n");
9347     }
9348 
appendSdkSandboxLibraryHeaders(StringBuilder sb, PackageInfo clientPackageInfo)9349     private void appendSdkSandboxLibraryHeaders(StringBuilder sb,
9350             PackageInfo clientPackageInfo) {
9351         final ApplicationInfo info = clientPackageInfo.applicationInfo;
9352         final List<SharedLibraryInfo> sharedLibraries = info.getSharedLibraryInfos();
9353         for (int j = 0, size = sharedLibraries.size(); j < size; j++) {
9354             final SharedLibraryInfo sharedLibrary = sharedLibraries.get(j);
9355             if (!sharedLibrary.isSdk()) {
9356                 continue;
9357             }
9358 
9359             sb.append("SdkSandbox-Library: ").append(sharedLibrary.getPackageName());
9360             final VersionedPackage versionedPackage = sharedLibrary.getDeclaringPackage();
9361             sb.append(" v").append(versionedPackage.getLongVersionCode());
9362             sb.append("\n");
9363         }
9364     }
9365 
processClass(ProcessRecord process)9366     private static String processClass(ProcessRecord process) {
9367         if (process == null || process.getPid() == MY_PID) {
9368             return "system_server";
9369         } else if (process.info.isSystemApp() || process.info.isSystemExt()) {
9370             return "system_app";
9371         } else {
9372             return "data_app";
9373         }
9374     }
9375 
9376     private final DropboxRateLimiter mDropboxRateLimiter = new DropboxRateLimiter();
9377 
9378     /**
9379      * Write a description of an error (crash, WTF, ANR) to the drop box.
9380      * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
9381      * @param process which caused the error, null means the system server
9382      * @param activityShortComponentName which triggered the error, null if unknown
9383      * @param parentShortComponentName activity related to the error, null if unknown
9384      * @param parentProcess parent process
9385      * @param subject line related to the error, null if absent
9386      * @param report in long form describing the error, null if absent
9387      * @param dataFile text file to include in the report, null if none
9388      * @param crashInfo giving an application stack trace, null if absent
9389      * @param loadingProgress the loading progress of an installed package, range in [0, 1].
9390      * @param incrementalMetrics metrics for apps installed on Incremental.
9391      * @param errorId a unique id to append to the dropbox headers.
9392      */
9393     @SuppressWarnings("DoNotCall") // Ignore warning for synchronous to call to worker.run()
addErrorToDropBox(String eventType, ProcessRecord process, String processName, String activityShortComponentName, String parentShortComponentName, ProcessRecord parentProcess, String subject, final String report, final File dataFile, final ApplicationErrorReport.CrashInfo crashInfo, @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics, @Nullable UUID errorId, @Nullable VolatileDropboxEntryStates volatileStates)9394     public void addErrorToDropBox(String eventType,
9395             ProcessRecord process, String processName, String activityShortComponentName,
9396             String parentShortComponentName, ProcessRecord parentProcess,
9397             String subject, final String report, final File dataFile,
9398             final ApplicationErrorReport.CrashInfo crashInfo,
9399             @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics,
9400             @Nullable UUID errorId, @Nullable VolatileDropboxEntryStates volatileStates) {
9401         // NOTE -- this must never acquire the ActivityManagerService lock,
9402         // otherwise the watchdog may be prevented from resetting the system.
9403 
9404         // Bail early if not published yet
9405         final DropBoxManager dbox;
9406         try {
9407             dbox = mContext.getSystemService(DropBoxManager.class);
9408         } catch (Exception e) {
9409             return;
9410         }
9411 
9412         // Exit early if the dropbox isn't configured to accept this report type.
9413         final String dropboxTag = processClass(process) + "_" + eventType;
9414         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9415 
9416         // Check if we should rate limit and abort early if needed.
9417         final DropboxRateLimiter.RateLimitResult rateLimitResult =
9418                 mDropboxRateLimiter.shouldRateLimit(eventType, processName);
9419         if (rateLimitResult.shouldRateLimit()) return;
9420 
9421         final StringBuilder sb = new StringBuilder(1024);
9422         appendDropBoxProcessHeaders(process, processName, volatileStates, sb);
9423         if (process != null) {
9424             sb.append("Foreground: ")
9425                     .append(process.isInterestingToUserLocked() ? "Yes" : "No")
9426                     .append("\n");
9427             if (process.getStartUptime() > 0) {
9428                 long runtimeMillis = SystemClock.uptimeMillis() - process.getStartUptime();
9429                 sb.append("Process-Runtime: ").append(runtimeMillis).append("\n");
9430             }
9431         }
9432         if (activityShortComponentName != null) {
9433             sb.append("Activity: ").append(activityShortComponentName).append("\n");
9434         }
9435         if (parentShortComponentName != null) {
9436             if (parentProcess != null && parentProcess.getPid() != process.getPid()) {
9437                 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n");
9438             }
9439             if (!parentShortComponentName.equals(activityShortComponentName)) {
9440                 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n");
9441             }
9442         }
9443         if (subject != null) {
9444             sb.append("Subject: ").append(subject).append("\n");
9445         }
9446         if (errorId != null) {
9447             sb.append("ErrorId: ").append(errorId.toString()).append("\n");
9448         }
9449         sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9450         if (Debug.isDebuggerConnected()) {
9451             sb.append("Debugger: Connected\n");
9452         }
9453         if (crashInfo != null && crashInfo.exceptionHandlerClassName != null
9454                 && !crashInfo.exceptionHandlerClassName.isEmpty()) {
9455             sb.append("Crash-Handler: ").append(crashInfo.exceptionHandlerClassName).append("\n");
9456         }
9457         if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) {
9458             sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n");
9459         }
9460         if (loadingProgress != null) {
9461             sb.append("Loading-Progress: ").append(loadingProgress.floatValue()).append("\n");
9462         }
9463         if (incrementalMetrics != null) {
9464             sb.append("Incremental: Yes").append("\n");
9465             final long millisSinceOldestPendingRead =
9466                     incrementalMetrics.getMillisSinceOldestPendingRead();
9467             if (millisSinceOldestPendingRead > 0) {
9468                 sb.append("Millis-Since-Oldest-Pending-Read: ").append(
9469                         millisSinceOldestPendingRead).append("\n");
9470             }
9471         }
9472         sb.append(rateLimitResult.createHeader());
9473         sb.append("\n");
9474 
9475         // Do the rest in a worker thread to avoid blocking the caller on I/O
9476         // (After this point, we shouldn't access AMS internal data structures.)
9477         //
9478         // If process is null, we are being called from some internal code
9479         // and may be about to die -- run this synchronously.
9480         final boolean runSynchronously = process == null;
9481         Thread worker = new Thread("Error dump: " + dropboxTag) {
9482             @Override
9483             public void run() {
9484                 if (report != null) {
9485                     sb.append(report);
9486                 }
9487 
9488                 String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
9489                 String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag;
9490                 int lines = Build.IS_USER
9491                         ? 0
9492                         : Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0);
9493                 int dropboxMaxSize = Settings.Global.getInt(
9494                         mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE);
9495                 int maxDataFileSize = dropboxMaxSize - sb.length()
9496                         - lines * RESERVED_BYTES_PER_LOGCAT_LINE;
9497 
9498                 if (dataFile != null && maxDataFileSize > 0) {
9499                     try {
9500                         sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize,
9501                                     "\n\n[[TRUNCATED]]"));
9502                     } catch (IOException e) {
9503                         Slog.e(TAG, "Error reading " + dataFile, e);
9504                     }
9505                 }
9506                 if (crashInfo != null && crashInfo.stackTrace != null) {
9507                     sb.append(crashInfo.stackTrace);
9508                 }
9509 
9510                 if (lines > 0 && !runSynchronously) {
9511                     sb.append("\n");
9512 
9513                     InputStreamReader input = null;
9514                     try {
9515                         java.lang.Process logcat = new ProcessBuilder(
9516                                 // Time out after 10s of inactivity, but kill logcat with SEGV
9517                                 // so we can investigate why it didn't finish.
9518                                 "/system/bin/timeout", "-i", "-s", "SEGV", "10s",
9519                                 // Merge several logcat streams, and take the last N lines.
9520                                 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system",
9521                                 "-b", "main", "-b", "crash", "-t", String.valueOf(lines))
9522                                         .redirectErrorStream(true).start();
9523 
9524                         try { logcat.getOutputStream().close(); } catch (IOException e) {}
9525                         try { logcat.getErrorStream().close(); } catch (IOException e) {}
9526                         input = new InputStreamReader(logcat.getInputStream());
9527 
9528                         int num;
9529                         char[] buf = new char[8192];
9530                         while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
9531                     } catch (IOException e) {
9532                         Slog.e(TAG, "Error running logcat", e);
9533                     } finally {
9534                         if (input != null) try { input.close(); } catch (IOException e) {}
9535                     }
9536                 }
9537 
9538                 dbox.addText(dropboxTag, sb.toString());
9539             }
9540         };
9541 
9542         if (runSynchronously) {
9543             final int oldMask = StrictMode.allowThreadDiskWritesMask();
9544             try {
9545                 worker.run();
9546             } finally {
9547                 StrictMode.setThreadPolicyMask(oldMask);
9548             }
9549         } else {
9550             worker.start();
9551         }
9552     }
9553 
9554     @Override
getProcessesInErrorState()9555     public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
9556         enforceNotIsolatedCaller("getProcessesInErrorState");
9557         // assume our apps are happy - lazy create the list
9558         final List<ActivityManager.ProcessErrorStateInfo>[] errList = new List[1];
9559 
9560         final int callingUid = Binder.getCallingUid();
9561         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
9562                 callingUid) == PackageManager.PERMISSION_GRANTED;
9563         int userId = UserHandle.getUserId(callingUid);
9564 
9565         final boolean hasDumpPermission = ActivityManager.checkUidPermission(
9566                 android.Manifest.permission.DUMP, callingUid) == PackageManager.PERMISSION_GRANTED;
9567 
9568         synchronized (mProcLock) {
9569             // iterate across all processes
9570             mProcessList.forEachLruProcessesLOSP(false, app -> {
9571                 if (!allUsers && app.userId != userId) {
9572                     return;
9573                 }
9574                 if (!hasDumpPermission && app.info.uid != callingUid) {
9575                     return;
9576                 }
9577                 final ProcessErrorStateRecord errState = app.mErrorState;
9578                 final boolean crashing = errState.isCrashing();
9579                 final boolean notResponding = errState.isNotResponding();
9580                 if ((app.getThread() != null) && (crashing || notResponding)) {
9581                     // This one's in trouble, so we'll generate a report for it
9582                     // crashes are higher priority (in case there's a crash *and* an anr)
9583                     ActivityManager.ProcessErrorStateInfo report = null;
9584                     if (crashing) {
9585                         report = errState.getCrashingReport();
9586                     } else if (notResponding) {
9587                         report = errState.getNotRespondingReport();
9588                     }
9589 
9590                     if (report != null) {
9591                         if (errList[0] == null) {
9592                             errList[0] = new ArrayList<>(1);
9593                         }
9594                         errList[0].add(report);
9595                     } else {
9596                         Slog.w(TAG, "Missing app error report, app = " + app.processName +
9597                                 " crashing = " + crashing +
9598                                 " notResponding = " + notResponding);
9599                     }
9600                 }
9601             });
9602         }
9603 
9604         return errList[0];
9605     }
9606 
9607     @Override
getRunningAppProcesses()9608     public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
9609         enforceNotIsolatedCaller("getRunningAppProcesses");
9610 
9611         final int callingUid = Binder.getCallingUid();
9612         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
9613 
9614         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
9615                 callingUid) == PackageManager.PERMISSION_GRANTED;
9616         final int userId = UserHandle.getUserId(callingUid);
9617         final boolean allUids = mAtmInternal.isGetTasksAllowed(
9618                 "getRunningAppProcesses", Binder.getCallingPid(), callingUid);
9619 
9620         synchronized (mProcLock) {
9621             // Iterate across all processes
9622             return mProcessList.getRunningAppProcessesLOSP(allUsers, userId, allUids,
9623                     callingUid, clientTargetSdk);
9624         }
9625     }
9626 
9627     @Override
getRunningExternalApplications()9628     public List<ApplicationInfo> getRunningExternalApplications() {
9629         enforceNotIsolatedCaller("getRunningExternalApplications");
9630         List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
9631         List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
9632         if (runningApps != null && runningApps.size() > 0) {
9633             Set<String> extList = new HashSet<String>();
9634             for (ActivityManager.RunningAppProcessInfo app : runningApps) {
9635                 if (app.pkgList != null) {
9636                     for (String pkg : app.pkgList) {
9637                         extList.add(pkg);
9638                     }
9639                 }
9640             }
9641             IPackageManager pm = AppGlobals.getPackageManager();
9642             for (String pkg : extList) {
9643                 try {
9644                     ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
9645                     if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
9646                         retList.add(info);
9647                     }
9648                 } catch (RemoteException e) {
9649                 }
9650             }
9651         }
9652         return retList;
9653     }
9654 
9655     /* @hide */
9656     @Override
getHistoricalProcessStartReasons( String packageName, int maxNum, int userId)9657     public ParceledListSlice<ApplicationStartInfo> getHistoricalProcessStartReasons(
9658             String packageName, int maxNum, int userId) {
9659         if (!mConstants.mFlagApplicationStartInfoEnabled) {
9660             return new ParceledListSlice<ApplicationStartInfo>(
9661                 new ArrayList<ApplicationStartInfo>());
9662         }
9663         enforceNotIsolatedCaller("getHistoricalProcessStartReasons");
9664 
9665         final ArrayList<ApplicationStartInfo> results = new ArrayList<ApplicationStartInfo>();
9666 
9667         return new ParceledListSlice<ApplicationStartInfo>(results);
9668     }
9669 
9670 
9671     /* @hide */
9672     @Override
setApplicationStartInfoCompleteListener( IApplicationStartInfoCompleteListener listener, int userId)9673     public void setApplicationStartInfoCompleteListener(
9674             IApplicationStartInfoCompleteListener listener, int userId) {
9675         if (!mConstants.mFlagApplicationStartInfoEnabled) {
9676             return;
9677         }
9678         enforceNotIsolatedCaller("setApplicationStartInfoCompleteListener");
9679     }
9680 
9681 
9682     /* @hide */
9683     @Override
removeApplicationStartInfoCompleteListener(int userId)9684     public void removeApplicationStartInfoCompleteListener(int userId) {
9685         if (!mConstants.mFlagApplicationStartInfoEnabled) {
9686             return;
9687         }
9688         enforceNotIsolatedCaller("removeApplicationStartInfoCompleteListener");
9689     }
9690 
9691     @Override
getHistoricalProcessExitReasons( String packageName, int pid, int maxNum, int userId)9692     public ParceledListSlice<ApplicationExitInfo> getHistoricalProcessExitReasons(
9693             String packageName, int pid, int maxNum, int userId) {
9694         enforceNotIsolatedCaller("getHistoricalProcessExitReasons");
9695 
9696         // For the simplification, we don't support USER_ALL nor USER_CURRENT here.
9697         if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) {
9698             throw new IllegalArgumentException("Unsupported userId");
9699         }
9700 
9701         final int callingPid = Binder.getCallingPid();
9702         final int callingUid = Binder.getCallingUid();
9703         final int callingUserId = UserHandle.getCallingUserId();
9704         mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL,
9705                 "getHistoricalProcessExitReasons", null);
9706 
9707         NativeTombstoneManager tombstoneService = LocalServices.getService(
9708                 NativeTombstoneManager.class);
9709 
9710         final ArrayList<ApplicationExitInfo> results = new ArrayList<ApplicationExitInfo>();
9711         if (!TextUtils.isEmpty(packageName)) {
9712             final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid,
9713                       "getHistoricalProcessExitReasons");
9714             if (uid != INVALID_UID) {
9715                 mProcessList.mAppExitInfoTracker.getExitInfo(
9716                         packageName, uid, pid, maxNum, results);
9717                 tombstoneService.collectTombstones(results, uid, pid, maxNum);
9718             }
9719         } else {
9720             // If no package name is given, use the caller's uid as the filter uid.
9721             mProcessList.mAppExitInfoTracker.getExitInfo(
9722                     packageName, callingUid, pid, maxNum, results);
9723             tombstoneService.collectTombstones(results, callingUid, pid, maxNum);
9724         }
9725 
9726         return new ParceledListSlice<ApplicationExitInfo>(results);
9727     }
9728 
9729     @Override
setProcessStateSummary(@ullable byte[] state)9730     public void setProcessStateSummary(@Nullable byte[] state) {
9731         if (state != null && state.length > MAX_STATE_DATA_SIZE) {
9732             throw new IllegalArgumentException("Data size is too large");
9733         }
9734         mProcessList.mAppExitInfoTracker.setProcessStateSummary(Binder.getCallingUid(),
9735                 Binder.getCallingPid(), state);
9736     }
9737 
9738     /**
9739      * Check if the calling process has the permission to dump given package,
9740      * throw SecurityException if it doesn't have the permission.
9741      *
9742      * @return The real UID of process that can be dumped, or {@link android.os.Process#INVALID_UID}
9743      *         if the package is not found.
9744      */
enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, String function)9745     int enforceDumpPermissionForPackage(String packageName, int userId, int callingUid,
9746             String function) {
9747         // Allow SDK sandbox process to dump for its own process (under SDK sandbox package)
9748         try {
9749             if (Process.isSdkSandboxUid(callingUid)
9750                     && getPackageManager().getSdkSandboxPackageName().equals(packageName)) {
9751                 return callingUid;
9752             }
9753         } catch (RemoteException e) {
9754             Log.e(TAG, "Could not get SDK sandbox package name");
9755         }
9756         final long identity = Binder.clearCallingIdentity();
9757         int uid = INVALID_UID;
9758         try {
9759             uid = mPackageManagerInt.getPackageUid(packageName,
9760                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId);
9761         } finally {
9762             Binder.restoreCallingIdentity(identity);
9763         }
9764         // If the uid is Process.INVALID_UID, the below 'if' check will be always true
9765         if (UserHandle.getAppId(uid) != UserHandle.getAppId(callingUid)) {
9766             // Requires the DUMP permission if the target package doesn't belong
9767             // to the caller or it doesn't exist.
9768             enforceCallingPermission(android.Manifest.permission.DUMP, function);
9769         }
9770         return uid;
9771     }
9772 
9773     @Override
getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)9774     public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) {
9775         if (outState == null) {
9776             throw new IllegalArgumentException("outState is null");
9777         }
9778         enforceNotIsolatedCaller("getMyMemoryState");
9779 
9780         final int callingUid = Binder.getCallingUid();
9781         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
9782 
9783         synchronized (mProcLock) {
9784             ProcessRecord proc;
9785             synchronized (mPidsSelfLocked) {
9786                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
9787             }
9788             if (proc != null) {
9789                 mProcessList.fillInProcMemInfoLOSP(proc, outState, clientTargetSdk);
9790             }
9791         }
9792     }
9793 
9794     @Override
getMemoryTrimLevel()9795     public @MemFactor int getMemoryTrimLevel() {
9796         enforceNotIsolatedCaller("getMyMemoryState");
9797         synchronized (this) {
9798             return mAppProfiler.getLastMemoryLevelLocked();
9799         }
9800     }
9801 
setMemFactorOverride(@emFactor int level)9802     void setMemFactorOverride(@MemFactor int level) {
9803         synchronized (this) {
9804             if (level == mAppProfiler.getLastMemoryLevelLocked()) {
9805                 return;
9806             }
9807 
9808             mAppProfiler.setMemFactorOverrideLocked(level);
9809             // Kick off an oom adj update since we forced a mem factor update.
9810             updateOomAdjLocked(OOM_ADJ_REASON_SHELL);
9811         }
9812     }
9813 
9814     /**
9815      * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}.
9816      */
setServiceRestartBackoffEnabled(@onNull String packageName, boolean enable, @NonNull String reason)9817     void setServiceRestartBackoffEnabled(@NonNull String packageName, boolean enable,
9818             @NonNull String reason) {
9819         synchronized (this) {
9820             mServices.setServiceRestartBackoffEnabledLocked(packageName, enable, reason);
9821         }
9822     }
9823 
9824     /**
9825      * @return {@code false} if the given package has been disable from enforcing the service
9826      * restart backoff policy, used by {@link ActivityManagerShellCommand}.
9827      */
isServiceRestartBackoffEnabled(@onNull String packageName)9828     boolean isServiceRestartBackoffEnabled(@NonNull String packageName) {
9829         synchronized (this) {
9830             return mServices.isServiceRestartBackoffEnabledLocked(packageName);
9831         }
9832     }
9833 
9834     @Override
onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)9835     public void onShellCommand(FileDescriptor in, FileDescriptor out,
9836             FileDescriptor err, String[] args, ShellCallback callback,
9837             ResultReceiver resultReceiver) {
9838         final int callingUid = Binder.getCallingUid();
9839         if (callingUid != ROOT_UID && callingUid != Process.SHELL_UID) {
9840             if (resultReceiver != null) {
9841                 resultReceiver.send(-1, null);
9842             }
9843             throw new SecurityException("Shell commands are only callable by root or shell");
9844         }
9845         (new ActivityManagerShellCommand(this, false)).exec(
9846                 this, in, out, err, args, callback, resultReceiver);
9847     }
9848 
9849     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)9850     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9851         PriorityDump.dump(mPriorityDumper, fd, pw, args);
9852     }
9853 
dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, int displayIdFilter, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies)9854     private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti,
9855             boolean dumpAll, String dumpPackage, int displayIdFilter, boolean dumpClient,
9856             boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies) {
9857 
9858         ActiveServices.ServiceDumper sdumper;
9859 
9860         synchronized(this) {
9861             mConstants.dump(pw);
9862             synchronized (mProcLock) {
9863                 mOomAdjuster.dumpCachedAppOptimizerSettings(pw);
9864             }
9865             mOomAdjuster.dumpCacheOomRankerSettings(pw);
9866             pw.println();
9867             if (dumpAll) {
9868                 pw.println("-------------------------------------------------------------------------------");
9869 
9870             }
9871             dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9872             pw.println();
9873             if (dumpAll) {
9874                 pw.println("-------------------------------------------------------------------------------");
9875 
9876             }
9877             mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage);
9878             pw.println();
9879             if (dumpAll) {
9880                 pw.println("-------------------------------------------------------------------------------");
9881             }
9882             dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9883             pw.println();
9884             if (dumpAll) {
9885                 pw.println("-------------------------------------------------------------------------------");
9886             }
9887             if (dumpAll || dumpPackage != null) {
9888                 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9889                 pw.println();
9890                 if (dumpAll) {
9891                     pw.println("-------------------------------------------------------------------------------");
9892                 }
9893             }
9894             mCpHelper.dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9895             pw.println();
9896             if (dumpAll) {
9897                 pw.println("-------------------------------------------------------------------------------");
9898             }
9899             dumpPermissions(fd, pw, args, opti, dumpAll, dumpPackage);
9900             pw.println();
9901             sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9902             if (!dumpClient) {
9903                 if (dumpAll) {
9904                     pw.println("-------------------------------------------------------------------------------");
9905                 }
9906                 sdumper.dumpLocked();
9907             }
9908         }
9909         // We drop the lock here because we can't call dumpWithClient() with the lock held;
9910         // if the caller wants a consistent state for the !dumpClient case, it can call this
9911         // method with the lock held.
9912         if (dumpClient) {
9913             if (dumpAll) {
9914                 pw.println("-------------------------------------------------------------------------------");
9915             }
9916             sdumper.dumpWithClient();
9917         }
9918         if (dumpPackage == null && dumpProxies) {
9919             // Intentionally dropping the lock for this, because dumpBinderProxies() will make many
9920             // outgoing binder calls to retrieve interface descriptors; while that is system code,
9921             // there is nothing preventing an app from overriding this implementation by talking to
9922             // the binder driver directly, and hang up system_server in the process. So, dump
9923             // without locks held, and even then only when there is an unreasonably large number of
9924             // proxies in the first place.
9925             pw.println();
9926             if (dumpAll) {
9927                 pw.println("-------------------------------------------------------------------------------");
9928             }
9929             dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */);
9930         }
9931         synchronized(this) {
9932             pw.println();
9933             if (dumpAll) {
9934                 pw.println("-------------------------------------------------------------------------------");
9935             }
9936             mAtmInternal.dump(DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9937                     dumpPackage, displayIdFilter);
9938             pw.println();
9939             if (dumpAll) {
9940                 pw.println("-------------------------------------------------------------------------------");
9941             }
9942             mAtmInternal.dump(DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9943                     dumpPackage, displayIdFilter);
9944             pw.println();
9945             if (dumpAll) {
9946                 pw.println("-------------------------------------------------------------------------------");
9947             }
9948             mAtmInternal.dump(DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9949                     dumpPackage, displayIdFilter);
9950             if (dumpPackage == null) {
9951                 pw.println();
9952                 if (dumpAll) {
9953                     pw.println("-------------------------------------------------------------------------------");
9954                 }
9955                 mAtmInternal.dump(DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9956                         dumpPackage, displayIdFilter);
9957             }
9958             // Activities section is dumped as part of the Critical priority dump. Exclude the
9959             // section if priority is Normal.
9960             if (!dumpNormalPriority) {
9961                 pw.println();
9962                 if (dumpAll) {
9963                     pw.println("-------------------------------------------------------------------------------");
9964                 }
9965                 mAtmInternal.dump(DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9966                         dumpPackage, displayIdFilter);
9967             }
9968             if (mAssociations.size() > 0) {
9969                 pw.println();
9970                 if (dumpAll) {
9971                     pw.println("-------------------------------------------------------------------------------");
9972                 }
9973                 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9974             }
9975             pw.println();
9976             if (dumpAll) {
9977                 pw.println("-------------------------------------------------------------------------------");
9978                 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage);
9979             }
9980             if (dumpPackage == null) {
9981                 pw.println();
9982                 if (dumpAll) {
9983                     pw.println("-------------------------------------------------------------------------------");
9984                 }
9985                 mOomAdjProfiler.dump(pw);
9986                 pw.println();
9987                 if (dumpAll) {
9988                     pw.println("-------------------------------------------------------------------------------");
9989                 }
9990                 dumpLmkLocked(pw);
9991             }
9992             pw.println();
9993             if (dumpAll) {
9994                 pw.println("-------------------------------------------------------------------------------");
9995             }
9996             synchronized (mProcLock) {
9997                 mProcessList.dumpProcessesLSP(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId);
9998             }
9999             pw.println();
10000             if (dumpAll) {
10001                 pw.println("-------------------------------------------------------------------------------");
10002             }
10003             dumpUsers(pw);
10004 
10005             pw.println();
10006             if (dumpAll) {
10007                 pw.println("-------------------------------------------------------------------------------");
10008             }
10009             mComponentAliasResolver.dump(pw);
10010         }
10011     }
10012 
10013     /**
10014      * Dump the app restriction controller, it's required not to hold the global lock here.
10015      */
dumpAppRestrictionController(PrintWriter pw)10016     private void dumpAppRestrictionController(PrintWriter pw) {
10017         pw.println("-------------------------------------------------------------------------------");
10018         mAppRestrictionController.dump(pw, "");
10019     }
10020 
dumpAppRestrictionController(ProtoOutputStream proto, int uid)10021     void dumpAppRestrictionController(ProtoOutputStream proto, int uid) {
10022         mAppRestrictionController.dumpAsProto(proto, uid);
10023     }
10024 
10025     /**
10026      * Wrapper function to print out debug data filtered by specified arguments.
10027     */
10028     @NeverCompile // Avoid size overhead of debugging code.
doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)10029     private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) {
10030         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
10031 
10032         boolean dumpAll = false;
10033         boolean dumpClient = false;
10034         boolean dumpCheckin = false;
10035         boolean dumpCheckinFormat = false;
10036         boolean dumpNormalPriority = false;
10037         boolean dumpVisibleStacksOnly = false;
10038         boolean dumpFocusedStackOnly = false;
10039         int dumpDisplayId = INVALID_DISPLAY;
10040         String dumpPackage = null;
10041         int dumpUserId = UserHandle.USER_ALL;
10042 
10043         int opti = 0;
10044         while (opti < args.length) {
10045             String opt = args[opti];
10046             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10047                 break;
10048             }
10049             opti++;
10050             if ("-a".equals(opt)) {
10051                 dumpAll = true;
10052             } else if ("-c".equals(opt)) {
10053                 dumpClient = true;
10054             } else if ("-v".equals(opt)) {
10055                 dumpVisibleStacksOnly = true;
10056             } else if ("-f".equals(opt)) {
10057                 dumpFocusedStackOnly = true;
10058             } else if ("-p".equals(opt)) {
10059                 if (opti < args.length) {
10060                     dumpPackage = args[opti];
10061                     opti++;
10062                 } else {
10063                     pw.println("Error: -p option requires package argument");
10064                     return;
10065                 }
10066                 dumpClient = true;
10067             } else if ("--checkin".equals(opt)) {
10068                 dumpCheckin = dumpCheckinFormat = true;
10069             } else if ("-C".equals(opt)) {
10070                 dumpCheckinFormat = true;
10071             } else if ("--normal-priority".equals(opt)) {
10072                 dumpNormalPriority = true;
10073             } else if ("--user".equals(opt)) {
10074                 if (opti < args.length) {
10075                     dumpUserId = UserHandle.parseUserArg(args[opti]);
10076                     if (dumpUserId == UserHandle.USER_CURRENT) {
10077                         dumpUserId = mUserController.getCurrentUserId();
10078                     }
10079                     opti++;
10080                 } else {
10081                     pw.println("Error: --user option requires user id argument");
10082                     return;
10083                 }
10084             } else if ("-d".equals(opt)) {
10085                 if (opti < args.length) {
10086                     dumpDisplayId = Integer.parseInt(args[opti]);
10087                     if (dumpDisplayId == INVALID_DISPLAY) {
10088                         pw.println("Error: -d cannot be used with INVALID_DISPLAY");
10089                         return;
10090                     }
10091                     opti++;
10092                 } else {
10093                     pw.println("Error: -d option requires display argument");
10094                     return;
10095                 }
10096                 dumpClient = true;
10097             } else if ("-h".equals(opt)) {
10098                 ActivityManagerShellCommand.dumpHelp(pw, true);
10099                 return;
10100             } else {
10101                 pw.println("Unknown argument: " + opt + "; use -h for help");
10102                 return;
10103             }
10104         }
10105 
10106         final long origId = Binder.clearCallingIdentity();
10107 
10108         if (useProto) {
10109             final ProtoOutputStream proto = new ProtoOutputStream(fd);
10110             String cmd = opti < args.length ? args[opti] : "";
10111             opti++;
10112 
10113             if ("activities".equals(cmd) || "a".equals(cmd)) {
10114                 // output proto is ActivityManagerServiceDumpActivitiesProto
10115                 mAtmInternal.writeActivitiesToProto(proto);
10116             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10117                 // output proto is ActivityManagerServiceDumpBroadcastsProto
10118                 synchronized (this) {
10119                     writeBroadcastsToProtoLocked(proto);
10120                 }
10121             } else if ("provider".equals(cmd)) {
10122                 String[] newArgs;
10123                 String name;
10124                 if (opti >= args.length) {
10125                     name = null;
10126                     newArgs = EMPTY_STRING_ARRAY;
10127                 } else {
10128                     name = args[opti];
10129                     opti++;
10130                     newArgs = new String[args.length - opti];
10131                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10132                             args.length - opti);
10133                 }
10134                 if (!mCpHelper.dumpProviderProto(fd, pw, name, newArgs)) {
10135                     pw.println("No providers match: " + name);
10136                     pw.println("Use -h for help.");
10137                 }
10138             } else if ("service".equals(cmd)) {
10139                 // output proto is ActivityManagerServiceDumpServicesProto
10140                 mServices.dumpDebug(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10141             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10142                 if (opti < args.length) {
10143                     dumpPackage = args[opti];
10144                     opti++;
10145                 }
10146                 // output proto is ProcessProto
10147                 synchronized (this) {
10148                     synchronized (mProcLock) {
10149                         mProcessList.writeProcessesToProtoLSP(proto, dumpPackage);
10150                     }
10151                 }
10152             } else if ("app-restrictions".equals(cmd)) {
10153                 int uid = Process.INVALID_UID;
10154                 boolean error = false;
10155                 for (int i = 0; i < args.length; i++) {
10156                     if ("--uid".equals(args[i])) {
10157                         if (i + 1 < args.length) {
10158                             try {
10159                                 uid = Integer.parseInt(args[i + 1]);
10160                             } catch (NumberFormatException e) {
10161                                 error = true;
10162                             }
10163                         } else {
10164                             error = true;
10165                         }
10166                         break;
10167                     }
10168                 }
10169                 if (error) {
10170                     pw.println("Invalid --uid argument");
10171                     pw.println("Use -h for help.");
10172                 } else {
10173                     dumpAppRestrictionController(proto, uid);
10174                 }
10175             } else {
10176                 // default option, dump everything, output is ActivityManagerServiceProto
10177                 synchronized (this) {
10178                     long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES);
10179                     mAtmInternal.writeActivitiesToProto(proto);
10180                     proto.end(activityToken);
10181 
10182                     long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS);
10183                     writeBroadcastsToProtoLocked(proto);
10184                     proto.end(broadcastToken);
10185 
10186                     long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES);
10187                     mServices.dumpDebug(proto,
10188                             ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10189                     proto.end(serviceToken);
10190 
10191                     long processToken = proto.start(ActivityManagerServiceProto.PROCESSES);
10192                     synchronized (mProcLock) {
10193                         mProcessList.writeProcessesToProtoLSP(proto, dumpPackage);
10194                     }
10195                     proto.end(processToken);
10196                 }
10197             }
10198             proto.flush();
10199             Binder.restoreCallingIdentity(origId);
10200             return;
10201         }
10202 
10203         int dumpAppId = getAppId(dumpPackage);
10204         boolean more = false;
10205         // Is the caller requesting to dump a particular piece of data?
10206         if (opti < args.length) {
10207             String cmd = args[opti];
10208             opti++;
10209             if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)
10210                     || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd)
10211                     || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd)
10212                     || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)
10213                     || DUMP_TOP_RESUMED_ACTIVITY.equals(cmd)
10214                     || DUMP_VISIBLE_ACTIVITIES.equals(cmd)) {
10215                 mAtmInternal.dump(cmd, fd, pw, args, opti, /* dumpAll= */ true , dumpClient,
10216                         dumpPackage, dumpDisplayId);
10217             } else if ("binder-proxies".equals(cmd)) {
10218                 if (opti >= args.length) {
10219                     dumpBinderProxies(pw, 0 /* minToDump */);
10220                 } else {
10221                     String uid = args[opti];
10222                     opti++;
10223                     // Ensure Binder Proxy Count is as up to date as possible
10224                     System.gc();
10225                     System.runFinalization();
10226                     System.gc();
10227                     pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid)));
10228                 }
10229             } else if ("allowed-associations".equals(cmd)) {
10230                 if (opti < args.length) {
10231                     dumpPackage = args[opti];
10232                     opti++;
10233                 }
10234                 synchronized (this) {
10235                     dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage);
10236                 }
10237             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10238                 if (opti < args.length) {
10239                     dumpPackage = args[opti];
10240                     opti++;
10241                 }
10242                 synchronized (this) {
10243                     dumpBroadcastsLocked(fd, pw, args, opti, /* dumpAll= */ true, dumpPackage);
10244                 }
10245             } else if ("broadcast-stats".equals(cmd)) {
10246                 if (opti < args.length) {
10247                     dumpPackage = args[opti];
10248                     opti++;
10249                 }
10250                 synchronized (this) {
10251                     if (dumpCheckinFormat) {
10252                         dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin,
10253                                 dumpPackage);
10254                     } else {
10255                         dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage);
10256                     }
10257                 }
10258             } else if ("intents".equals(cmd) || "i".equals(cmd)) {
10259                 if (opti < args.length) {
10260                     dumpPackage = args[opti];
10261                     opti++;
10262                 }
10263                 mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage);
10264             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10265                 if (opti < args.length) {
10266                     dumpPackage = args[opti];
10267                     opti++;
10268                 }
10269                 synchronized (this) {
10270                     synchronized (mProcLock) {
10271                         mProcessList.dumpProcessesLSP(
10272                                 fd, pw, args, opti, true, dumpPackage, dumpAppId);
10273                     }
10274                 }
10275             } else if ("oom".equals(cmd) || "o".equals(cmd)) {
10276                 synchronized (this) {
10277                     mProcessList.dumpOomLocked(fd, pw, false, args, opti, true, dumpPackage, true);
10278                 }
10279             } else if ("lmk".equals(cmd)) {
10280                 synchronized (this) {
10281                     dumpLmkLocked(pw);
10282                 }
10283             } else if ("lru".equals(cmd)) {
10284                 synchronized (this) {
10285                     mProcessList.dumpLruLocked(pw, dumpPackage, null);
10286                 }
10287             } else if ("permissions".equals(cmd) || "perm".equals(cmd)) {
10288                 dumpPermissions(fd, pw, args, opti, true, dumpPackage);
10289             } else if ("provider".equals(cmd)) {
10290                 String[] newArgs;
10291                 String name;
10292                 if (opti >= args.length) {
10293                     name = null;
10294                     newArgs = EMPTY_STRING_ARRAY;
10295                 } else {
10296                     name = args[opti];
10297                     opti++;
10298                     newArgs = new String[args.length - opti];
10299                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
10300                 }
10301                 if (!mCpHelper.dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
10302                     pw.println("No providers match: " + name);
10303                     pw.println("Use -h for help.");
10304                 }
10305             } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
10306                 synchronized (this) {
10307                     mCpHelper.dumpProvidersLocked(fd, pw, args, opti, true, dumpPackage);
10308                 }
10309             } else if ("service".equals(cmd)) {
10310                 String[] newArgs;
10311                 String name;
10312                 if (opti >= args.length) {
10313                     name = null;
10314                     newArgs = EMPTY_STRING_ARRAY;
10315                 } else {
10316                     name = args[opti];
10317                     opti++;
10318                     newArgs = new String[args.length - opti];
10319                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10320                             args.length - opti);
10321                 }
10322                 int[] users = dumpUserId == UserHandle.USER_ALL ? null : new int[] { dumpUserId };
10323                 if (!mServices.dumpService(fd, pw, name, users, newArgs, 0, dumpAll)) {
10324                     pw.println("No services match: " + name);
10325                     pw.println("Use -h for help.");
10326                 }
10327             } else if ("package".equals(cmd)) {
10328                 String[] newArgs;
10329                 if (opti >= args.length) {
10330                     pw.println("package: no package name specified");
10331                     pw.println("Use -h for help.");
10332                 } else {
10333                     dumpPackage = args[opti];
10334                     opti++;
10335                     newArgs = new String[args.length - opti];
10336                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10337                             args.length - opti);
10338                     args = newArgs;
10339                     opti = 0;
10340                     more = true;
10341                 }
10342             } else if ("associations".equals(cmd) || "as".equals(cmd)) {
10343                 synchronized (this) {
10344                     dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage);
10345                 }
10346             } else if ("settings".equals(cmd)) {
10347                 synchronized (this) {
10348                     mConstants.dump(pw);
10349                 }
10350                 synchronized (mProcLock) {
10351                     mOomAdjuster.dumpCachedAppOptimizerSettings(pw);
10352                     mOomAdjuster.dumpCacheOomRankerSettings(pw);
10353                 }
10354             } else if ("services".equals(cmd) || "s".equals(cmd)) {
10355                 if (dumpClient) {
10356                     ActiveServices.ServiceDumper dumper;
10357                     synchronized (this) {
10358                         dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10359                                 dumpPackage);
10360                     }
10361                     dumper.dumpWithClient();
10362                 } else {
10363                     synchronized (this) {
10364                         mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10365                                 dumpPackage).dumpLocked();
10366                     }
10367                 }
10368             } else if ("locks".equals(cmd)) {
10369                 LockGuard.dump(fd, pw, args);
10370             } else if ("users".equals(cmd)) {
10371                 dumpUsers(pw);
10372             } else if ("exit-info".equals(cmd)) {
10373                 if (opti < args.length) {
10374                     dumpPackage = args[opti];
10375                     opti++;
10376                 }
10377                 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage);
10378             } else if ("component-alias".equals(cmd)) {
10379                 mComponentAliasResolver.dump(pw);
10380             } else {
10381                 // Dumping a single activity?
10382                 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll,
10383                         dumpVisibleStacksOnly, dumpFocusedStackOnly, dumpDisplayId, dumpUserId)) {
10384                     ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true);
10385                     int res = shell.exec(this, null, fd, null, args, null,
10386                             new ResultReceiver(null));
10387                     if (res < 0) {
10388                         pw.println("Bad activity command, or no activities match: " + cmd);
10389                         pw.println("Use -h for help.");
10390                     }
10391                 }
10392             }
10393             if (!more) {
10394                 Binder.restoreCallingIdentity(origId);
10395                 return;
10396             }
10397         }
10398 
10399         // No piece of data specified, dump everything.
10400         if (dumpCheckinFormat) {
10401             dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage);
10402         } else {
10403             if (dumpClient) {
10404                 // dumpEverything() will take the lock when needed, and momentarily drop
10405                 // it for dumping client state.
10406                 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpDisplayId,
10407                         dumpClient, dumpNormalPriority, dumpAppId, /* dumpProxies= */ true);
10408             } else {
10409                 // Take the lock here, so we get a consistent state for the entire dump;
10410                 // dumpEverything() will take the lock as well, which is fine for everything
10411                 // except dumping proxies, which can take a long time; exclude them.
10412                 synchronized(this) {
10413                     dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpDisplayId,
10414                             dumpClient, dumpNormalPriority, dumpAppId, /* dumpProxies= */ false);
10415                 }
10416             }
10417             if (dumpAll) {
10418                 dumpAppRestrictionController(pw);
10419             }
10420         }
10421         Binder.restoreCallingIdentity(origId);
10422     }
10423 
dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)10424     void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10425             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
10426         pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)");
10427 
10428         int dumpUid = 0;
10429         if (dumpPackage != null) {
10430             IPackageManager pm = AppGlobals.getPackageManager();
10431             try {
10432                 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0);
10433             } catch (RemoteException e) {
10434             }
10435         }
10436 
10437         boolean printedAnything = false;
10438 
10439         final long now = SystemClock.uptimeMillis();
10440 
10441         for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
10442             ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
10443                     = mAssociations.valueAt(i1);
10444             for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
10445                 SparseArray<ArrayMap<String, Association>> sourceUids
10446                         = targetComponents.valueAt(i2);
10447                 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) {
10448                     ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3);
10449                     for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
10450                         Association ass = sourceProcesses.valueAt(i4);
10451                         if (dumpPackage != null) {
10452                             if (!ass.mTargetComponent.getPackageName().equals(dumpPackage)
10453                                     && UserHandle.getAppId(ass.mSourceUid) != dumpUid) {
10454                                 continue;
10455                             }
10456                         }
10457                         printedAnything = true;
10458                         pw.print("  ");
10459                         pw.print(ass.mTargetProcess);
10460                         pw.print("/");
10461                         UserHandle.formatUid(pw, ass.mTargetUid);
10462                         pw.print(" <- ");
10463                         pw.print(ass.mSourceProcess);
10464                         pw.print("/");
10465                         UserHandle.formatUid(pw, ass.mSourceUid);
10466                         pw.println();
10467                         pw.print("    via ");
10468                         pw.print(ass.mTargetComponent.flattenToShortString());
10469                         pw.println();
10470                         pw.print("    ");
10471                         long dur = ass.mTime;
10472                         if (ass.mNesting > 0) {
10473                             dur += now - ass.mStartTime;
10474                         }
10475                         TimeUtils.formatDuration(dur, pw);
10476                         pw.print(" (");
10477                         pw.print(ass.mCount);
10478                         pw.print(" times)");
10479                         pw.print("  ");
10480                         for (int i=0; i<ass.mStateTimes.length; i++) {
10481                             long amt = ass.mStateTimes[i];
10482                             if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
10483                                 amt += now - ass.mLastStateUptime;
10484                             }
10485                             if (amt != 0) {
10486                                 pw.print(" ");
10487                                 pw.print(ProcessList.makeProcStateString(
10488                                             i + ActivityManager.MIN_PROCESS_STATE));
10489                                 pw.print("=");
10490                                 TimeUtils.formatDuration(amt, pw);
10491                                 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
10492                                     pw.print("*");
10493                                 }
10494                             }
10495                         }
10496                         pw.println();
10497                         if (ass.mNesting > 0) {
10498                             pw.print("    Currently active: ");
10499                             TimeUtils.formatDuration(now - ass.mStartTime, pw);
10500                             pw.println();
10501                         }
10502                     }
10503                 }
10504             }
10505 
10506         }
10507 
10508         if (!printedAnything) {
10509             pw.println("  (nothing)");
10510         }
10511     }
10512 
getAppId(String dumpPackage)10513     int getAppId(String dumpPackage) {
10514         if (dumpPackage != null) {
10515             try {
10516                 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
10517                         dumpPackage, 0);
10518                 return UserHandle.getAppId(info.uid);
10519             } catch (NameNotFoundException e) {
10520                 e.printStackTrace();
10521             }
10522         }
10523         return -1;
10524     }
10525 
dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)10526     void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) {
10527         final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50);
10528 
10529         pw.println(header);
10530         for (int i = 0; i < proxyCounts.length; i++) {
10531             pw.println("    #" + (i + 1) + ": " + proxyCounts[i]);
10532         }
10533     }
10534 
dumpBinderProxiesCounts(PrintWriter pw, String header)10535     boolean dumpBinderProxiesCounts(PrintWriter pw, String header) {
10536         SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
10537         if(counts != null) {
10538             pw.println(header);
10539             for (int i = 0; i < counts.size(); i++) {
10540                 final int uid = counts.keyAt(i);
10541                 final int binderCount = counts.valueAt(i);
10542                 pw.print("    UID ");
10543                 pw.print(uid);
10544                 pw.print(", binder count = ");
10545                 pw.print(binderCount);
10546                 pw.print(", package(s)= ");
10547                 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid);
10548                 if (pkgNames != null) {
10549                     for (int j = 0; j < pkgNames.length; j++) {
10550                         pw.print(pkgNames[j]);
10551                         pw.print("; ");
10552                     }
10553                 } else {
10554                     pw.print("NO PACKAGE NAME FOUND");
10555                 }
10556                 pw.println();
10557             }
10558             return true;
10559         }
10560         return false;
10561     }
10562 
dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)10563     void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) {
10564         pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)");
10565         final int proxyCount = BinderProxy.getProxyCount();
10566         if (proxyCount >= minCountToDumpInterfaces) {
10567             dumpBinderProxyInterfaceCounts(pw,
10568                     "Top proxy interface names held by SYSTEM");
10569         } else {
10570             pw.print("Not dumping proxy interface counts because size ("
10571                     + Integer.toString(proxyCount) + ") looks reasonable");
10572             pw.println();
10573         }
10574         dumpBinderProxiesCounts(pw,
10575                 "  Counts of Binder Proxies held by SYSTEM");
10576     }
10577 
10578     @GuardedBy("this")
dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep)10579     boolean dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep) {
10580         final int size = mActiveInstrumentation.size();
10581         if (size > 0) {
10582             boolean printed = false;
10583             for (int i = 0; i < size; i++) {
10584                 ActiveInstrumentation ai = mActiveInstrumentation.get(i);
10585                 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
10586                         && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
10587                     continue;
10588                 }
10589                 if (!printed) {
10590                     if (needSep) {
10591                         pw.println();
10592                     }
10593                     pw.println("  Active instrumentation:");
10594                     printed = true;
10595                     needSep = true;
10596                 }
10597                 pw.print("    Instrumentation #"); pw.print(i); pw.print(": ");
10598                 pw.println(ai);
10599                 ai.dump(pw, "      ");
10600             }
10601         }
10602         return needSep;
10603     }
10604 
10605     @NeverCompile // Avoid size overhead of debugging code.
10606     @GuardedBy({"this", "mProcLock"})
dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep)10607     void dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw,
10608             boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep) {
10609         if (dumpAll || dumpPackage != null) {
10610             final SparseArray<ProcessRecord> pidToProcess = new SparseArray<>();
10611             synchronized (mPidsSelfLocked) {
10612                 boolean printed = false;
10613                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
10614                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
10615                     pidToProcess.put(r.getPid(), r);
10616                     if (dumpPackage != null && !r.getPkgList().containsKey(dumpPackage)) {
10617                         continue;
10618                     }
10619                     if (!printed) {
10620                         if (needSep) pw.println();
10621                         needSep = true;
10622                         pw.println("  PID mappings:");
10623                         printed = true;
10624                     }
10625                     pw.print("    PID #"); pw.print(mPidsSelfLocked.keyAt(i));
10626                     pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
10627                 }
10628             }
10629 
10630             synchronized (sActiveProcessInfoSelfLocked) {
10631                 boolean printed = false;
10632                 for (int i = 0, size = sActiveProcessInfoSelfLocked.size(); i < size; i++) {
10633                     ProcessInfo info = sActiveProcessInfoSelfLocked.valueAt(i);
10634                     ProcessRecord r = pidToProcess.get(sActiveProcessInfoSelfLocked.keyAt(i));
10635                     if (r != null && dumpPackage != null
10636                             && !r.getPkgList().containsKey(dumpPackage)) {
10637                         continue;
10638                     }
10639                     if (!printed) {
10640                         if (needSep) pw.println();
10641                         needSep = true;
10642                         pw.println("  Active process infos:");
10643                         printed = true;
10644                     }
10645                     pw.print("    Pinfo PID #"); pw.print(sActiveProcessInfoSelfLocked.keyAt(i));
10646                     pw.println(":");
10647                     pw.print("      name="); pw.println(info.name);
10648                     if (info.deniedPermissions != null) {
10649                         for (int j = 0; j < info.deniedPermissions.size(); j++) {
10650                             pw.print("      deny: ");
10651                             pw.println(info.deniedPermissions.valueAt(j));
10652                         }
10653                     }
10654                 }
10655             }
10656         }
10657 
10658         if (dumpAll) {
10659             mPhantomProcessList.dump(pw, "  ");
10660         }
10661 
10662         if (mImportantProcesses.size() > 0) {
10663             synchronized (mPidsSelfLocked) {
10664                 boolean printed = false;
10665                 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) {
10666                     ProcessRecord r = mPidsSelfLocked.get(mImportantProcesses.valueAt(i).pid);
10667                     if (dumpPackage != null && (r == null
10668                             || !r.getPkgList().containsKey(dumpPackage))) {
10669                         continue;
10670                     }
10671                     if (!printed) {
10672                         if (needSep) pw.println();
10673                         needSep = true;
10674                         pw.println("  Foreground Processes:");
10675                         printed = true;
10676                     }
10677                     pw.print("    PID #"); pw.print(mImportantProcesses.keyAt(i));
10678                             pw.print(": "); pw.println(mImportantProcesses.valueAt(i));
10679                 }
10680             }
10681         }
10682 
10683         if (mPersistentStartingProcesses.size() > 0) {
10684             if (needSep) pw.println();
10685             needSep = true;
10686             pw.println("  Persisent processes that are starting:");
10687             dumpProcessList(pw, this, mPersistentStartingProcesses, "    ",
10688                     "Starting Norm", "Restarting PERS", dumpPackage);
10689         }
10690 
10691         if (mProcessList.mRemovedProcesses.size() > 0) {
10692             if (needSep) pw.println();
10693             needSep = true;
10694             pw.println("  Processes that are being removed:");
10695             dumpProcessList(pw, this, mProcessList.mRemovedProcesses, "    ",
10696                     "Removed Norm", "Removed PERS", dumpPackage);
10697         }
10698 
10699         if (mProcessesOnHold.size() > 0) {
10700             if (needSep) pw.println();
10701             needSep = true;
10702             pw.println("  Processes that are on old until the system is ready:");
10703             dumpProcessList(pw, this, mProcessesOnHold, "    ",
10704                     "OnHold Norm", "OnHold PERS", dumpPackage);
10705         }
10706 
10707         needSep = mAppErrors.dumpLPr(fd, pw, needSep, dumpPackage);
10708 
10709         needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep,
10710                 mAppProfiler.getTestPssMode(), mWakefulness.get());
10711 
10712         if (dumpAll && mProcessList.mPendingStarts.size() > 0) {
10713             if (needSep) pw.println();
10714             needSep = true;
10715             pw.println("  mPendingStarts: ");
10716             for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) {
10717                 pw.println("    " + mProcessList.mPendingStarts.keyAt(i) + ": "
10718                         + mProcessList.mPendingStarts.valueAt(i));
10719             }
10720         }
10721         if (dumpAll) {
10722             mUidObserverController.dump(pw, dumpPackage);
10723 
10724             pw.println("  mDeviceIdleAllowlist=" + Arrays.toString(mDeviceIdleAllowlist));
10725             pw.println("  mDeviceIdleExceptIdleAllowlist="
10726                     + Arrays.toString(mDeviceIdleExceptIdleAllowlist));
10727             pw.println("  mDeviceIdleTempAllowlist=" + Arrays.toString(mDeviceIdleTempAllowlist));
10728             if (mPendingTempAllowlist.size() > 0) {
10729                 pw.println("  mPendingTempAllowlist:");
10730                 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) {
10731                     PendingTempAllowlist ptw = mPendingTempAllowlist.valueAt(i);
10732                     pw.print("    ");
10733                     UserHandle.formatUid(pw, ptw.targetUid);
10734                     pw.print(": ");
10735                     TimeUtils.formatDuration(ptw.duration, pw);
10736                     pw.print(" ");
10737                     pw.println(ptw.tag);
10738                     pw.print(" ");
10739                     pw.print(ptw.type);
10740                     pw.print(" ");
10741                     pw.print(ptw.reasonCode);
10742                     pw.print(" ");
10743                     pw.print(ptw.callingUid);
10744                 }
10745             }
10746             pw.println("  mFgsStartTempAllowList:");
10747             final long currentTimeNow = System.currentTimeMillis();
10748             final long elapsedRealtimeNow = SystemClock.elapsedRealtime();
10749             mFgsStartTempAllowList.forEach((uid, entry) -> {
10750                 pw.print("    " + UserHandle.formatUid(uid) + ": ");
10751                 entry.second.dump(pw);
10752                 pw.print(" expiration=");
10753                 // Convert entry.mExpirationTime, which is an elapsed time since boot,
10754                 // to a time since epoch (i.e. System.currentTimeMillis()-based time.)
10755                 final long expirationInCurrentTime =
10756                         currentTimeNow - elapsedRealtimeNow + entry.first;
10757                 TimeUtils.dumpTimeWithDelta(pw, expirationInCurrentTime, currentTimeNow);
10758                 pw.println();
10759             });
10760 
10761             if (!mProcessList.mAppsInBackgroundRestricted.isEmpty()) {
10762                 pw.println("  Processes that are in background restricted:");
10763                 for (int i = 0, size = mProcessList.mAppsInBackgroundRestricted.size();
10764                         i < size; i++) {
10765                     pw.println(String.format("%s #%2d: %s", "    ", i,
10766                             mProcessList.mAppsInBackgroundRestricted.valueAt(i).toString()));
10767                 }
10768             }
10769         }
10770         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
10771                 || mOrigWaitForDebugger) {
10772             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
10773                     || dumpPackage.equals(mOrigDebugApp)) {
10774                 if (needSep) {
10775                     pw.println();
10776                     needSep = false;
10777                 }
10778                 pw.println("  mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
10779                         + " mDebugTransient=" + mDebugTransient
10780                         + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
10781             }
10782         }
10783         synchronized (mAppProfiler.mProfilerLock) {
10784             needSep = mAppProfiler.dumpMemWatchProcessesLPf(pw, needSep);
10785         }
10786         if (mTrackAllocationApp != null) {
10787             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
10788                 if (needSep) {
10789                     pw.println();
10790                     needSep = false;
10791                 }
10792                 pw.println("  mTrackAllocationApp=" + mTrackAllocationApp);
10793             }
10794         }
10795         needSep = mAppProfiler.dumpProfileDataLocked(pw, dumpPackage, needSep);
10796         if (mNativeDebuggingApp != null) {
10797             if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
10798                 if (needSep) {
10799                     pw.println();
10800                     needSep = false;
10801                 }
10802                 pw.println("  mNativeDebuggingApp=" + mNativeDebuggingApp);
10803             }
10804         }
10805         if (dumpPackage == null) {
10806             if (mAlwaysFinishActivities) {
10807                 pw.println("  mAlwaysFinishActivities=" + mAlwaysFinishActivities);
10808             }
10809             if (dumpAll) {
10810                 pw.println("  Total persistent processes: " + numPers);
10811                 pw.println("  mProcessesReady=" + mProcessesReady
10812                         + " mSystemReady=" + mSystemReady
10813                         + " mBooted=" + mBooted
10814                         + " mFactoryTest=" + mFactoryTest);
10815                 pw.println("  mBooting=" + mBooting
10816                         + " mCallFinishBooting=" + mCallFinishBooting
10817                         + " mBootAnimationComplete=" + mBootAnimationComplete);
10818                 pw.print("  mLastPowerCheckUptime=");
10819                         TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
10820                         pw.println("");
10821                 mOomAdjuster.dumpSequenceNumbersLocked(pw);
10822                 mOomAdjuster.dumpProcCountsLocked(pw);
10823                 mAppProfiler.dumpMemoryLevelsLocked(pw);
10824                 long now = SystemClock.uptimeMillis();
10825                 pw.print("  mLastIdleTime=");
10826                         TimeUtils.formatDuration(now, mLastIdleTime, pw);
10827                         pw.print(" mLowRamSinceLastIdle=");
10828                         TimeUtils.formatDuration(
10829                                 mAppProfiler.getLowRamTimeSinceIdleLPr(now), pw);
10830                         pw.println();
10831 
10832                 pw.println();
10833                 pw.println("  ServiceManager statistics:");
10834                 ServiceManager.sStatLogger.dump(pw, "    ");
10835                 pw.println();
10836             }
10837         }
10838         pw.println("  mForceBackgroundCheck=" + mForceBackgroundCheck);
10839     }
10840 
dumpUsers(PrintWriter pw)10841     private void dumpUsers(PrintWriter pw) {
10842         pw.println("ACTIVITY MANAGER USERS (dumpsys activity users)");
10843         mUserController.dump(pw);
10844     }
10845 
10846     @GuardedBy({"this", "mProcLock"})
writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, int dumpAppId, int numPers)10847     void writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage,
10848             int dumpAppId, int numPers) {
10849         for (int i = 0, size = mActiveInstrumentation.size(); i < size; i++) {
10850             ActiveInstrumentation ai = mActiveInstrumentation.get(i);
10851             if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
10852                     && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
10853                 continue;
10854             }
10855             ai.dumpDebug(proto,
10856                     ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS);
10857         }
10858 
10859         mUidObserverController.dumpValidateUidsProto(proto, dumpPackage, dumpAppId,
10860                 ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS);
10861 
10862         if (dumpPackage != null) {
10863             synchronized (mPidsSelfLocked) {
10864                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
10865                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
10866                     if (!r.getPkgList().containsKey(dumpPackage)) {
10867                         continue;
10868                     }
10869                     r.dumpDebug(proto,
10870                             ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED);
10871                 }
10872             }
10873         }
10874 
10875         if (mImportantProcesses.size() > 0) {
10876             synchronized (mPidsSelfLocked) {
10877                 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) {
10878                     ImportanceToken it = mImportantProcesses.valueAt(i);
10879                     ProcessRecord r = mPidsSelfLocked.get(it.pid);
10880                     if (dumpPackage != null && (r == null
10881                             || !r.getPkgList().containsKey(dumpPackage))) {
10882                         continue;
10883                     }
10884                     it.dumpDebug(proto,
10885                             ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS);
10886                 }
10887             }
10888         }
10889 
10890         for (int i = 0, size = mPersistentStartingProcesses.size(); i < size; i++) {
10891             ProcessRecord r = mPersistentStartingProcesses.get(i);
10892             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10893                 continue;
10894             }
10895             r.dumpDebug(proto,
10896                     ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS);
10897         }
10898 
10899         for (int i = 0, size = mProcessList.mRemovedProcesses.size(); i < size; i++) {
10900             ProcessRecord r = mProcessList.mRemovedProcesses.get(i);
10901             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10902                 continue;
10903             }
10904             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS);
10905         }
10906 
10907         for (int i = 0, size = mProcessesOnHold.size(); i < size; i++) {
10908             ProcessRecord r = mProcessesOnHold.get(i);
10909             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10910                 continue;
10911             }
10912             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS);
10913         }
10914 
10915         synchronized (mAppProfiler.mProfilerLock) {
10916             mAppProfiler.writeProcessesToGcToProto(proto,
10917                     ActivityManagerServiceDumpProcessesProto.GC_PROCS,
10918                     dumpPackage);
10919         }
10920         mAppErrors.dumpDebugLPr(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS,
10921                 dumpPackage);
10922         mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness.get(),
10923                 mAppProfiler.getTestPssMode());
10924 
10925         if (dumpPackage == null) {
10926             mUserController.dumpDebug(proto,
10927             ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER);
10928         }
10929 
10930         mUidObserverController.dumpDebug(proto, dumpPackage);
10931 
10932         for (int v : mDeviceIdleAllowlist) {
10933             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v);
10934         }
10935 
10936         for (int v : mDeviceIdleTempAllowlist) {
10937             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v);
10938         }
10939 
10940         if (mPendingTempAllowlist.size() > 0) {
10941             for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) {
10942                 mPendingTempAllowlist.valueAt(i).dumpDebug(proto,
10943                         ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST);
10944             }
10945         }
10946 
10947         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
10948                 || mOrigWaitForDebugger) {
10949             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
10950                     || dumpPackage.equals(mOrigDebugApp)) {
10951                 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG);
10952                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp);
10953                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp);
10954                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient);
10955                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger);
10956                 proto.end(debugAppToken);
10957             }
10958         }
10959 
10960         synchronized (mAppProfiler.mProfilerLock) {
10961             mAppProfiler.writeMemWatchProcessToProtoLPf(proto);
10962         }
10963 
10964         if (mTrackAllocationApp != null) {
10965             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
10966                 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP,
10967                         mTrackAllocationApp);
10968             }
10969         }
10970 
10971         mAppProfiler.writeProfileDataToProtoLocked(proto, dumpPackage);
10972 
10973         if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
10974             proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp);
10975         }
10976 
10977         if (dumpPackage == null) {
10978             proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities);
10979             proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers);
10980             proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady);
10981             proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady);
10982             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted);
10983             proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest);
10984             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting);
10985             proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting);
10986             proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete);
10987             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime);
10988             mOomAdjuster.dumpProcessListVariablesLocked(proto);
10989             mAppProfiler.writeMemoryLevelsToProtoLocked(proto);
10990             long now = SystemClock.uptimeMillis();
10991             ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now);
10992             proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS,
10993                     mAppProfiler.getLowRamTimeSinceIdleLPr(now));
10994         }
10995     }
10996 
reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)10997     private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) {
10998         Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj);
10999         if (cnt != null) {
11000             pw.println("    kills at or below oom_adj " + oom_adj + ": " + cnt);
11001             return true;
11002         }
11003         return false;
11004     }
11005 
dumpLmkLocked(PrintWriter pw)11006     boolean dumpLmkLocked(PrintWriter pw) {
11007         pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)");
11008         Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ,
11009                 ProcessList.UNKNOWN_ADJ);
11010         if (cnt == null) {
11011             return false;
11012         }
11013         pw.println("  Total number of kills: " + cnt);
11014 
11015         return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) &&
11016                 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) &&
11017                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) &&
11018                 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) &&
11019                 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) &&
11020                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) &&
11021                 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) &&
11022                 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) &&
11023                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) &&
11024                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) &&
11025                 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) &&
11026                 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ);
11027     }
11028 
11029     public static class ItemMatcher {
11030         ArrayList<ComponentName> components;
11031         ArrayList<String> strings;
11032         ArrayList<Integer> objects;
11033         boolean all;
11034 
ItemMatcher()11035         public ItemMatcher() {
11036             all = true;
11037         }
11038 
build(String name)11039         public void build(String name) {
11040             ComponentName componentName = ComponentName.unflattenFromString(name);
11041             if (componentName != null) {
11042                 if (components == null) {
11043                     components = new ArrayList<ComponentName>();
11044                 }
11045                 components.add(componentName);
11046                 all = false;
11047             } else {
11048                 int objectId = 0;
11049                 // Not a '/' separated full component name; maybe an object ID?
11050                 try {
11051                     objectId = Integer.parseInt(name, 16);
11052                     if (objects == null) {
11053                         objects = new ArrayList<Integer>();
11054                     }
11055                     objects.add(objectId);
11056                     all = false;
11057                 } catch (RuntimeException e) {
11058                     // Not an integer; just do string match.
11059                     if (strings == null) {
11060                         strings = new ArrayList<String>();
11061                     }
11062                     strings.add(name);
11063                     all = false;
11064                 }
11065             }
11066         }
11067 
build(String[] args, int opti)11068         public int build(String[] args, int opti) {
11069             for (; opti<args.length; opti++) {
11070                 String name = args[opti];
11071                 if ("--".equals(name)) {
11072                     return opti+1;
11073                 }
11074                 build(name);
11075             }
11076             return opti;
11077         }
11078 
match(Object object, ComponentName comp)11079         public boolean match(Object object, ComponentName comp) {
11080             if (all) {
11081                 return true;
11082             }
11083             if (components != null) {
11084                 for (int i=0; i<components.size(); i++) {
11085                     if (components.get(i).equals(comp)) {
11086                         return true;
11087                     }
11088                 }
11089             }
11090             if (objects != null) {
11091                 for (int i=0; i<objects.size(); i++) {
11092                     if (System.identityHashCode(object) == objects.get(i)) {
11093                         return true;
11094                     }
11095                 }
11096             }
11097             if (strings != null) {
11098                 String flat = comp.flattenToString();
11099                 for (int i=0; i<strings.size(); i++) {
11100                     if (flat.contains(strings.get(i))) {
11101                         return true;
11102                     }
11103                 }
11104             }
11105             return false;
11106         }
11107     }
11108 
writeBroadcastsToProtoLocked(ProtoOutputStream proto)11109     void writeBroadcastsToProtoLocked(ProtoOutputStream proto) {
11110         if (mRegisteredReceivers.size() > 0) {
11111             Iterator it = mRegisteredReceivers.values().iterator();
11112             while (it.hasNext()) {
11113                 ReceiverList r = (ReceiverList)it.next();
11114                 r.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST);
11115             }
11116         }
11117         mReceiverResolver.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER);
11118         for (BroadcastQueue q : mBroadcastQueues) {
11119             q.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE);
11120         }
11121         for (int user=0; user<mStickyBroadcasts.size(); user++) {
11122             long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS);
11123             proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user));
11124             for (Map.Entry<String, ArrayList<StickyBroadcast>> ent
11125                     : mStickyBroadcasts.valueAt(user).entrySet()) {
11126                 long actionToken = proto.start(StickyBroadcastProto.ACTIONS);
11127                 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey());
11128                 for (StickyBroadcast broadcast : ent.getValue()) {
11129                     broadcast.intent.dumpDebug(proto, StickyBroadcastProto.StickyAction.INTENTS,
11130                             false, true, true, false);
11131                 }
11132                 proto.end(actionToken);
11133             }
11134             proto.end(token);
11135         }
11136 
11137         long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER);
11138         proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString());
11139         mHandler.getLooper().dumpDebug(proto,
11140             ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER);
11141         proto.end(handlerToken);
11142     }
11143 
dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11144     void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11145             int opti, boolean dumpAll, String dumpPackage) {
11146         pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)");
11147         boolean printed = false;
11148         if (mAllowedAssociations != null) {
11149             for (int i = 0; i < mAllowedAssociations.size(); i++) {
11150                 final String pkg = mAllowedAssociations.keyAt(i);
11151                 final ArraySet<String> asc =
11152                         mAllowedAssociations.valueAt(i).getAllowedPackageAssociations();
11153                 if (!printed) {
11154                     pw.println("  Allowed associations (by restricted package):");
11155                     printed = true;
11156                 }
11157                 pw.print("  * ");
11158                 pw.print(pkg);
11159                 pw.println(":");
11160                 for (int j = 0; j < asc.size(); j++) {
11161                     if (dumpPackage == null || pkg.equals(dumpPackage)
11162                             || asc.valueAt(j).equals(dumpPackage)) {
11163                         pw.print("      Allow: ");
11164                         pw.println(asc.valueAt(j));
11165                     }
11166                 }
11167                 if (mAllowedAssociations.valueAt(i).isDebuggable()) {
11168                     pw.println("      (debuggable)");
11169                 }
11170             }
11171         }
11172         if (!printed) {
11173             pw.println("  (No association restrictions)");
11174         }
11175     }
11176 
11177     @NeverCompile
dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11178     void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11179             int opti, boolean dumpAll, String dumpPackage) {
11180         boolean dumpConstants = true;
11181         boolean dumpHistory = true;
11182         boolean needSep = false;
11183         boolean onlyHistory = false;
11184         boolean printedAnything = false;
11185         boolean onlyReceivers = false;
11186         int filteredUid = Process.INVALID_UID;
11187 
11188         if ("history".equals(dumpPackage)) {
11189             if (opti < args.length && "-s".equals(args[opti])) {
11190                 dumpAll = false;
11191             }
11192             onlyHistory = true;
11193             dumpPackage = null;
11194         }
11195         if ("receivers".equals(dumpPackage)) {
11196             onlyReceivers = true;
11197             dumpPackage = null;
11198             if (opti + 2 <= args.length) {
11199                 for (int i = opti; i < args.length; i++) {
11200                     String arg = args[i];
11201                     switch (arg) {
11202                         case "--uid":
11203                             filteredUid = getIntArg(pw, args, ++i, Process.INVALID_UID);
11204                             if (filteredUid == Process.INVALID_UID) {
11205                                 return;
11206                             }
11207                             break;
11208                         default:
11209                             pw.printf("Invalid argument at index %d: %s\n", i, arg);
11210                             return;
11211                     }
11212                 }
11213             }
11214         }
11215         if (DEBUG_BROADCAST) {
11216             Slogf.d(TAG_BROADCAST, "dumpBroadcastsLocked(): dumpPackage=%s, onlyHistory=%b, "
11217                     + "onlyReceivers=%b, filteredUid=%d", dumpPackage, onlyHistory, onlyReceivers,
11218                     filteredUid);
11219         }
11220 
11221         pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
11222         if (!onlyHistory && dumpAll) {
11223             if (mRegisteredReceivers.size() > 0) {
11224                 boolean printed = false;
11225                 Iterator it = mRegisteredReceivers.values().iterator();
11226                 while (it.hasNext()) {
11227                     ReceiverList r = (ReceiverList)it.next();
11228                     if (dumpPackage != null && (r.app == null ||
11229                             !dumpPackage.equals(r.app.info.packageName))) {
11230                         continue;
11231                     }
11232                     if (filteredUid != Process.INVALID_UID && filteredUid != r.app.uid) {
11233                         if (DEBUG_BROADCAST) {
11234                             Slogf.v(TAG_BROADCAST, "dumpBroadcastsLocked(): skipping receiver whose"
11235                                     + " uid (%d) is not %d: %s", r.app.uid, filteredUid, r.app);
11236                         }
11237                         continue;
11238                     }
11239                     if (!printed) {
11240                         pw.println("  Registered Receivers:");
11241                         needSep = true;
11242                         printed = true;
11243                         printedAnything = true;
11244                     }
11245                     pw.print("  * "); pw.println(r);
11246                     r.dump(pw, "    ");
11247                 }
11248             } else {
11249                 if (onlyReceivers) {
11250                     pw.println("  (no registered receivers)");
11251                 }
11252             }
11253 
11254             if (!onlyReceivers) {
11255                 if (mReceiverResolver.dump(pw, needSep
11256                         ? "\n  Receiver Resolver Table:" : "  Receiver Resolver Table:",
11257                         "    ", dumpPackage, false, false)) {
11258                     needSep = true;
11259                     printedAnything = true;
11260                 }
11261             }
11262         }
11263 
11264         if (!onlyReceivers) {
11265             for (BroadcastQueue q : mBroadcastQueues) {
11266                 needSep = q.dumpLocked(fd, pw, args, opti,
11267                         dumpConstants, dumpHistory, dumpAll, dumpPackage, needSep);
11268                 printedAnything |= needSep;
11269             }
11270         }
11271 
11272         needSep = true;
11273 
11274         if (!onlyHistory && !onlyReceivers && mStickyBroadcasts != null && dumpPackage == null) {
11275             for (int user=0; user<mStickyBroadcasts.size(); user++) {
11276                 if (needSep) {
11277                     pw.println();
11278                 }
11279                 needSep = true;
11280                 printedAnything = true;
11281                 pw.print("  Sticky broadcasts for user ");
11282                         pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
11283                 StringBuilder sb = new StringBuilder(128);
11284                 for (Map.Entry<String, ArrayList<StickyBroadcast>> ent
11285                         : mStickyBroadcasts.valueAt(user).entrySet()) {
11286                     pw.print("  * Sticky action "); pw.print(ent.getKey());
11287                     if (dumpAll) {
11288                         pw.println(":");
11289                         ArrayList<StickyBroadcast> broadcasts = ent.getValue();
11290                         final int N = broadcasts.size();
11291                         for (int i=0; i<N; i++) {
11292                             final Intent intent = broadcasts.get(i).intent;
11293                             final boolean deferUntilActive = broadcasts.get(i).deferUntilActive;
11294                             sb.setLength(0);
11295                             sb.append("    Intent: ");
11296                             intent.toShortString(sb, false, true, false, false);
11297                             pw.print(sb);
11298                             if (deferUntilActive) {
11299                                 pw.print(" [D]");
11300                             }
11301                             pw.println();
11302                             pw.print("      originalCallingUid: ");
11303                             pw.println(broadcasts.get(i).originalCallingUid);
11304                             pw.println();
11305                             Bundle bundle = intent.getExtras();
11306                             if (bundle != null) {
11307                                 pw.print("      extras: ");
11308                                 pw.println(bundle);
11309                             }
11310                         }
11311                     } else {
11312                         pw.println("");
11313                     }
11314                 }
11315             }
11316         }
11317 
11318         if (!onlyHistory && !onlyReceivers && dumpAll) {
11319             pw.println();
11320             for (BroadcastQueue queue : mBroadcastQueues) {
11321                 pw.println("  Queue " + queue.toString() + ": " + queue.describeStateLocked());
11322             }
11323             pw.println("  mHandler:");
11324             mHandler.dump(new PrintWriterPrinter(pw), "    ");
11325             needSep = true;
11326             printedAnything = true;
11327         }
11328 
11329         if (!printedAnything) {
11330             pw.println("  (nothing)");
11331         }
11332     }
11333 
11334     @NeverCompile
dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11335     void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11336             int opti, boolean dumpAll, String dumpPackage) {
11337         if (mCurBroadcastStats == null) {
11338             return;
11339         }
11340 
11341         pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)");
11342         final long now = SystemClock.elapsedRealtime();
11343         if (mLastBroadcastStats != null) {
11344             pw.print("  Last stats (from ");
11345             TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw);
11346             pw.print(" to ");
11347             TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw);
11348             pw.print(", ");
11349             TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime
11350                     - mLastBroadcastStats.mStartUptime, pw);
11351             pw.println(" uptime):");
11352             if (!mLastBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
11353                 pw.println("    (nothing)");
11354             }
11355             pw.println();
11356         }
11357         pw.print("  Current stats (from ");
11358         TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw);
11359         pw.print(" to now, ");
11360         TimeUtils.formatDuration(SystemClock.uptimeMillis()
11361                 - mCurBroadcastStats.mStartUptime, pw);
11362         pw.println(" uptime):");
11363         if (!mCurBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
11364             pw.println("    (nothing)");
11365         }
11366     }
11367 
11368     @NeverCompile
dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)11369     void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11370             int opti, boolean fullCheckin, String dumpPackage) {
11371         if (mCurBroadcastStats == null) {
11372             return;
11373         }
11374 
11375         if (mLastBroadcastStats != null) {
11376             mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage);
11377             if (fullCheckin) {
11378                 mLastBroadcastStats = null;
11379                 return;
11380             }
11381         }
11382         mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage);
11383         if (fullCheckin) {
11384             mCurBroadcastStats = null;
11385         }
11386     }
11387 
dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11388     void dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args,
11389             int opti, boolean dumpAll, String dumpPackage) {
11390 
11391         pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)");
11392 
11393         mUgmInternal.dump(pw, dumpAll, dumpPackage);
11394     }
11395 
dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)11396     private static int dumpProcessList(PrintWriter pw,
11397             ActivityManagerService service, List list,
11398             String prefix, String normalLabel, String persistentLabel,
11399             String dumpPackage) {
11400         int numPers = 0;
11401         for (int i = list.size() - 1; i >= 0; i--) {
11402             ProcessRecord r = (ProcessRecord) list.get(i);
11403             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11404                 continue;
11405             }
11406             pw.println(String.format("%s%s #%2d: %s",
11407                     prefix, (r.isPersistent() ? persistentLabel : normalLabel),
11408                     i, r.toString()));
11409             if (r.isPersistent()) {
11410                 numPers++;
11411             }
11412         }
11413         return numPers;
11414     }
11415 
collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)11416     ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs,
11417             String[] args) {
11418         synchronized (mProcLock) {
11419             return mProcessList.collectProcessesLOSP(start, allPkgs, args);
11420         }
11421     }
11422 
dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)11423     final void dumpGraphicsHardwareUsage(FileDescriptor fd,
11424             PrintWriter pw, String[] args) {
11425         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
11426         if (procs == null) {
11427             pw.println("No process found for: " + args[0]);
11428             return;
11429         }
11430 
11431         long uptime = SystemClock.uptimeMillis();
11432         long realtime = SystemClock.elapsedRealtime();
11433         pw.println("Applications Graphics Acceleration Info:");
11434         pw.println("Uptime: " + uptime + " Realtime: " + realtime);
11435 
11436         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
11437             ProcessRecord r = procs.get(i);
11438             final int pid = r.getPid();
11439             final IApplicationThread thread = r.getThread();
11440             if (thread != null) {
11441                 pw.println("\n** Graphics info for pid " + pid + " [" + r.processName + "] **");
11442                 pw.flush();
11443                 try {
11444                     TransferPipe tp = new TransferPipe();
11445                     try {
11446                         thread.dumpGfxInfo(tp.getWriteFd(), args);
11447                         tp.go(fd);
11448                     } finally {
11449                         tp.kill();
11450                     }
11451                 } catch (IOException e) {
11452                     pw.println("Failure while dumping the app: " + r);
11453                     pw.flush();
11454                 } catch (RemoteException e) {
11455                     pw.println("Got a RemoteException while dumping the app " + r);
11456                     pw.flush();
11457                 }
11458             }
11459         }
11460     }
11461 
dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args)11462     final void dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args) {
11463         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
11464         if (procs == null) {
11465             pw.println("No process found for: " + args[0]);
11466             return;
11467         }
11468 
11469         pw.println("Per-process Binder Cache Contents");
11470 
11471         for (int i = procs.size() - 1; i >= 0; i--) {
11472             ProcessRecord r = procs.get(i);
11473             final int pid = r.getPid();
11474             final IApplicationThread thread = r.getThread();
11475             if (thread != null) {
11476                 pw.println("\n\n** Cache info for pid " + pid + " [" + r.processName + "] **");
11477                 pw.flush();
11478                 try {
11479                     TransferPipe tp = new TransferPipe();
11480                     try {
11481                         thread.dumpCacheInfo(tp.getWriteFd(), args);
11482                         tp.go(fd);
11483                     } finally {
11484                         tp.kill();
11485                     }
11486                 } catch (IOException e) {
11487                     pw.println("Failure while dumping the app " + r);
11488                     pw.flush();
11489                 } catch (RemoteException e) {
11490                     pw.println("Got a RemoteException while dumping the app " + r);
11491                     pw.flush();
11492                 }
11493             }
11494         }
11495     }
11496 
dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)11497     final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
11498         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
11499         if (procs == null) {
11500             pw.println("No process found for: " + args[0]);
11501             return;
11502         }
11503 
11504         pw.println("Applications Database Info:");
11505 
11506         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
11507             ProcessRecord r = procs.get(i);
11508             final int pid = r.getPid();
11509             final IApplicationThread thread = r.getThread();
11510             if (thread != null) {
11511                 pw.println("\n** Database info for pid " + pid + " [" + r.processName + "] **");
11512                 pw.flush();
11513                 try {
11514                     TransferPipe tp = new TransferPipe();
11515                     try {
11516                         thread.dumpDbInfo(tp.getWriteFd(), args);
11517                         tp.go(fd);
11518                     } finally {
11519                         tp.kill();
11520                     }
11521                 } catch (IOException e) {
11522                     pw.println("Failure while dumping the app: " + r);
11523                     pw.flush();
11524                 } catch (RemoteException e) {
11525                     pw.println("Got a RemoteException while dumping the app " + r);
11526                     pw.flush();
11527                 }
11528             }
11529         }
11530     }
11531 
11532     final static class MemItem {
11533         final boolean isProc;
11534         final String label;
11535         final String shortLabel;
11536         final long pss;
11537         final long swapPss;
11538         final long mRss;
11539         final int id; // pid
11540         final int userId;
11541         final boolean hasActivities;
11542         ArrayList<MemItem> subitems;
11543 
MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id, @UserIdInt int userId, boolean hasActivities)11544         MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id,
11545                 @UserIdInt int userId,
11546                 boolean hasActivities) {
11547             this.isProc = true;
11548             this.label = label;
11549             this.shortLabel = shortLabel;
11550             this.pss = pss;
11551             this.swapPss = swapPss;
11552             this.mRss = rss;
11553             this.id = id;
11554             this.userId = userId;
11555             this.hasActivities = hasActivities;
11556         }
11557 
MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id)11558         MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id) {
11559             this.isProc = false;
11560             this.label = label;
11561             this.shortLabel = shortLabel;
11562             this.pss = pss;
11563             this.swapPss = swapPss;
11564             this.mRss = rss;
11565             this.id = id;
11566             this.userId = UserHandle.USER_SYSTEM;
11567             this.hasActivities = false;
11568         }
11569     }
11570 
sortMemItems(List<MemItem> items, final boolean pss)11571     private static void sortMemItems(List<MemItem> items, final boolean pss) {
11572         Collections.sort(items, new Comparator<MemItem>() {
11573             @Override
11574             public int compare(MemItem lhs, MemItem rhs) {
11575                 long lss = pss ? lhs.pss : lhs.mRss;
11576                 long rss = pss ? rhs.pss : rhs.mRss;
11577                 if (lss < rss) {
11578                     return 1;
11579                 } else if (lss > rss) {
11580                     return -1;
11581                 }
11582                 return 0;
11583             }
11584         });
11585     }
11586 
dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, boolean dumpSwapPss)11587     static final void dumpMemItems(PrintWriter pw, String prefix, String tag,
11588             ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss,
11589             boolean dumpSwapPss) {
11590         if (sort && !isCompact) {
11591             sortMemItems(items, dumpPss);
11592         }
11593 
11594         for (int i=0; i<items.size(); i++) {
11595             MemItem mi = items.get(i);
11596             if (!isCompact) {
11597                 if (dumpPss && dumpSwapPss) {
11598                     pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss),
11599                             mi.label, stringifyKBSize(mi.swapPss));
11600                 } else {
11601                     pw.printf("%s%s: %s%s\n", prefix, stringifyKBSize(dumpPss ? mi.pss : mi.mRss),
11602                             mi.label,
11603                             mi.userId != UserHandle.USER_SYSTEM ? " (user " + mi.userId + ")" : "");
11604                 }
11605             } else if (mi.isProc) {
11606                 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel);
11607                 pw.print(","); pw.print(mi.id); pw.print(",");
11608                 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(",");
11609                 pw.print(dumpSwapPss ? mi.swapPss : "N/A");
11610                 pw.println(mi.hasActivities ? ",a" : ",e");
11611             } else {
11612                 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(",");
11613                 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(",");
11614                 pw.println(dumpSwapPss ? mi.swapPss : "N/A");
11615             }
11616             if (mi.subitems != null) {
11617                 dumpMemItems(pw, prefix + "    ", mi.shortLabel, mi.subitems,
11618                         true, isCompact, dumpPss, dumpSwapPss);
11619             }
11620         }
11621     }
11622 
dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss)11623     static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag,
11624             ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss) {
11625         if (sort) {
11626             sortMemItems(items, dumpPss);
11627         }
11628 
11629         for (int i=0; i<items.size(); i++) {
11630             MemItem mi = items.get(i);
11631             final long token = proto.start(fieldId);
11632 
11633             proto.write(MemInfoDumpProto.MemItem.TAG, tag);
11634             proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel);
11635             proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc);
11636             proto.write(MemInfoDumpProto.MemItem.ID, mi.id);
11637             proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities);
11638             proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss);
11639             proto.write(MemInfoDumpProto.MemItem.RSS_KB, mi.mRss);
11640             if (dumpSwapPss) {
11641                 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss);
11642             }
11643             if (mi.subitems != null) {
11644                 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems,
11645                         true, dumpPss, dumpSwapPss);
11646             }
11647             proto.end(token);
11648         }
11649     }
11650 
11651     // These are in KB.
11652     static final long[] DUMP_MEM_BUCKETS = new long[] {
11653         5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
11654         120*1024, 160*1024, 200*1024,
11655         250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
11656         1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
11657     };
11658 
appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)11659     static final void appendMemBucket(StringBuilder out, long memKB, String label,
11660             boolean stackLike) {
11661         int start = label.lastIndexOf('.');
11662         if (start >= 0) start++;
11663         else start = 0;
11664         int end = label.length();
11665         for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
11666             if (DUMP_MEM_BUCKETS[i] >= memKB) {
11667                 long bucket = DUMP_MEM_BUCKETS[i]/1024;
11668                 out.append(bucket);
11669                 out.append(stackLike ? "MB." : "MB ");
11670                 out.append(label, start, end);
11671                 return;
11672             }
11673         }
11674         out.append(memKB/1024);
11675         out.append(stackLike ? "MB." : "MB ");
11676         out.append(label, start, end);
11677     }
11678 
11679     static final int[] DUMP_MEM_OOM_ADJ = new int[] {
11680             ProcessList.NATIVE_ADJ,
11681             ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ,
11682             ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ,
11683             ProcessList.VISIBLE_APP_ADJ,
11684             ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ,
11685             ProcessList.PERCEPTIBLE_MEDIUM_APP_ADJ,
11686             ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
11687             ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
11688             ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ
11689     };
11690     static final String[] DUMP_MEM_OOM_LABEL = new String[] {
11691             "Native",
11692             "System", "Persistent", "Persistent Service", "Foreground",
11693             "Visible", "Perceptible", "Perceptible Low", "Perceptible Medium",
11694             "Backup", "Heavy Weight",
11695             "A Services", "Home",
11696             "Previous", "B Services", "Cached"
11697     };
11698     static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] {
11699             "native",
11700             "sys", "pers", "persvc", "fore",
11701             "vis", "percept", "perceptl", "perceptm",
11702             "backup", "heavy",
11703             "servicea", "home",
11704             "prev", "serviceb", "cached"
11705     };
11706 
dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)11707     private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime,
11708             long realtime, boolean isCheckinRequest, boolean isCompact) {
11709         if (isCompact) {
11710             pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION);
11711         }
11712         if (isCheckinRequest || isCompact) {
11713             // short checkin version
11714             pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime);
11715         } else {
11716             pw.println("Applications Memory Usage (in Kilobytes):");
11717             pw.println("Uptime: " + uptime + " Realtime: " + realtime);
11718         }
11719     }
11720 
11721     static final int KSM_SHARED = 0;
11722     static final int KSM_SHARING = 1;
11723     static final int KSM_UNSHARED = 2;
11724     static final int KSM_VOLATILE = 3;
11725 
getKsmInfo()11726     static final long[] getKsmInfo() {
11727         long[] longOut = new long[4];
11728         final int[] SINGLE_LONG_FORMAT = new int[] {
11729             PROC_SPACE_TERM| PROC_OUT_LONG
11730         };
11731         long[] longTmp = new long[1];
11732         readProcFile("/sys/kernel/mm/ksm/pages_shared",
11733                 SINGLE_LONG_FORMAT, null, longTmp, null);
11734         longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
11735         longTmp[0] = 0;
11736         readProcFile("/sys/kernel/mm/ksm/pages_sharing",
11737                 SINGLE_LONG_FORMAT, null, longTmp, null);
11738         longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
11739         longTmp[0] = 0;
11740         readProcFile("/sys/kernel/mm/ksm/pages_unshared",
11741                 SINGLE_LONG_FORMAT, null, longTmp, null);
11742         longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
11743         longTmp[0] = 0;
11744         readProcFile("/sys/kernel/mm/ksm/pages_volatile",
11745                 SINGLE_LONG_FORMAT, null, longTmp, null);
11746         longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
11747         return longOut;
11748     }
11749 
stringifySize(long size, int order)11750     static String stringifySize(long size, int order) {
11751         Locale locale = Locale.US;
11752         switch (order) {
11753             case 1:
11754                 return String.format(locale, "%,13d", size);
11755             case 1024:
11756                 return String.format(locale, "%,9dK", size / 1024);
11757             case 1024 * 1024:
11758                 return String.format(locale, "%,5dM", size / 1024 / 1024);
11759             case 1024 * 1024 * 1024:
11760                 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024);
11761             default:
11762                 throw new IllegalArgumentException("Invalid size order");
11763         }
11764     }
11765 
stringifyKBSize(long size)11766     static String stringifyKBSize(long size) {
11767         return stringifySize(size * 1024, 1024);
11768     }
11769 
11770     // Update this version number if you change the 'compact' format.
11771     private static final int MEMINFO_COMPACT_VERSION = 1;
11772 
11773     private static class MemoryUsageDumpOptions {
11774         boolean dumpDetails;
11775         boolean dumpFullDetails;
11776         boolean dumpDalvik;
11777         boolean dumpSummaryOnly;
11778         boolean dumpUnreachable;
11779         boolean oomOnly;
11780         boolean isCompact;
11781         boolean localOnly;
11782         boolean packages;
11783         boolean isCheckinRequest;
11784         boolean dumpSwapPss;
11785         boolean dumpProto;
11786     }
11787 
11788     @NeverCompile // Avoid size overhead of debugging code.
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)11789     final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
11790             String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) {
11791         MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions();
11792         opts.dumpDetails = false;
11793         opts.dumpFullDetails = false;
11794         opts.dumpDalvik = false;
11795         opts.dumpSummaryOnly = false;
11796         opts.dumpUnreachable = false;
11797         opts.oomOnly = false;
11798         opts.isCompact = false;
11799         opts.localOnly = false;
11800         opts.packages = false;
11801         opts.isCheckinRequest = false;
11802         opts.dumpSwapPss = false;
11803         opts.dumpProto = asProto;
11804 
11805         int opti = 0;
11806         while (opti < args.length) {
11807             String opt = args[opti];
11808             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11809                 break;
11810             }
11811             opti++;
11812             if ("-a".equals(opt)) {
11813                 opts.dumpDetails = true;
11814                 opts.dumpFullDetails = true;
11815                 opts.dumpDalvik = true;
11816                 opts.dumpSwapPss = true;
11817             } else if ("-d".equals(opt)) {
11818                 opts.dumpDalvik = true;
11819             } else if ("-c".equals(opt)) {
11820                 opts.isCompact = true;
11821             } else if ("-s".equals(opt)) {
11822                 opts.dumpDetails = true;
11823                 opts.dumpSummaryOnly = true;
11824             } else if ("-S".equals(opt)) {
11825                 opts.dumpSwapPss = true;
11826             } else if ("--unreachable".equals(opt)) {
11827                 opts.dumpUnreachable = true;
11828             } else if ("--oom".equals(opt)) {
11829                 opts.oomOnly = true;
11830             } else if ("--local".equals(opt)) {
11831                 opts.localOnly = true;
11832             } else if ("--package".equals(opt)) {
11833                 opts.packages = true;
11834             } else if ("--checkin".equals(opt)) {
11835                 opts.isCheckinRequest = true;
11836             } else if ("--proto".equals(opt)) {
11837                 opts.dumpProto = true;
11838 
11839             } else if ("-h".equals(opt)) {
11840                 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]");
11841                 pw.println("  -a: include all available information for each process.");
11842                 pw.println("  -d: include dalvik details.");
11843                 pw.println("  -c: dump in a compact machine-parseable representation.");
11844                 pw.println("  -s: dump only summary of application memory usage.");
11845                 pw.println("  -S: dump also SwapPss.");
11846                 pw.println("  --oom: only show processes organized by oom adj.");
11847                 pw.println("  --local: only collect details locally, don't call process.");
11848                 pw.println("  --package: interpret process arg as package, dumping all");
11849                 pw.println("             processes that have loaded that package.");
11850                 pw.println("  --checkin: dump data for a checkin");
11851                 pw.println("  --proto: dump data to proto");
11852                 pw.println("If [process] is specified it can be the name or ");
11853                 pw.println("pid of a specific process to dump.");
11854                 return;
11855             } else {
11856                 pw.println("Unknown argument: " + opt + "; use -h for help");
11857             }
11858         }
11859 
11860         String[] innerArgs = new String[args.length-opti];
11861         System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
11862 
11863         ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args);
11864         if (opts.dumpProto) {
11865             dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs);
11866         } else {
11867             dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw);
11868         }
11869     }
11870 
11871     @NeverCompile // Avoid size overhead of debugging code.
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs, PrintWriter categoryPw)11872     private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
11873             MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief,
11874             ArrayList<ProcessRecord> procs, PrintWriter categoryPw) {
11875         long uptime = SystemClock.uptimeMillis();
11876         long realtime = SystemClock.elapsedRealtime();
11877         final long[] tmpLong = new long[3];
11878 
11879         if (procs == null) {
11880             // No Java processes.  Maybe they want to print a native process.
11881             String proc = "N/A";
11882             if (innerArgs.length > 0) {
11883                 proc = innerArgs[0];
11884                 if (proc.charAt(0) != '-') {
11885                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
11886                             = new ArrayList<ProcessCpuTracker.Stats>();
11887                     updateCpuStatsNow();
11888                     int findPid = -1;
11889                     try {
11890                         findPid = Integer.parseInt(innerArgs[0]);
11891                     } catch (NumberFormatException e) {
11892                     }
11893                     final int fFindPid = findPid;
11894                     mAppProfiler.forAllCpuStats((st) -> {
11895                         if (st.pid == fFindPid || (st.baseName != null
11896                                 && st.baseName.equals(innerArgs[0]))) {
11897                             nativeProcs.add(st);
11898                         }
11899                     });
11900                     if (nativeProcs.size() > 0) {
11901                         dumpApplicationMemoryUsageHeader(pw, uptime, realtime,
11902                                 opts.isCheckinRequest, opts.isCompact);
11903                         Debug.MemoryInfo mi = null;
11904                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
11905                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
11906                             final int pid = r.pid;
11907                             if (mi == null) {
11908                                 mi = new Debug.MemoryInfo();
11909                             }
11910                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
11911                                 if (!Debug.getMemoryInfo(pid, mi)) {
11912                                     continue;
11913                                 }
11914                             } else {
11915                                 long pss = Debug.getPss(pid, tmpLong, null);
11916                                 if (pss == 0) {
11917                                     continue;
11918                                 }
11919                                 mi.nativePss = (int) pss;
11920                                 mi.nativePrivateDirty = (int) tmpLong[0];
11921                                 mi.nativeRss = (int) tmpLong[2];
11922                             }
11923                             if (!opts.isCheckinRequest && opts.dumpDetails) {
11924                                 pw.println("\n** MEMINFO in pid " + pid + " ["
11925                                         + r.baseName + "] **");
11926                             }
11927                             ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest,
11928                                     opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
11929                                     pid, r.baseName, 0, 0, 0, 0, 0, 0);
11930                             if (opts.isCheckinRequest) {
11931                                 pw.println();
11932                             }
11933                         }
11934                         return;
11935                     }
11936                 }
11937             }
11938             pw.println("No process found for: " + proc);
11939             return;
11940         }
11941 
11942         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
11943             opts.dumpDetails = true;
11944         }
11945         final int numProcs = procs.size();
11946         final boolean collectNative = !opts.isCheckinRequest && numProcs > 1 && !opts.packages;
11947         if (collectNative) {
11948             // If we are showing aggregations, also look for native processes to
11949             // include so that our aggregations are more accurate.
11950             updateCpuStatsNow();
11951         }
11952 
11953         dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact);
11954 
11955         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
11956         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
11957         final long[] ss = new long[INDEX_LAST];
11958         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11959                 EmptyArray.LONG;
11960         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11961                 EmptyArray.LONG;
11962         long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11963                 EmptyArray.LONG;
11964         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11965         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11966         long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11967         long[] memtrackTmp = new long[4];
11968 
11969         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
11970         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
11971         long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length];
11972         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
11973                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
11974 
11975         long totalSwapPss = 0;
11976         long totalRss = 0;
11977         long cachedPss = 0;
11978         long cachedSwapPss = 0;
11979         boolean hasSwapPss = false;
11980 
11981         Debug.MemoryInfo mi = null;
11982         for (int i = numProcs - 1; i >= 0; i--) {
11983             final ProcessRecord r = procs.get(i);
11984             final IApplicationThread thread;
11985             final int pid;
11986             final int oomAdj;
11987             final boolean hasActivities;
11988             synchronized (mProcLock) {
11989                 thread = r.getThread();
11990                 pid = r.getPid();
11991                 oomAdj = r.mState.getSetAdjWithServices();
11992                 hasActivities = r.hasActivities();
11993             }
11994             if (thread != null) {
11995                 if (mi == null) {
11996                     mi = new Debug.MemoryInfo();
11997                 }
11998                 final int reportType;
11999                 final long startTime;
12000                 final long endTime;
12001                 long memtrackGraphics = 0;
12002                 long memtrackGl = 0;
12003                 if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12004                     reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
12005                     startTime = SystemClock.currentThreadTimeMillis();
12006                     if (!Debug.getMemoryInfo(pid, mi)) {
12007                         continue;
12008                     }
12009                     endTime = SystemClock.currentThreadTimeMillis();
12010                     hasSwapPss = mi.hasSwappedOutPss;
12011                     memtrackGraphics = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS);
12012                     memtrackGl = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GL);
12013                 } else {
12014                     reportType = ProcessStats.ADD_PSS_EXTERNAL;
12015                     startTime = SystemClock.currentThreadTimeMillis();
12016                     long pss = Debug.getPss(pid, tmpLong, memtrackTmp);
12017                     if (pss == 0) {
12018                         continue;
12019                     }
12020                     mi.dalvikPss = (int) pss;
12021                     endTime = SystemClock.currentThreadTimeMillis();
12022                     mi.dalvikPrivateDirty = (int) tmpLong[0];
12023                     mi.dalvikRss = (int) tmpLong[2];
12024                     memtrackGraphics = memtrackTmp[1];
12025                     memtrackGl = memtrackTmp[2];
12026                 }
12027                 if (!opts.isCheckinRequest && opts.dumpDetails) {
12028                     pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
12029                 }
12030                 if (opts.dumpDetails) {
12031                     if (opts.localOnly) {
12032                         ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails,
12033                                 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0);
12034                         if (opts.isCheckinRequest) {
12035                             pw.println();
12036                         }
12037                     } else {
12038                         pw.flush();
12039                         try {
12040                             TransferPipe tp = new TransferPipe();
12041                             try {
12042                                 thread.dumpMemInfo(tp.getWriteFd(),
12043                                         mi, opts.isCheckinRequest, opts.dumpFullDetails,
12044                                         opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs);
12045                                 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000);
12046                             } finally {
12047                                 tp.kill();
12048                             }
12049                         } catch (IOException e) {
12050                             if (!opts.isCheckinRequest) {
12051                                 pw.println("Got IoException! " + e);
12052                                 pw.flush();
12053                             }
12054                         } catch (RemoteException e) {
12055                             if (!opts.isCheckinRequest) {
12056                                 pw.println("Got RemoteException! " + e);
12057                                 pw.flush();
12058                             }
12059                         }
12060                     }
12061                 }
12062 
12063                 final long myTotalPss = mi.getTotalPss();
12064                 final long myTotalUss = mi.getTotalUss();
12065                 final long myTotalRss = mi.getTotalRss();
12066                 final long myTotalSwapPss = mi.getTotalSwappedOutPss();
12067 
12068                 synchronized (mProcLock) {
12069                     if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) {
12070                         // Record this for posterity if the process has been stable.
12071                         r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true,
12072                                 reportType, endTime - startTime);
12073                         r.getPkgList().forEachPackageProcessStats(holder -> {
12074                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
12075                                     r.info.uid,
12076                                     holder.state.getName(),
12077                                     holder.state.getPackage(),
12078                                     myTotalPss, myTotalUss, myTotalRss, reportType,
12079                                     endTime-startTime,
12080                                     holder.appVersion,
12081                                     r.mProfile.getCurrentHostingComponentTypes(),
12082                                     r.mProfile.getHistoricalHostingComponentTypes());
12083                         });
12084                     }
12085                 }
12086 
12087                 if (!opts.isCheckinRequest && mi != null) {
12088                     ss[INDEX_TOTAL_PSS] += myTotalPss;
12089                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
12090                     ss[INDEX_TOTAL_RSS] += myTotalRss;
12091                     ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics;
12092                     ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl;
12093                     MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
12094                             (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
12095                             myTotalSwapPss, myTotalRss, pid, r.userId, hasActivities);
12096                     procMems.add(pssItem);
12097                     procMemsMap.put(pid, pssItem);
12098 
12099                     ss[INDEX_NATIVE_PSS] += mi.nativePss;
12100                     ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss;
12101                     ss[INDEX_NATIVE_RSS] += mi.nativeRss;
12102                     ss[INDEX_DALVIK_PSS] += mi.dalvikPss;
12103                     ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss;
12104                     ss[INDEX_DALVIK_RSS] += mi.dalvikRss;
12105                     for (int j=0; j<dalvikSubitemPss.length; j++) {
12106                         dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12107                         dalvikSubitemSwapPss[j] +=
12108                                 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12109                         dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12110                     }
12111                     ss[INDEX_OTHER_PSS] += mi.otherPss;
12112                     ss[INDEX_OTHER_RSS] += mi.otherRss;
12113                     ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss;
12114                     for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12115                         long mem = mi.getOtherPss(j);
12116                         miscPss[j] += mem;
12117                         ss[INDEX_OTHER_PSS] -= mem;
12118                         mem = mi.getOtherSwappedOutPss(j);
12119                         miscSwapPss[j] += mem;
12120                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
12121                         mem = mi.getOtherRss(j);
12122                         miscRss[j] += mem;
12123                         ss[INDEX_OTHER_RSS] -= mem;
12124                     }
12125 
12126                     if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
12127                         cachedPss += myTotalPss;
12128                         cachedSwapPss += myTotalSwapPss;
12129                     }
12130 
12131                     for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
12132                         if (oomIndex == (oomPss.length - 1)
12133                                 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
12134                                         && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
12135                             oomPss[oomIndex] += myTotalPss;
12136                             oomSwapPss[oomIndex] += myTotalSwapPss;
12137                             if (oomProcs[oomIndex] == null) {
12138                                 oomProcs[oomIndex] = new ArrayList<MemItem>();
12139                             }
12140                             oomProcs[oomIndex].add(pssItem);
12141                             oomRss[oomIndex] += myTotalRss;
12142                             break;
12143                         }
12144                     }
12145                 }
12146             }
12147         }
12148 
12149         long nativeProcTotalPss = 0;
12150 
12151         if (collectNative) {
12152             mi = null;
12153             final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1];
12154             mAppProfiler.forAllCpuStats((st) -> {
12155                 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
12156                     long memtrackGraphics = 0;
12157                     long memtrackGl = 0;
12158                     if (memInfos[0] == null) {
12159                         memInfos[0] = new Debug.MemoryInfo();
12160                     }
12161                     final Debug.MemoryInfo info = memInfos[0];
12162                     if (!brief && !opts.oomOnly) {
12163                         if (!Debug.getMemoryInfo(st.pid, info)) {
12164                             return;
12165                         }
12166                         memtrackGraphics = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS);
12167                         memtrackGl = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GL);
12168                     } else {
12169                         long pss = Debug.getPss(st.pid, tmpLong, memtrackTmp);
12170                         if (pss == 0) {
12171                             return;
12172                         }
12173                         info.nativePss = (int) pss;
12174                         info.nativePrivateDirty = (int) tmpLong[0];
12175                         info.nativeRss = (int) tmpLong[2];
12176                         memtrackGraphics = memtrackTmp[1];
12177                         memtrackGl = memtrackTmp[2];
12178                     }
12179 
12180                     final long myTotalPss = info.getTotalPss();
12181                     final long myTotalSwapPss = info.getTotalSwappedOutPss();
12182                     final long myTotalRss = info.getTotalRss();
12183                     ss[INDEX_TOTAL_PSS] += myTotalPss;
12184                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
12185                     ss[INDEX_TOTAL_RSS] += myTotalRss;
12186                     ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss;
12187                     ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics;
12188                     ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl;
12189 
12190                     MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
12191                             st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss,
12192                             st.pid, UserHandle.getUserId(st.uid), false);
12193                     procMems.add(pssItem);
12194 
12195                     ss[INDEX_NATIVE_PSS] += info.nativePss;
12196                     ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss;
12197                     ss[INDEX_NATIVE_RSS] += info.nativeRss;
12198                     ss[INDEX_DALVIK_PSS] += info.dalvikPss;
12199                     ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss;
12200                     ss[INDEX_DALVIK_RSS] += info.dalvikRss;
12201                     for (int j = 0; j < dalvikSubitemPss.length; j++) {
12202                         dalvikSubitemPss[j] += info.getOtherPss(
12203                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12204                         dalvikSubitemSwapPss[j] +=
12205                                 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12206                         dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS
12207                                 + j);
12208                     }
12209                     ss[INDEX_OTHER_PSS] += info.otherPss;
12210                     ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss;
12211                     ss[INDEX_OTHER_RSS] += info.otherRss;
12212                     for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12213                         long mem = info.getOtherPss(j);
12214                         miscPss[j] += mem;
12215                         ss[INDEX_OTHER_PSS] -= mem;
12216                         mem = info.getOtherSwappedOutPss(j);
12217                         miscSwapPss[j] += mem;
12218                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
12219                         mem = info.getOtherRss(j);
12220                         miscRss[j] += mem;
12221                         ss[INDEX_OTHER_RSS] -= mem;
12222                     }
12223                     oomPss[0] += myTotalPss;
12224                     oomSwapPss[0] += myTotalSwapPss;
12225                     if (oomProcs[0] == null) {
12226                         oomProcs[0] = new ArrayList<MemItem>();
12227                     }
12228                     oomProcs[0].add(pssItem);
12229                     oomRss[0] += myTotalRss;
12230                 }
12231             });
12232 
12233             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
12234 
12235             catMems.add(new MemItem("Native", "Native",
12236                     ss[INDEX_NATIVE_PSS], ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1));
12237             final int dalvikId = -2;
12238             catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS],
12239                     ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId));
12240             catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS],
12241                     ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3));
12242             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12243                 String label = Debug.MemoryInfo.getOtherLabel(j);
12244                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j],  j));
12245             }
12246             if (dalvikSubitemPss.length > 0) {
12247                 // Add dalvik subitems.
12248                 for (MemItem memItem : catMems) {
12249                     int memItemStart = 0, memItemEnd = 0;
12250                     if (memItem.id == dalvikId) {
12251                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
12252                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
12253                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
12254                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
12255                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
12256                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
12257                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
12258                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
12259                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
12260                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
12261                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
12262                     } else {
12263                         continue;  // No subitems, continue.
12264                     }
12265                     memItem.subitems = new ArrayList<MemItem>();
12266                     for (int j=memItemStart; j<=memItemEnd; j++) {
12267                         final String name = Debug.MemoryInfo.getOtherLabel(
12268                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12269                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
12270                                 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j));
12271                     }
12272                 }
12273             }
12274 
12275             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
12276             for (int j=0; j<oomPss.length; j++) {
12277                 if (oomPss[j] != 0) {
12278                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
12279                             : DUMP_MEM_OOM_LABEL[j];
12280                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j],
12281                             DUMP_MEM_OOM_ADJ[j]);
12282                     item.subitems = oomProcs[j];
12283                     oomMems.add(item);
12284                 }
12285             }
12286             if (!opts.isCompact) {
12287                 pw.println();
12288             }
12289             if (!brief && !opts.oomOnly && !opts.isCompact) {
12290                 pw.println();
12291                 pw.println("Total RSS by process:");
12292                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, false, false);
12293                 pw.println();
12294             }
12295             if (!opts.isCompact) {
12296                 pw.println("Total RSS by OOM adjustment:");
12297             }
12298             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, false, false);
12299             if (!brief && !opts.oomOnly) {
12300                 PrintWriter out = categoryPw != null ? categoryPw : pw;
12301                 if (!opts.isCompact) {
12302                     out.println();
12303                     out.println("Total RSS by category:");
12304                 }
12305                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, false, false);
12306             }
12307             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0;
12308             if (!brief && !opts.oomOnly && !opts.isCompact) {
12309                 pw.println();
12310                 pw.println("Total PSS by process:");
12311                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, true,
12312                         opts.dumpSwapPss);
12313                 pw.println();
12314             }
12315             if (!opts.isCompact) {
12316                 pw.println("Total PSS by OOM adjustment:");
12317             }
12318             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, true, opts.dumpSwapPss);
12319             if (!brief && !opts.oomOnly) {
12320                 PrintWriter out = categoryPw != null ? categoryPw : pw;
12321                 if (!opts.isCompact) {
12322                     out.println();
12323                     out.println("Total PSS by category:");
12324                 }
12325                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, true,
12326                         opts.dumpSwapPss);
12327             }
12328             if (!opts.isCompact) {
12329                 pw.println();
12330             }
12331             MemInfoReader memInfo = new MemInfoReader();
12332             memInfo.readMemInfo();
12333             if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) {
12334                 synchronized (mProcessStats.mLock) {
12335                     final long cachedKb = memInfo.getCachedSizeKb();
12336                     final long freeKb = memInfo.getFreeSizeKb();
12337                     final long zramKb = memInfo.getZramTotalSizeKb();
12338                     final long kernelKb = memInfo.getKernelUsedSizeKb();
12339                     EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024,
12340                             kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024);
12341                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
12342                             ss[INDEX_TOTAL_NATIVE_PSS]);
12343                 }
12344             }
12345             if (!brief) {
12346                 if (!opts.isCompact) {
12347                     pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb()));
12348                     pw.print(" (status ");
12349                     mAppProfiler.dumpLastMemoryLevelLocked(pw);
12350                     pw.print(" Free RAM: ");
12351                     pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
12352                             + memInfo.getFreeSizeKb()));
12353                     pw.print(" (");
12354                     pw.print(stringifyKBSize(cachedPss));
12355                     pw.print(" cached pss + ");
12356                     pw.print(stringifyKBSize(memInfo.getCachedSizeKb()));
12357                     pw.print(" cached kernel + ");
12358                     pw.print(stringifyKBSize(memInfo.getFreeSizeKb()));
12359                     pw.println(" free)");
12360                 } else {
12361                     pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(",");
12362                     pw.print(cachedPss + memInfo.getCachedSizeKb()
12363                             + memInfo.getFreeSizeKb()); pw.print(",");
12364                     pw.println(ss[INDEX_TOTAL_PSS] - cachedPss);
12365                 }
12366             }
12367             long kernelUsed = memInfo.getKernelUsedSizeKb();
12368             final long ionHeap = Debug.getIonHeapsSizeKb();
12369             final long ionPool = Debug.getIonPoolsSizeKb();
12370             final long dmabufMapped = Debug.getDmabufMappedSizeKb();
12371             if (ionHeap >= 0 && ionPool >= 0) {
12372                 final long ionUnmapped = ionHeap - dmabufMapped;
12373                 pw.print("      ION: ");
12374                         pw.print(stringifyKBSize(ionHeap + ionPool));
12375                         pw.print(" (");
12376                         pw.print(stringifyKBSize(dmabufMapped));
12377                         pw.print(" mapped + ");
12378                         pw.print(stringifyKBSize(ionUnmapped));
12379                         pw.print(" unmapped + ");
12380                         pw.print(stringifyKBSize(ionPool));
12381                         pw.println(" pools)");
12382                 kernelUsed += ionUnmapped;
12383                 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being
12384                 // set on ION VMAs, however it might be included by the memtrack HAL.
12385                 // Replace memtrack HAL reported Graphics category with mapped dmabufs
12386                 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS];
12387                 ss[INDEX_TOTAL_PSS] += dmabufMapped;
12388             } else {
12389                 final long totalExportedDmabuf = Debug.getDmabufTotalExportedKb();
12390                 if (totalExportedDmabuf >= 0) {
12391                     final long dmabufUnmapped = totalExportedDmabuf - dmabufMapped;
12392                     pw.print("DMA-BUF: ");
12393                     pw.print(stringifyKBSize(totalExportedDmabuf));
12394                     pw.print(" (");
12395                     pw.print(stringifyKBSize(dmabufMapped));
12396                     pw.print(" mapped + ");
12397                     pw.print(stringifyKBSize(dmabufUnmapped));
12398                     pw.println(" unmapped)");
12399                     // Account unmapped dmabufs as part of kernel memory allocations
12400                     kernelUsed += dmabufUnmapped;
12401                     // Replace memtrack HAL reported Graphics category with mapped dmabufs
12402                     ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS];
12403                     ss[INDEX_TOTAL_PSS] += dmabufMapped;
12404                 }
12405 
12406                 // totalDmabufHeapExported is included in totalExportedDmabuf above and hence do not
12407                 // need to be added to kernelUsed.
12408                 final long totalDmabufHeapExported = Debug.getDmabufHeapTotalExportedKb();
12409                 if (totalDmabufHeapExported >= 0) {
12410                     pw.print("DMA-BUF Heaps: ");
12411                     pw.println(stringifyKBSize(totalDmabufHeapExported));
12412                 }
12413 
12414                 final long totalDmabufHeapPool = Debug.getDmabufHeapPoolsSizeKb();
12415                 if (totalDmabufHeapPool >= 0) {
12416                     pw.print("DMA-BUF Heaps pool: ");
12417                     pw.println(stringifyKBSize(totalDmabufHeapPool));
12418                 }
12419             }
12420             final long gpuUsage = Debug.getGpuTotalUsageKb();
12421             if (gpuUsage >= 0) {
12422                 final long gpuPrivateUsage = Debug.getGpuPrivateMemoryKb();
12423                 if (gpuPrivateUsage >= 0) {
12424                     final long gpuDmaBufUsage = gpuUsage - gpuPrivateUsage;
12425                     pw.print("      GPU: ");
12426                     pw.print(stringifyKBSize(gpuUsage));
12427                     pw.print(" (");
12428                     pw.print(stringifyKBSize(gpuDmaBufUsage));
12429                     pw.print(" dmabuf + ");
12430                     pw.print(stringifyKBSize(gpuPrivateUsage));
12431                     pw.println(" private)");
12432                     // Replace memtrack HAL reported GL category with private GPU allocations and
12433                     // account it as part of kernel memory allocations
12434                     ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GL];
12435                     kernelUsed += gpuPrivateUsage;
12436                 } else {
12437                     pw.print("      GPU: "); pw.println(stringifyKBSize(gpuUsage));
12438                 }
12439             }
12440 
12441              // Note: ION/DMA-BUF heap pools are reclaimable and hence, they are included as part of
12442              // memInfo.getCachedSizeKb().
12443             final long lostRAM = memInfo.getTotalSizeKb()
12444                     - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS])
12445                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
12446                     - kernelUsed - memInfo.getZramTotalSizeKb();
12447             if (!opts.isCompact) {
12448                 pw.print(" Used RAM: "); pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss
12449                         + kernelUsed)); pw.print(" (");
12450                 pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss)); pw.print(" used pss + ");
12451                 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n");
12452                 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM));
12453             } else {
12454                 pw.print("lostram,"); pw.println(lostRAM);
12455             }
12456             if (!brief) {
12457                 if (memInfo.getZramTotalSizeKb() != 0) {
12458                     if (!opts.isCompact) {
12459                         pw.print("     ZRAM: ");
12460                         pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb()));
12461                                 pw.print(" physical used for ");
12462                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()
12463                                         - memInfo.getSwapFreeSizeKb()));
12464                                 pw.print(" in swap (");
12465                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()));
12466                                 pw.println(" total swap)");
12467                     } else {
12468                         pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(",");
12469                                 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(",");
12470                                 pw.println(memInfo.getSwapFreeSizeKb());
12471                     }
12472                 }
12473                 final long[] ksm = getKsmInfo();
12474                 if (!opts.isCompact) {
12475                     if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
12476                             || ksm[KSM_VOLATILE] != 0) {
12477                         pw.print("      KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING]));
12478                                 pw.print(" saved from shared ");
12479                                 pw.print(stringifyKBSize(ksm[KSM_SHARED]));
12480                         pw.print("           "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED]));
12481                                 pw.print(" unshared; ");
12482                                 pw.print(stringifyKBSize(
12483                                              ksm[KSM_VOLATILE])); pw.println(" volatile");
12484                     }
12485                     pw.print("   Tuning: ");
12486                     pw.print(ActivityManager.staticGetMemoryClass());
12487                     pw.print(" (large ");
12488                     pw.print(ActivityManager.staticGetLargeMemoryClass());
12489                     pw.print("), oom ");
12490                     pw.print(stringifySize(
12491                                 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024));
12492                     pw.print(", restore limit ");
12493                     pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb()));
12494                     if (ActivityManager.isLowRamDeviceStatic()) {
12495                         pw.print(" (low-ram)");
12496                     }
12497                     if (ActivityManager.isHighEndGfx()) {
12498                         pw.print(" (high-end-gfx)");
12499                     }
12500                     pw.println();
12501                 } else {
12502                     pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(",");
12503                     pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]);
12504                     pw.print(","); pw.println(ksm[KSM_VOLATILE]);
12505                     pw.print("tuning,");
12506                     pw.print(ActivityManager.staticGetMemoryClass());
12507                     pw.print(',');
12508                     pw.print(ActivityManager.staticGetLargeMemoryClass());
12509                     pw.print(',');
12510                     pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
12511                     if (ActivityManager.isLowRamDeviceStatic()) {
12512                         pw.print(",low-ram");
12513                     }
12514                     if (ActivityManager.isHighEndGfx()) {
12515                         pw.print(",high-end-gfx");
12516                     }
12517                     pw.println();
12518                 }
12519             }
12520         }
12521     }
12522 
12523     @NeverCompile // Avoid size overhead of debugging code.
dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)12524     private final void dumpApplicationMemoryUsage(FileDescriptor fd,
12525             MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief,
12526             ArrayList<ProcessRecord> procs) {
12527         final long uptimeMs = SystemClock.uptimeMillis();
12528         final long realtimeMs = SystemClock.elapsedRealtime();
12529         final long[] tmpLong = new long[3];
12530 
12531         if (procs == null) {
12532             // No Java processes.  Maybe they want to print a native process.
12533             String proc = "N/A";
12534             if (innerArgs.length > 0) {
12535                 proc = innerArgs[0];
12536                 if (proc.charAt(0) != '-') {
12537                     final ArrayList<ProcessCpuTracker.Stats> nativeProcs
12538                             = new ArrayList<ProcessCpuTracker.Stats>();
12539                     updateCpuStatsNow();
12540                     int findPid = -1;
12541                     try {
12542                         findPid = Integer.parseInt(innerArgs[0]);
12543                     } catch (NumberFormatException e) {
12544                     }
12545                     final int fFindPid = findPid;
12546                     mAppProfiler.forAllCpuStats((st) -> {
12547                         if (st.pid == fFindPid || (st.baseName != null
12548                                 && st.baseName.equals(innerArgs[0]))) {
12549                             nativeProcs.add(st);
12550                         }
12551                     });
12552                     if (nativeProcs.size() > 0) {
12553                         ProtoOutputStream proto = new ProtoOutputStream(fd);
12554 
12555                         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
12556                         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
12557                         Debug.MemoryInfo mi = null;
12558                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
12559                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
12560                             final int pid = r.pid;
12561 
12562                             if (mi == null) {
12563                                 mi = new Debug.MemoryInfo();
12564                             }
12565                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12566                                 if (!Debug.getMemoryInfo(pid, mi)) {
12567                                     continue;
12568                                 }
12569                             } else {
12570                                 long pss = Debug.getPss(pid, tmpLong, null);
12571                                 if (pss == 0) {
12572                                     continue;
12573                                 }
12574                                 mi.nativePss = (int) pss;
12575                                 mi.nativePrivateDirty = (int) tmpLong[0];
12576                                 mi.nativeRss = (int) tmpLong[2];
12577                             }
12578 
12579                             final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES);
12580 
12581                             proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
12582                             proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName);
12583 
12584                             ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
12585                                     opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
12586 
12587                             proto.end(nToken);
12588                         }
12589 
12590                         proto.flush();
12591                         return;
12592                     }
12593                 }
12594             }
12595             Log.d(TAG, "No process found for: " + innerArgs[0]);
12596             return;
12597         }
12598 
12599         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
12600             opts.dumpDetails = true;
12601         }
12602         final int numProcs = procs.size();
12603         final boolean collectNative = numProcs > 1 && !opts.packages;
12604         if (collectNative) {
12605             // If we are showing aggregations, also look for native processes to
12606             // include so that our aggregations are more accurate.
12607             updateCpuStatsNow();
12608         }
12609 
12610         ProtoOutputStream proto = new ProtoOutputStream(fd);
12611 
12612         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
12613         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
12614 
12615         final ArrayList<MemItem> procMems = new ArrayList<MemItem>();
12616         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
12617         final long[] ss = new long[INDEX_LAST];
12618         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12619                 EmptyArray.LONG;
12620         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12621                 EmptyArray.LONG;
12622         long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12623                 EmptyArray.LONG;
12624         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12625         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12626         long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12627 
12628         final long[] oomPss = new long[DUMP_MEM_OOM_LABEL.length];
12629         final long[] oomSwapPss = new long[DUMP_MEM_OOM_LABEL.length];
12630         final long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length];
12631         final ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
12632                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
12633 
12634         long cachedPss = 0;
12635         long cachedSwapPss = 0;
12636         boolean hasSwapPss = false;
12637 
12638         Debug.MemoryInfo mi = null;
12639         for (int i = numProcs - 1; i >= 0; i--) {
12640             final ProcessRecord r = procs.get(i);
12641             final IApplicationThread thread;
12642             final int pid;
12643             final int oomAdj;
12644             final boolean hasActivities;
12645             synchronized (mProcLock) {
12646                 thread = r.getThread();
12647                 pid = r.getPid();
12648                 oomAdj = r.mState.getSetAdjWithServices();
12649                 hasActivities = r.hasActivities();
12650             }
12651             if (thread == null) {
12652                 continue;
12653             }
12654             if (mi == null) {
12655                 mi = new Debug.MemoryInfo();
12656             }
12657             final int reportType;
12658             final long startTime;
12659             final long endTime;
12660             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12661                 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
12662                 startTime = SystemClock.currentThreadTimeMillis();
12663                 if (!Debug.getMemoryInfo(pid, mi)) {
12664                     continue;
12665                 }
12666                 endTime = SystemClock.currentThreadTimeMillis();
12667                 hasSwapPss = mi.hasSwappedOutPss;
12668             } else {
12669                 reportType = ProcessStats.ADD_PSS_EXTERNAL;
12670                 startTime = SystemClock.currentThreadTimeMillis();
12671                 long pss = Debug.getPss(pid, tmpLong, null);
12672                 if (pss == 0) {
12673                     continue;
12674                 }
12675                 mi.dalvikPss = (int) pss;
12676                 endTime = SystemClock.currentThreadTimeMillis();
12677                 mi.dalvikPrivateDirty = (int) tmpLong[0];
12678                 mi.dalvikRss = (int) tmpLong[2];
12679             }
12680             if (opts.dumpDetails) {
12681                 if (opts.localOnly) {
12682                     final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES);
12683                     final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
12684                     proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
12685                     proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName);
12686                     ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
12687                             opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
12688                     proto.end(mToken);
12689                     proto.end(aToken);
12690                 } else {
12691                     try {
12692                         ByteTransferPipe tp = new ByteTransferPipe();
12693                         try {
12694                             thread.dumpMemInfoProto(tp.getWriteFd(),
12695                                 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
12696                                 opts.dumpUnreachable, innerArgs);
12697                             proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get());
12698                         } finally {
12699                             tp.kill();
12700                         }
12701                     } catch (IOException e) {
12702                         Log.e(TAG, "Got IOException!", e);
12703                     } catch (RemoteException e) {
12704                         Log.e(TAG, "Got RemoteException!", e);
12705                     }
12706                 }
12707             }
12708 
12709             final long myTotalPss = mi.getTotalPss();
12710             final long myTotalUss = mi.getTotalUss();
12711             final long myTotalRss = mi.getTotalRss();
12712             final long myTotalSwapPss = mi.getTotalSwappedOutPss();
12713 
12714             synchronized (mProcLock) {
12715                 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) {
12716                     // Record this for posterity if the process has been stable.
12717                     r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true,
12718                                 reportType, endTime - startTime);
12719                     r.getPkgList().forEachPackageProcessStats(holder -> {
12720                         FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
12721                                 r.info.uid,
12722                                 holder.state.getName(),
12723                                 holder.state.getPackage(),
12724                                 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime,
12725                                 holder.appVersion,
12726                                 r.mProfile.getCurrentHostingComponentTypes(),
12727                                 r.mProfile.getHistoricalHostingComponentTypes());
12728                     });
12729                 }
12730             }
12731 
12732             if (!opts.isCheckinRequest && mi != null) {
12733                 ss[INDEX_TOTAL_PSS] += myTotalPss;
12734                 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
12735                 ss[INDEX_TOTAL_RSS] += myTotalRss;
12736                 MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
12737                         (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
12738                         myTotalSwapPss, myTotalRss, pid, r.userId, hasActivities);
12739                 procMems.add(pssItem);
12740                 procMemsMap.put(pid, pssItem);
12741 
12742                 ss[INDEX_NATIVE_PSS] += mi.nativePss;
12743                 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss;
12744                 ss[INDEX_NATIVE_RSS] += mi.nativeRss;
12745                 ss[INDEX_DALVIK_PSS] += mi.dalvikPss;
12746                 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss;
12747                 ss[INDEX_DALVIK_RSS] += mi.dalvikRss;
12748                 for (int j=0; j<dalvikSubitemPss.length; j++) {
12749                     dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12750                     dalvikSubitemSwapPss[j] +=
12751                             mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12752                     dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12753                 }
12754                 ss[INDEX_OTHER_PSS] += mi.otherPss;
12755                 ss[INDEX_OTHER_RSS] += mi.otherRss;
12756                 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss;
12757                 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12758                     long mem = mi.getOtherPss(j);
12759                     miscPss[j] += mem;
12760                     ss[INDEX_OTHER_PSS] -= mem;
12761                     mem = mi.getOtherSwappedOutPss(j);
12762                     miscSwapPss[j] += mem;
12763                     ss[INDEX_OTHER_SWAP_PSS] -= mem;
12764                     mem = mi.getOtherRss(j);
12765                     miscRss[j] += mem;
12766                     ss[INDEX_OTHER_RSS] -= mem;
12767                 }
12768 
12769                 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
12770                     cachedPss += myTotalPss;
12771                     cachedSwapPss += myTotalSwapPss;
12772                 }
12773 
12774                 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
12775                     if (oomIndex == (oomPss.length - 1)
12776                             || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
12777                                     && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
12778                         oomPss[oomIndex] += myTotalPss;
12779                         oomSwapPss[oomIndex] += myTotalSwapPss;
12780                         if (oomProcs[oomIndex] == null) {
12781                             oomProcs[oomIndex] = new ArrayList<MemItem>();
12782                         }
12783                         oomProcs[oomIndex].add(pssItem);
12784                         oomRss[oomIndex] += myTotalRss;
12785                         break;
12786                     }
12787                 }
12788             }
12789         }
12790 
12791         long nativeProcTotalPss = 0;
12792 
12793         if (collectNative) {
12794             mi = null;
12795             final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1];
12796             mAppProfiler.forAllCpuStats((st) -> {
12797                 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
12798                     if (memInfos[0] == null) {
12799                         memInfos[0] = new Debug.MemoryInfo();
12800                     }
12801                     final Debug.MemoryInfo info = memInfos[0];
12802                     if (!brief && !opts.oomOnly) {
12803                         if (!Debug.getMemoryInfo(st.pid, info)) {
12804                             return;
12805                         }
12806                     } else {
12807                         long pss = Debug.getPss(st.pid, tmpLong, null);
12808                         if (pss == 0) {
12809                             return;
12810                         }
12811                         info.nativePss = (int) pss;
12812                         info.nativePrivateDirty = (int) tmpLong[0];
12813                         info.nativeRss = (int) tmpLong[2];
12814                     }
12815 
12816                     final long myTotalPss = info.getTotalPss();
12817                     final long myTotalSwapPss = info.getTotalSwappedOutPss();
12818                     final long myTotalRss = info.getTotalRss();
12819                     ss[INDEX_TOTAL_PSS] += myTotalPss;
12820                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
12821                     ss[INDEX_TOTAL_RSS] += myTotalRss;
12822                     ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss;
12823 
12824                     MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
12825                             st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss,
12826                             st.pid, UserHandle.getUserId(st.uid), false);
12827                     procMems.add(pssItem);
12828 
12829                     ss[INDEX_NATIVE_PSS] += info.nativePss;
12830                     ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss;
12831                     ss[INDEX_NATIVE_RSS] += info.nativeRss;
12832                     ss[INDEX_DALVIK_PSS] += info.dalvikPss;
12833                     ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss;
12834                     ss[INDEX_DALVIK_RSS] += info.dalvikRss;
12835                     for (int j = 0; j < dalvikSubitemPss.length; j++) {
12836                         dalvikSubitemPss[j] += info.getOtherPss(
12837                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12838                         dalvikSubitemSwapPss[j] +=
12839                                 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12840                         dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS
12841                                 + j);
12842                     }
12843                     ss[INDEX_OTHER_PSS] += info.otherPss;
12844                     ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss;
12845                     ss[INDEX_OTHER_RSS] += info.otherRss;
12846                     for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12847                         long mem = info.getOtherPss(j);
12848                         miscPss[j] += mem;
12849                         ss[INDEX_OTHER_PSS] -= mem;
12850                         mem = info.getOtherSwappedOutPss(j);
12851                         miscSwapPss[j] += mem;
12852                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
12853                         mem = info.getOtherRss(j);
12854                         miscRss[j] += mem;
12855                         ss[INDEX_OTHER_RSS] -= mem;
12856                     }
12857                     oomPss[0] += myTotalPss;
12858                     oomSwapPss[0] += myTotalSwapPss;
12859                     if (oomProcs[0] == null) {
12860                         oomProcs[0] = new ArrayList<MemItem>();
12861                     }
12862                     oomProcs[0].add(pssItem);
12863                     oomRss[0] += myTotalRss;
12864                 }
12865             });
12866 
12867             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
12868 
12869             catMems.add(new MemItem("Native", "Native", ss[INDEX_NATIVE_PSS],
12870                     ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1));
12871             final int dalvikId = -2;
12872             catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS],
12873                     ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId));
12874             catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS],
12875                     ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3));
12876             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12877                 String label = Debug.MemoryInfo.getOtherLabel(j);
12878                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], j));
12879             }
12880             if (dalvikSubitemPss.length > 0) {
12881                 // Add dalvik subitems.
12882                 for (MemItem memItem : catMems) {
12883                     int memItemStart = 0, memItemEnd = 0;
12884                     if (memItem.id == dalvikId) {
12885                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
12886                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
12887                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
12888                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
12889                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
12890                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
12891                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
12892                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
12893                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
12894                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
12895                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
12896                     } else {
12897                         continue;  // No subitems, continue.
12898                     }
12899                     memItem.subitems = new ArrayList<MemItem>();
12900                     for (int j=memItemStart; j<=memItemEnd; j++) {
12901                         final String name = Debug.MemoryInfo.getOtherLabel(
12902                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12903                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
12904                                 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j));
12905                     }
12906                 }
12907             }
12908 
12909             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
12910             for (int j=0; j<oomPss.length; j++) {
12911                 if (oomPss[j] != 0) {
12912                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
12913                             : DUMP_MEM_OOM_LABEL[j];
12914                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j],
12915                             DUMP_MEM_OOM_ADJ[j]);
12916                     item.subitems = oomProcs[j];
12917                     oomMems.add(item);
12918                 }
12919             }
12920 
12921             if (!opts.oomOnly) {
12922                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_PROCESS, "proc",
12923                         procMems, true, false, false);
12924             }
12925             dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_OOM_ADJUSTMENT, "oom",
12926                     oomMems, false, false, false);
12927             if (!brief && !opts.oomOnly) {
12928                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_CATEGORY, "cat",
12929                         catMems, true, false, false);
12930             }
12931 
12932             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0;
12933             if (!opts.oomOnly) {
12934                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc",
12935                         procMems, true, true, opts.dumpSwapPss);
12936             }
12937             dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom",
12938                     oomMems, false, true, opts.dumpSwapPss);
12939             if (!brief && !opts.oomOnly) {
12940                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat",
12941                         catMems, true, true, opts.dumpSwapPss);
12942             }
12943             MemInfoReader memInfo = new MemInfoReader();
12944             memInfo.readMemInfo();
12945             if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) {
12946                 synchronized (mProcessStats.mLock) {
12947                     final long cachedKb = memInfo.getCachedSizeKb();
12948                     final long freeKb = memInfo.getFreeSizeKb();
12949                     final long zramKb = memInfo.getZramTotalSizeKb();
12950                     final long kernelKb = memInfo.getKernelUsedSizeKb();
12951                     EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024,
12952                             kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024);
12953                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
12954                             ss[INDEX_TOTAL_NATIVE_PSS]);
12955                 }
12956             }
12957             if (!brief) {
12958                 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb());
12959                 proto.write(MemInfoDumpProto.STATUS, mAppProfiler.getLastMemoryLevelLocked());
12960                 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss);
12961                 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb());
12962                 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb());
12963             }
12964             long lostRAM = memInfo.getTotalSizeKb()
12965                     - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS])
12966                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
12967                     - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb();
12968             proto.write(MemInfoDumpProto.USED_PSS_KB, ss[INDEX_TOTAL_PSS] - cachedPss);
12969             proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb());
12970             proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM);
12971             if (!brief) {
12972                 if (memInfo.getZramTotalSizeKb() != 0) {
12973                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb());
12974                     proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB,
12975                             memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb());
12976                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb());
12977                 }
12978                 final long[] ksm = getKsmInfo();
12979                 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]);
12980                 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]);
12981                 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]);
12982                 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]);
12983 
12984                 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass());
12985                 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass());
12986                 proto.write(MemInfoDumpProto.OOM_KB,
12987                         mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024);
12988                 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB,
12989                         mProcessList.getCachedRestoreThresholdKb());
12990 
12991                 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic());
12992                 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx());
12993             }
12994         }
12995 
12996         proto.flush();
12997     }
12998 
appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)12999     static void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss,
13000             long memtrack, String name) {
13001         sb.append("  ");
13002         sb.append(ProcessList.makeOomAdjString(oomAdj, false));
13003         sb.append(' ');
13004         sb.append(ProcessList.makeProcStateString(procState));
13005         sb.append(' ');
13006         ProcessList.appendRamKb(sb, pss);
13007         sb.append(": ");
13008         sb.append(name);
13009         if (memtrack > 0) {
13010             sb.append(" (");
13011             sb.append(stringifyKBSize(memtrack));
13012             sb.append(" memtrack)");
13013         }
13014     }
13015 
appendMemInfo(StringBuilder sb, ProcessMemInfo mi)13016     static void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) {
13017         appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name);
13018         sb.append(" (pid ");
13019         sb.append(mi.pid);
13020         sb.append(") ");
13021         sb.append(mi.adjType);
13022         sb.append('\n');
13023         if (mi.adjReason != null) {
13024             sb.append("                      ");
13025             sb.append(mi.adjReason);
13026             sb.append('\n');
13027         }
13028     }
13029 
13030     /**
13031      * Searches array of arguments for the specified string
13032      * @param args array of argument strings
13033      * @param value value to search for
13034      * @return true if the value is contained in the array
13035      */
scanArgs(String[] args, String value)13036     private static boolean scanArgs(String[] args, String value) {
13037         if (args != null) {
13038             for (String arg : args) {
13039                 if (value.equals(arg)) {
13040                     return true;
13041                 }
13042             }
13043         }
13044         return false;
13045     }
13046 
13047     /**
13048      * Filters out non-exported components in a given list of broadcast filters
13049      * @param intent the original intent
13050      * @param callingUid the calling UID
13051      * @param query the list of broadcast filters
13052      * @param platformCompat the instance of platform compat
13053      */
filterNonExportedComponents(Intent intent, int callingUid, int callingPid, List query, PlatformCompat platformCompat, String callerPackage, String resolvedType)13054     private void filterNonExportedComponents(Intent intent, int callingUid, int callingPid,
13055             List query, PlatformCompat platformCompat, String callerPackage, String resolvedType) {
13056         if (query == null
13057                 || intent.getPackage() != null
13058                 || intent.getComponent() != null
13059                 || ActivityManager.canAccessUnexportedComponents(callingUid)) {
13060             return;
13061         }
13062         IUnsafeIntentStrictModeCallback callback = mStrictModeCallbacks.get(callingPid);
13063         for (int i = query.size() - 1; i >= 0; i--) {
13064             String componentInfo;
13065             ResolveInfo resolveInfo;
13066             BroadcastFilter broadcastFilter;
13067             if (query.get(i) instanceof ResolveInfo) {
13068                 resolveInfo = (ResolveInfo) query.get(i);
13069                 if (resolveInfo.getComponentInfo().exported) {
13070                     continue;
13071                 }
13072                 componentInfo = resolveInfo.getComponentInfo()
13073                         .getComponentName().flattenToShortString();
13074             } else if (query.get(i) instanceof BroadcastFilter) {
13075                 broadcastFilter = (BroadcastFilter) query.get(i);
13076                 if (broadcastFilter.exported) {
13077                     continue;
13078                 }
13079                 componentInfo = broadcastFilter.packageName;
13080             } else {
13081                 continue;
13082             }
13083             if (callback != null) {
13084                 mHandler.post(() -> {
13085                     try {
13086                         callback.onImplicitIntentMatchedInternalComponent(intent.cloneFilter());
13087                     } catch (RemoteException e) {
13088                         mStrictModeCallbacks.remove(callingPid);
13089                     }
13090                 });
13091             }
13092             boolean hasToBeExportedToMatch = platformCompat.isChangeEnabledByUid(
13093                     ActivityManagerService.IMPLICIT_INTENTS_ONLY_MATCH_EXPORTED_COMPONENTS,
13094                     callingUid);
13095             ActivityManagerUtils.logUnsafeIntentEvent(
13096                     UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__INTERNAL_NON_EXPORTED_COMPONENT_MATCH,
13097                     callingUid, intent, resolvedType, hasToBeExportedToMatch);
13098             if (!hasToBeExportedToMatch) {
13099                 return;
13100             }
13101             query.remove(i);
13102         }
13103     }
13104 
13105     /**
13106      * Main code for cleaning up a process when it has gone away.  This is
13107      * called both as a result of the process dying, or directly when stopping
13108      * a process when running in single process mode.
13109      *
13110      * @return Returns true if the given process has been restarted, so the
13111      * app that was passed in must remain on the process lists.
13112      */
13113     @GuardedBy("this")
cleanUpApplicationRecordLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, int index, boolean replacingPid, boolean fromBinderDied)13114     final boolean cleanUpApplicationRecordLocked(ProcessRecord app, int pid,
13115             boolean restarting, boolean allowRestart, int index, boolean replacingPid,
13116             boolean fromBinderDied) {
13117         boolean restart;
13118         synchronized (mProcLock) {
13119             if (index >= 0) {
13120                 removeLruProcessLocked(app);
13121                 ProcessList.remove(pid);
13122             }
13123 
13124             // We don't want to unlinkDeathRecipient immediately, if it's not called from binder
13125             // and it's not isolated, as we'd need the signal to bookkeeping the dying process list.
13126             restart = app.onCleanupApplicationRecordLSP(mProcessStats, allowRestart,
13127                     fromBinderDied || app.isolated /* unlinkDeath */);
13128 
13129             // Cancel pending frozen task and clean up frozen record if there is any.
13130             mOomAdjuster.mCachedAppOptimizer.onCleanupApplicationRecordLocked(app);
13131         }
13132         mAppProfiler.onCleanupApplicationRecordLocked(app);
13133         for (BroadcastQueue queue : mBroadcastQueues) {
13134             queue.onApplicationCleanupLocked(app);
13135         }
13136         clearProcessForegroundLocked(app);
13137         mServices.killServicesLocked(app, allowRestart);
13138         mPhantomProcessList.onAppDied(pid);
13139 
13140         // If the app is undergoing backup, tell the backup manager about it
13141         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
13142         if (backupTarget != null && pid == backupTarget.app.getPid()) {
13143             if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App "
13144                     + backupTarget.appInfo + " died during backup");
13145             mHandler.post(new Runnable() {
13146                 @Override
13147                 public void run() {
13148                     try {
13149                         IBackupManager bm = IBackupManager.Stub.asInterface(
13150                                 ServiceManager.getService(Context.BACKUP_SERVICE));
13151                         bm.agentDisconnectedForUser(app.userId, app.info.packageName);
13152                     } catch (RemoteException e) {
13153                         // can't happen; backup manager is local
13154                     }
13155                 }
13156             });
13157         }
13158 
13159         mProcessList.scheduleDispatchProcessDiedLocked(pid, app.info.uid);
13160 
13161         // If this is a preceding instance of another process instance
13162         allowRestart = mProcessList.handlePrecedingAppDiedLocked(app);
13163 
13164         // If somehow this process was still waiting for the death of its predecessor,
13165         // (probably it's "killed" before starting for real), reset the bookkeeping.
13166         final ProcessRecord predecessor = app.mPredecessor;
13167         if (predecessor != null) {
13168             predecessor.mSuccessor = null;
13169             predecessor.mSuccessorStartRunnable = null;
13170             app.mPredecessor = null;
13171         }
13172 
13173         // If the caller is restarting this app, then leave it in its
13174         // current lists and let the caller take care of it.
13175         if (restarting) {
13176             return false;
13177         }
13178 
13179         if (!app.isPersistent() || app.isolated) {
13180             if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
13181                     "Removing non-persistent process during cleanup: " + app);
13182             if (!replacingPid) {
13183                 mProcessList.removeProcessNameLocked(app.processName, app.uid, app);
13184             }
13185             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
13186         } else if (!app.isRemoved()) {
13187             // This app is persistent, so we need to keep its record around.
13188             // If it is not already on the pending app list, add it there
13189             // and start a new process for it.
13190             if (mPersistentStartingProcesses.indexOf(app) < 0) {
13191                 mPersistentStartingProcesses.add(app);
13192                 restart = true;
13193             }
13194         }
13195         if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(
13196                 TAG_CLEANUP, "Clean-up removing on hold: " + app);
13197         mProcessesOnHold.remove(app);
13198 
13199         mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController());
13200         mProcessList.noteProcessDiedLocked(app);
13201 
13202         if (restart && allowRestart && !app.isolated) {
13203             // We have components that still need to be running in the
13204             // process, so re-launch it.
13205             if (index < 0) {
13206                 ProcessList.remove(pid);
13207             }
13208 
13209             // Remove provider publish timeout because we will start a new timeout when the
13210             // restarted process is attaching (if the process contains launching providers).
13211             mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, app);
13212 
13213             mProcessList.addProcessNameLocked(app);
13214             app.setPendingStart(false);
13215             mProcessList.startProcessLocked(app, new HostingRecord(
13216                     HostingRecord.HOSTING_TYPE_RESTART, app.processName),
13217                     ZYGOTE_POLICY_FLAG_EMPTY);
13218             return true;
13219         } else if (pid > 0 && pid != MY_PID) {
13220             // Goodbye!
13221             removePidLocked(pid, app);
13222             mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
13223             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
13224             if (app.isolated) {
13225                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
13226             }
13227             app.setPid(0);
13228         }
13229         return false;
13230     }
13231 
13232     // =========================================================
13233     // SERVICES
13234     // =========================================================
13235 
13236     @Override
getServices(int maxNum, int flags)13237     public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) {
13238         enforceNotIsolatedCaller("getServices");
13239 
13240         final int callingUid = Binder.getCallingUid();
13241         final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission(
13242             INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED);
13243         final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices",
13244                 Binder.getCallingPid(), callingUid);
13245         synchronized (this) {
13246             return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid,
13247                 allowed, canInteractAcrossUsers);
13248         }
13249     }
13250 
13251     @Override
getRunningServiceControlPanel(ComponentName name)13252     public PendingIntent getRunningServiceControlPanel(ComponentName name) {
13253         enforceNotIsolatedCaller("getRunningServiceControlPanel");
13254         final int callingUid = Binder.getCallingUid();
13255         final int callingUserId = UserHandle.getUserId(callingUid);
13256         if (name == null || getPackageManagerInternal()
13257                 .filterAppAccess(name.getPackageName(), callingUid, callingUserId)) {
13258             return null;
13259         }
13260         synchronized (this) {
13261             return mServices.getRunningServiceControlPanelLocked(name);
13262         }
13263     }
13264 
13265     @Override
logFgsApiBegin(@oregroundServiceApiType int apiType, int uid, int pid)13266     public void logFgsApiBegin(@ForegroundServiceApiType int apiType,
13267             int uid, int pid) {
13268         enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE,
13269                 "logFgsApiBegin");
13270         synchronized (this) {
13271             mServices.logFgsApiBeginLocked(apiType, uid, pid);
13272         }
13273     }
13274 
13275     @Override
logFgsApiEnd(@oregroundServiceApiType int apiType, int uid, int pid)13276     public void logFgsApiEnd(@ForegroundServiceApiType int apiType,
13277             int uid, int pid) {
13278         enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE,
13279                 "logFgsApiEnd");
13280         synchronized (this) {
13281             mServices.logFgsApiEndLocked(apiType, uid, pid);
13282         }
13283     }
13284 
13285     @Override
logFgsApiStateChanged(@oregroundServiceApiType int apiType, int state, int uid, int pid)13286     public void logFgsApiStateChanged(@ForegroundServiceApiType int apiType,
13287             int state, int uid, int pid) {
13288         enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE,
13289                 "logFgsApiEvent");
13290         synchronized (this) {
13291             mServices.logFgsApiStateChangedLocked(apiType, uid, pid, state);
13292         }
13293     }
13294 
13295     @Override
startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId)13296     public ComponentName startService(IApplicationThread caller, Intent service,
13297             String resolvedType, boolean requireForeground, String callingPackage,
13298             String callingFeatureId, int userId)
13299             throws TransactionTooLargeException {
13300         return startService(caller, service, resolvedType, requireForeground, callingPackage,
13301                 callingFeatureId, userId, false /* isSdkSandboxService */, INVALID_UID, null, null);
13302     }
13303 
startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)13304     private ComponentName startService(IApplicationThread caller, Intent service,
13305             String resolvedType, boolean requireForeground, String callingPackage,
13306             String callingFeatureId, int userId, boolean isSdkSandboxService,
13307             int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)
13308             throws TransactionTooLargeException {
13309         enforceNotIsolatedCaller("startService");
13310         enforceAllowedToStartOrBindServiceIfSdkSandbox(service);
13311         // Refuse possible leaked file descriptors
13312         if (service != null && service.hasFileDescriptors() == true) {
13313             throw new IllegalArgumentException("File descriptors passed in Intent");
13314         }
13315 
13316         if (callingPackage == null) {
13317             throw new IllegalArgumentException("callingPackage cannot be null");
13318         }
13319 
13320         if (isSdkSandboxService && instanceName == null) {
13321             throw new IllegalArgumentException("No instance name provided for SDK sandbox process");
13322         }
13323         validateServiceInstanceName(instanceName);
13324 
13325         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
13326                 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
13327         final int callingPid = Binder.getCallingPid();
13328         final int callingUid = Binder.getCallingUid();
13329         final long origId = Binder.clearCallingIdentity();
13330         ComponentName res;
13331         try {
13332             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13333                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startService: "
13334                         + "intent=" + service + ", caller=" + callingPackage
13335                         + ", fgRequired=" + requireForeground);
13336             }
13337             synchronized (this) {
13338                 res = mServices.startServiceLocked(caller, service,
13339                         resolvedType, callingPid, callingUid,
13340                         requireForeground, callingPackage, callingFeatureId, userId,
13341                         isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage,
13342                         instanceName);
13343             }
13344         } finally {
13345             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13346             Binder.restoreCallingIdentity(origId);
13347         }
13348         return res;
13349     }
13350 
validateServiceInstanceName(String instanceName)13351     private void validateServiceInstanceName(String instanceName) {
13352         // Ensure that instanceName, which is caller provided, does not contain
13353         // unusual characters.
13354         if (instanceName != null) {
13355             if (!instanceName.matches("[a-zA-Z0-9_.]+")) {
13356                 throw new IllegalArgumentException("Illegal instanceName");
13357             }
13358         }
13359     }
13360 
13361     @Override
stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)13362     public int stopService(IApplicationThread caller, Intent service,
13363             String resolvedType, int userId) {
13364         return stopService(caller, service, resolvedType, userId, false /* isSdkSandboxService */,
13365                 INVALID_UID, null, null);
13366     }
13367 
stopService(IApplicationThread caller, Intent service, String resolvedType, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)13368     private int stopService(IApplicationThread caller, Intent service, String resolvedType,
13369             int userId, boolean isSdkSandboxService,
13370             int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName) {
13371         enforceNotIsolatedCaller("stopService");
13372         // Refuse possible leaked file descriptors
13373         if (service != null && service.hasFileDescriptors() == true) {
13374             throw new IllegalArgumentException("File descriptors passed in Intent");
13375         }
13376 
13377         try {
13378             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13379                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopService: " + service);
13380             }
13381             synchronized (this) {
13382                 return mServices.stopServiceLocked(caller, service, resolvedType, userId,
13383                         isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage,
13384                         instanceName);
13385             }
13386         } finally {
13387             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13388         }
13389     }
13390 
13391     @Override
peekService(Intent service, String resolvedType, String callingPackage)13392     public IBinder peekService(Intent service, String resolvedType, String callingPackage) {
13393         enforceNotIsolatedCaller("peekService");
13394         // Refuse possible leaked file descriptors
13395         if (service != null && service.hasFileDescriptors() == true) {
13396             throw new IllegalArgumentException("File descriptors passed in Intent");
13397         }
13398 
13399         if (callingPackage == null) {
13400             throw new IllegalArgumentException("callingPackage cannot be null");
13401         }
13402 
13403         synchronized(this) {
13404             return mServices.peekServiceLocked(service, resolvedType, callingPackage);
13405         }
13406     }
13407 
13408     @Override
stopServiceToken(ComponentName className, IBinder token, int startId)13409     public boolean stopServiceToken(ComponentName className, IBinder token,
13410             int startId) {
13411         try {
13412             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13413                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopServiceToken: "
13414                         + (className != null ? className.toShortString()
13415                         : ("from " + Binder.getCallingPid())));
13416             }
13417             synchronized (this) {
13418                 return mServices.stopServiceTokenLocked(className, token, startId);
13419             }
13420         } finally {
13421             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13422         }
13423     }
13424 
13425     @Override
setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)13426     public void setServiceForeground(ComponentName className, IBinder token,
13427             int id, Notification notification, int flags, int foregroundServiceType) {
13428         synchronized(this) {
13429             mServices.setServiceForegroundLocked(className, token, id, notification, flags,
13430                     foregroundServiceType);
13431         }
13432     }
13433 
13434     @Override
getForegroundServiceType(ComponentName className, IBinder token)13435     public int getForegroundServiceType(ComponentName className, IBinder token) {
13436         synchronized (this) {
13437             return mServices.getForegroundServiceTypeLocked(className, token);
13438         }
13439     }
13440 
13441     @Override
shouldServiceTimeOut(ComponentName className, IBinder token)13442     public boolean shouldServiceTimeOut(ComponentName className, IBinder token) {
13443         synchronized (this) {
13444             return mServices.shouldServiceTimeOutLocked(className, token);
13445         }
13446     }
13447 
13448     @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)13449     public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
13450             boolean requireFull, String name, String callerPackage) {
13451         return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
13452                 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage);
13453     }
13454 
isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)13455     boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
13456             String className, int flags) {
13457         boolean result = false;
13458         // For apps that don't have pre-defined UIDs, check for permission
13459         if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) {
13460             if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
13461                 if (ActivityManager.checkUidPermission(
13462                         INTERACT_ACROSS_USERS,
13463                         aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
13464                     ComponentName comp = new ComponentName(aInfo.packageName, className);
13465                     String msg = "Permission Denial: Component " + comp.flattenToShortString()
13466                             + " requests FLAG_SINGLE_USER, but app does not hold "
13467                             + INTERACT_ACROSS_USERS;
13468                     Slog.w(TAG, msg);
13469                     throw new SecurityException(msg);
13470                 }
13471                 // Permission passed
13472                 result = true;
13473             }
13474         } else if ("system".equals(componentProcessName)) {
13475             result = true;
13476         } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
13477             // Phone app and persistent apps are allowed to export singleuser providers.
13478             result = UserHandle.isSameApp(aInfo.uid, PHONE_UID)
13479                     || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
13480         }
13481         if (DEBUG_MU) Slog.v(TAG_MU,
13482                 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x"
13483                 + Integer.toHexString(flags) + ") = " + result);
13484         return result;
13485     }
13486 
13487     /**
13488      * Checks to see if the caller is in the same app as the singleton
13489      * component, or the component is in a special app. It allows special apps
13490      * to export singleton components but prevents exporting singleton
13491      * components for regular apps.
13492      */
isValidSingletonCall(int callingUid, int componentUid)13493     boolean isValidSingletonCall(int callingUid, int componentUid) {
13494         int componentAppId = UserHandle.getAppId(componentUid);
13495         return UserHandle.isSameApp(callingUid, componentUid)
13496                 || componentAppId == SYSTEM_UID
13497                 || componentAppId == PHONE_UID
13498                 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid)
13499                         == PackageManager.PERMISSION_GRANTED;
13500     }
13501 
bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String callingPackage, int userId)13502     public int bindService(IApplicationThread caller, IBinder token, Intent service,
13503             String resolvedType, IServiceConnection connection, long flags,
13504             String callingPackage, int userId) throws TransactionTooLargeException {
13505         return bindServiceInstance(caller, token, service, resolvedType, connection, flags,
13506                 null, callingPackage, userId);
13507     }
13508 
13509     /**
13510      * Binds to a service with a given instanceName, creating it if it does not already exist.
13511      * If the instanceName field is not supplied, binding to the service occurs as usual.
13512      */
bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String instanceName, String callingPackage, int userId)13513     public int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service,
13514             String resolvedType, IServiceConnection connection, long flags, String instanceName,
13515             String callingPackage, int userId) throws TransactionTooLargeException {
13516         return bindServiceInstance(caller, token, service, resolvedType, connection, flags,
13517                 instanceName, false, INVALID_UID, null, null, callingPackage, userId);
13518     }
13519 
bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, IApplicationThread sdkSandboxClientApplicationThread, String callingPackage, int userId)13520     private int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service,
13521             String resolvedType, IServiceConnection connection, long flags, String instanceName,
13522             boolean isSdkSandboxService, int sdkSandboxClientAppUid,
13523             String sdkSandboxClientAppPackage,
13524             IApplicationThread sdkSandboxClientApplicationThread,
13525             String callingPackage, int userId)
13526             throws TransactionTooLargeException {
13527         enforceNotIsolatedCaller("bindService");
13528         enforceAllowedToStartOrBindServiceIfSdkSandbox(service);
13529 
13530         // Refuse possible leaked file descriptors
13531         if (service != null && service.hasFileDescriptors() == true) {
13532             throw new IllegalArgumentException("File descriptors passed in Intent");
13533         }
13534 
13535         if (callingPackage == null) {
13536             throw new IllegalArgumentException("callingPackage cannot be null");
13537         }
13538 
13539         if (isSdkSandboxService && instanceName == null) {
13540             throw new IllegalArgumentException("No instance name provided for isolated process");
13541         }
13542 
13543         validateServiceInstanceName(instanceName);
13544 
13545         try {
13546             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13547                 final ComponentName cn = service.getComponent();
13548                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindService:"
13549                         + (cn != null ? cn.toShortString() : service.getAction()));
13550             }
13551             synchronized (this) {
13552                 return mServices.bindServiceLocked(caller, token, service, resolvedType, connection,
13553                         flags, instanceName, isSdkSandboxService, sdkSandboxClientAppUid,
13554                         sdkSandboxClientAppPackage, sdkSandboxClientApplicationThread,
13555                         callingPackage, userId);
13556             }
13557         } finally {
13558             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13559         }
13560     }
13561 
updateServiceGroup(IServiceConnection connection, int group, int importance)13562     public void updateServiceGroup(IServiceConnection connection, int group, int importance) {
13563         synchronized (this) {
13564             mServices.updateServiceGroupLocked(connection, group, importance);
13565         }
13566     }
13567 
unbindService(IServiceConnection connection)13568     public boolean unbindService(IServiceConnection connection) {
13569         try {
13570             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13571                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "unbindService");
13572             }
13573             synchronized (this) {
13574                 return mServices.unbindServiceLocked(connection);
13575             }
13576         } finally {
13577             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13578         }
13579     }
13580 
publishService(IBinder token, Intent intent, IBinder service)13581     public void publishService(IBinder token, Intent intent, IBinder service) {
13582         // Refuse possible leaked file descriptors
13583         if (intent != null && intent.hasFileDescriptors() == true) {
13584             throw new IllegalArgumentException("File descriptors passed in Intent");
13585         }
13586 
13587         synchronized(this) {
13588             if (!(token instanceof ServiceRecord)) {
13589                 throw new IllegalArgumentException("Invalid service token");
13590             }
13591             mServices.publishServiceLocked((ServiceRecord)token, intent, service);
13592         }
13593     }
13594 
unbindFinished(IBinder token, Intent intent, boolean doRebind)13595     public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
13596         // Refuse possible leaked file descriptors
13597         if (intent != null && intent.hasFileDescriptors() == true) {
13598             throw new IllegalArgumentException("File descriptors passed in Intent");
13599         }
13600 
13601         synchronized(this) {
13602             mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
13603         }
13604     }
13605 
serviceDoneExecuting(IBinder token, int type, int startId, int res)13606     public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
13607         synchronized(this) {
13608             if (!(token instanceof ServiceRecord)) {
13609                 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token);
13610                 throw new IllegalArgumentException("Invalid service token");
13611             }
13612             mServices.serviceDoneExecutingLocked((ServiceRecord) token, type, startId, res, false);
13613         }
13614     }
13615 
13616     // =========================================================
13617     // BACKUP AND RESTORE
13618     // =========================================================
13619 
13620     // Cause the target app to be launched if necessary and its backup agent
13621     // instantiated.  The backup agent will invoke backupAgentCreated() on the
13622     // activity manager to announce its creation.
bindBackupAgent(String packageName, int backupMode, int targetUserId, @BackupDestination int backupDestination)13623     public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId,
13624             @BackupDestination int backupDestination) {
13625         if (DEBUG_BACKUP) {
13626             Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode
13627                     + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid()
13628                     + " uid = " + Process.myUid());
13629         }
13630         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
13631 
13632         // The instantiatedUserId is the user of the process the backup agent is started in. This is
13633         // different from the targetUserId which is the user whose data is to be backed up or
13634         // restored. This distinction is important for system-process packages that live in the
13635         // system user's process but backup/restore data for non-system users.
13636         // TODO (b/123688746): Handle all system-process packages with singleton check.
13637         boolean useSystemUser = PLATFORM_PACKAGE_NAME.equals(packageName)
13638                 || getPackageManagerInternal().getSystemUiServiceComponent().getPackageName()
13639                         .equals(packageName);
13640         final int instantiatedUserId = useSystemUser ? UserHandle.USER_SYSTEM : targetUserId;
13641 
13642         IPackageManager pm = AppGlobals.getPackageManager();
13643         ApplicationInfo app = null;
13644         try {
13645             app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId);
13646         } catch (RemoteException e) {
13647             // can't happen; package manager is process-local
13648         }
13649         if (app == null) {
13650             Slog.w(TAG, "Unable to bind backup agent for " + packageName);
13651             return false;
13652         }
13653         if (app.backupAgentName != null) {
13654             final ComponentName backupAgentName = new ComponentName(
13655                     app.packageName, app.backupAgentName);
13656             int enableState = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
13657             try {
13658                 enableState = pm.getComponentEnabledSetting(backupAgentName, instantiatedUserId);
13659             } catch (RemoteException e) {
13660                 // can't happen; package manager is process-local
13661             }
13662             switch (enableState) {
13663                 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
13664                 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER:
13665                 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED:
13666                     Slog.w(TAG, "Unable to bind backup agent for " + backupAgentName
13667                             + ", the backup agent component is disabled.");
13668                     return false;
13669 
13670                 case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
13671                 case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
13672                 default:
13673                     // Since there's no way to declare a backup agent disabled in the manifest,
13674                     // assume the case COMPONENT_ENABLED_STATE_DEFAULT to be enabled.
13675                     break;
13676             }
13677         }
13678 
13679         int oldBackupUid;
13680         int newBackupUid;
13681 
13682         synchronized(this) {
13683             // !!! TODO: currently no check here that we're already bound
13684             // Backup agent is now in use, its package can't be stopped.
13685             try {
13686                 mPackageManagerInt.setPackageStoppedState(
13687                         app.packageName, false, UserHandle.getUserId(app.uid));
13688             } catch (IllegalArgumentException e) {
13689                 Slog.w(TAG, "Failed trying to unstop package "
13690                         + app.packageName + ": " + e);
13691             }
13692 
13693             BackupRecord r = new BackupRecord(app, backupMode, targetUserId, backupDestination);
13694             ComponentName hostingName =
13695                     (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL
13696                             || backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE)
13697                             ? new ComponentName(app.packageName, app.backupAgentName)
13698                             : new ComponentName("android", "FullBackupAgent");
13699 
13700             // startProcessLocked() returns existing proc's record if it's already running
13701             ProcessRecord proc = startProcessLocked(app.processName, app,
13702                     false, 0,
13703                     new HostingRecord(HostingRecord.HOSTING_TYPE_BACKUP, hostingName),
13704                     ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false);
13705             if (proc == null) {
13706                 Slog.e(TAG, "Unable to start backup agent process " + r);
13707                 return false;
13708             }
13709 
13710             // If the app is a regular app (uid >= 10000) and not the system server or phone
13711             // process, etc, then mark it as being in full backup so that certain calls to the
13712             // process can be blocked. This is not reset to false anywhere because we kill the
13713             // process after the full backup is done and the ProcessRecord will vaporize anyway.
13714             if (UserHandle.isApp(app.uid) &&
13715                     backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) {
13716                 proc.setInFullBackup(true);
13717             }
13718             r.app = proc;
13719             final BackupRecord backupTarget = mBackupTargets.get(targetUserId);
13720             oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
13721             newBackupUid = proc.isInFullBackup() ? r.appInfo.uid : -1;
13722             mBackupTargets.put(targetUserId, r);
13723 
13724             proc.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP);
13725 
13726             // Try not to kill the process during backup
13727             updateOomAdjLocked(proc, OOM_ADJ_REASON_BACKUP);
13728 
13729             // If the process is already attached, schedule the creation of the backup agent now.
13730             // If it is not yet live, this will be done when it attaches to the framework.
13731             final IApplicationThread thread = proc.getThread();
13732             if (thread != null) {
13733                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc);
13734                 try {
13735                     thread.scheduleCreateBackupAgent(app, backupMode, targetUserId,
13736                             backupDestination);
13737                 } catch (RemoteException e) {
13738                     // Will time out on the backup manager side
13739                 }
13740             } else {
13741                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach");
13742             }
13743             // Invariants: at this point, the target app process exists and the application
13744             // is either already running or in the process of coming up.  mBackupTarget and
13745             // mBackupAppName describe the app, so that when it binds back to the AM we
13746             // know that it's scheduled for a backup-agent operation.
13747         }
13748 
13749         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
13750         if (oldBackupUid != -1) {
13751             js.removeBackingUpUid(oldBackupUid);
13752         }
13753         if (newBackupUid != -1) {
13754             js.addBackingUpUid(newBackupUid);
13755         }
13756 
13757         return true;
13758     }
13759 
clearPendingBackup(int userId)13760     private void clearPendingBackup(int userId) {
13761         if (DEBUG_BACKUP) {
13762             Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = "
13763                     + Binder.getCallingUid() + " uid = " + Process.myUid());
13764         }
13765 
13766         synchronized (this) {
13767             final int indexOfKey = mBackupTargets.indexOfKey(userId);
13768             if (indexOfKey >= 0) {
13769                 final BackupRecord backupTarget = mBackupTargets.valueAt(indexOfKey);
13770                 if (backupTarget != null && backupTarget.app != null) {
13771                     backupTarget.app.mProfile.clearHostingComponentType(
13772                             HOSTING_COMPONENT_TYPE_BACKUP);
13773                 }
13774                 mBackupTargets.removeAt(indexOfKey);
13775             }
13776         }
13777 
13778         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
13779         js.clearAllBackingUpUids();
13780     }
13781 
13782     // A backup agent has just come up
13783     @Override
backupAgentCreated(String agentPackageName, IBinder agent, int userId)13784     public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) {
13785         final int callingUid = Binder.getCallingUid();
13786         enforceCallingPackage(agentPackageName, callingUid);
13787 
13788         // Resolve the target user id and enforce permissions.
13789         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid,
13790                 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null);
13791         if (DEBUG_BACKUP) {
13792             Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent
13793                     + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId
13794                     + " callingUid = " + callingUid + " uid = " + Process.myUid());
13795         }
13796 
13797         synchronized(this) {
13798             final BackupRecord backupTarget = mBackupTargets.get(userId);
13799             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
13800             if (!agentPackageName.equals(backupAppName)) {
13801                 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
13802                 return;
13803             }
13804         }
13805 
13806         final long oldIdent = Binder.clearCallingIdentity();
13807         try {
13808             IBackupManager bm = IBackupManager.Stub.asInterface(
13809                     ServiceManager.getService(Context.BACKUP_SERVICE));
13810             bm.agentConnectedForUser(userId, agentPackageName, agent);
13811         } catch (RemoteException e) {
13812             // can't happen; the backup manager service is local
13813         } catch (Exception e) {
13814             Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
13815             e.printStackTrace();
13816         } finally {
13817             Binder.restoreCallingIdentity(oldIdent);
13818         }
13819     }
13820 
13821     // done with this agent
unbindBackupAgent(ApplicationInfo appInfo)13822     public void unbindBackupAgent(ApplicationInfo appInfo) {
13823         if (DEBUG_BACKUP) {
13824             Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = "
13825                     + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = "
13826                     + Process.myUid());
13827         }
13828 
13829         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent");
13830         if (appInfo == null) {
13831             Slog.w(TAG, "unbind backup agent for null app");
13832             return;
13833         }
13834 
13835         int oldBackupUid;
13836 
13837         final int userId = UserHandle.getUserId(appInfo.uid);
13838         synchronized(this) {
13839             final BackupRecord backupTarget = mBackupTargets.get(userId);
13840             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
13841             try {
13842                 if (backupAppName == null) {
13843                     Slog.w(TAG, "Unbinding backup agent with no active backup");
13844                     return;
13845                 }
13846 
13847                 if (!backupAppName.equals(appInfo.packageName)) {
13848                     Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
13849                     return;
13850                 }
13851 
13852                 // Not backing this app up any more; reset its OOM adjustment
13853                 final ProcessRecord proc = backupTarget.app;
13854                 updateOomAdjLocked(proc, OOM_ADJ_REASON_BACKUP);
13855                 proc.setInFullBackup(false);
13856                 proc.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP);
13857 
13858                 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
13859 
13860                 // If the app crashed during backup, 'thread' will be null here
13861                 final IApplicationThread thread = proc.getThread();
13862                 if (thread != null) {
13863                     try {
13864                         thread.scheduleDestroyBackupAgent(appInfo, userId);
13865                     } catch (Exception e) {
13866                         Slog.e(TAG, "Exception when unbinding backup agent:");
13867                         e.printStackTrace();
13868                     }
13869                 }
13870             } finally {
13871                 mBackupTargets.delete(userId);
13872             }
13873         }
13874 
13875         if (oldBackupUid != -1) {
13876             JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
13877             js.removeBackingUpUid(oldBackupUid);
13878         }
13879     }
13880 
13881     // =========================================================
13882     // BROADCASTS
13883     // =========================================================
13884 
isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)13885     private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) {
13886         if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) {
13887             return false;
13888         }
13889         // Easy case -- we have the app's ProcessRecord.
13890         if (record != null) {
13891             return record.info.isInstantApp();
13892         }
13893         // Otherwise check with PackageManager.
13894         IPackageManager pm = AppGlobals.getPackageManager();
13895         try {
13896             if (callerPackage == null) {
13897                 final String[] packageNames = pm.getPackagesForUid(uid);
13898                 if (packageNames == null || packageNames.length == 0) {
13899                     throw new IllegalArgumentException("Unable to determine caller package name");
13900                 }
13901                 // Instant Apps can't use shared uids, so its safe to only check the first package.
13902                 callerPackage = packageNames[0];
13903             }
13904             mAppOpsService.checkPackage(uid, callerPackage);
13905             return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid));
13906         } catch (RemoteException e) {
13907             Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e);
13908             return true;
13909         }
13910     }
13911 
13912     /**
13913      * @deprecated Use {@link #registerReceiverWithFeature}
13914      */
13915     @Deprecated
registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)13916     public Intent registerReceiver(IApplicationThread caller, String callerPackage,
13917             IIntentReceiver receiver, IntentFilter filter, String permission, int userId,
13918             int flags) {
13919         return registerReceiverWithFeature(caller, callerPackage, null, null,
13920                 receiver, filter, permission, userId, flags);
13921     }
13922 
registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)13923     public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage,
13924             String callerFeatureId, String receiverId, IIntentReceiver receiver,
13925             IntentFilter filter, String permission, int userId, int flags) {
13926         enforceNotIsolatedCaller("registerReceiver");
13927         ArrayList<StickyBroadcast> stickyBroadcasts = null;
13928         ProcessRecord callerApp = null;
13929         final boolean visibleToInstantApps
13930                 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
13931 
13932         int callingUid;
13933         int callingPid;
13934         boolean instantApp;
13935         synchronized(this) {
13936             callerApp = getRecordForAppLOSP(caller);
13937             if (callerApp == null) {
13938                 Slog.w(TAG, "registerReceiverWithFeature: no app for " + caller);
13939                 return null;
13940             }
13941             if (callerApp.info.uid != SYSTEM_UID
13942                     && !callerApp.getPkgList().containsKey(callerPackage)
13943                     && !"android".equals(callerPackage)) {
13944                 throw new SecurityException("Given caller package " + callerPackage
13945                         + " is not running in process " + callerApp);
13946             }
13947             callingUid = callerApp.info.uid;
13948             callingPid = callerApp.getPid();
13949 
13950             instantApp = isInstantApp(callerApp, callerPackage, callingUid);
13951             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
13952                     ALLOW_FULL_ONLY, "registerReceiver", callerPackage);
13953 
13954             // Warn if system internals are registering for important broadcasts
13955             // without also using a priority to ensure they process the event
13956             // before normal apps hear about it
13957             if (UserHandle.isCore(callingUid)) {
13958                 final int priority = filter.getPriority();
13959                 final boolean systemPriority = (priority >= IntentFilter.SYSTEM_HIGH_PRIORITY)
13960                         || (priority <= IntentFilter.SYSTEM_LOW_PRIORITY);
13961                 if (!systemPriority) {
13962                     final int N = filter.countActions();
13963                     for (int i = 0; i < N; i++) {
13964                         // TODO: expand to additional important broadcasts over time
13965                         final String action = filter.getAction(i);
13966                         if (action.startsWith("android.intent.action.USER_")
13967                                 || action.startsWith("android.intent.action.PACKAGE_")
13968                                 || action.startsWith("android.intent.action.UID_")
13969                                 || action.startsWith("android.intent.action.EXTERNAL_")
13970                                 || action.startsWith("android.bluetooth.")) {
13971                             if (DEBUG_BROADCAST) {
13972                                 Slog.wtf(TAG,
13973                                         "System internals registering for " + filter.toLongString()
13974                                                 + " with app priority; this will race with apps!",
13975                                         new Throwable());
13976                             }
13977 
13978                             // When undefined, assume that system internals need
13979                             // to hear about the event first; they can use
13980                             // SYSTEM_LOW_PRIORITY if they need to hear last
13981                             if (priority == 0) {
13982                                 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
13983                             }
13984                             break;
13985                         }
13986                     }
13987                 }
13988             }
13989 
13990             Iterator<String> actions = filter.actionsIterator();
13991             if (actions == null) {
13992                 ArrayList<String> noAction = new ArrayList<String>(1);
13993                 noAction.add(null);
13994                 actions = noAction.iterator();
13995             }
13996             boolean onlyProtectedBroadcasts = true;
13997 
13998             // Collect stickies of users and check if broadcast is only registered for protected
13999             // broadcasts
14000             int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) };
14001             while (actions.hasNext()) {
14002                 String action = actions.next();
14003                 for (int id : userIds) {
14004                     ArrayMap<String, ArrayList<StickyBroadcast>> stickies =
14005                             mStickyBroadcasts.get(id);
14006                     if (stickies != null) {
14007                         ArrayList<StickyBroadcast> broadcasts = stickies.get(action);
14008                         if (broadcasts != null) {
14009                             if (stickyBroadcasts == null) {
14010                                 stickyBroadcasts = new ArrayList<>();
14011                             }
14012                             stickyBroadcasts.addAll(broadcasts);
14013                         }
14014                     }
14015                 }
14016                 if (onlyProtectedBroadcasts) {
14017                     try {
14018                         onlyProtectedBroadcasts &=
14019                                 AppGlobals.getPackageManager().isProtectedBroadcast(action);
14020                     } catch (RemoteException e) {
14021                         onlyProtectedBroadcasts = false;
14022                         Slog.w(TAG, "Remote exception", e);
14023                     }
14024                 }
14025             }
14026 
14027             if (Process.isSdkSandboxUid(Binder.getCallingUid())) {
14028                 SdkSandboxManagerLocal sdkSandboxManagerLocal =
14029                         LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class);
14030                 if (sdkSandboxManagerLocal == null) {
14031                     throw new IllegalStateException("SdkSandboxManagerLocal not found when checking"
14032                             + " whether SDK sandbox uid can register to broadcast receivers.");
14033                 }
14034                 if (!sdkSandboxManagerLocal.canRegisterBroadcastReceiver(
14035                         /*IntentFilter=*/ filter, flags, onlyProtectedBroadcasts)) {
14036                     throw new SecurityException("SDK sandbox not allowed to register receiver"
14037                             + " with the given IntentFilter: " + filter.toLongString());
14038                 }
14039             }
14040 
14041             // If the change is enabled, but neither exported or not exported is set, we need to log
14042             // an error so the consumer can know to explicitly set the value for their flag.
14043             // If the caller is registering for a sticky broadcast with a null receiver, we won't
14044             // require a flag
14045             final boolean explicitExportStateDefined =
14046                     (flags & (Context.RECEIVER_EXPORTED | Context.RECEIVER_NOT_EXPORTED)) != 0;
14047             if (((flags & Context.RECEIVER_EXPORTED) != 0) && (
14048                     (flags & Context.RECEIVER_NOT_EXPORTED) != 0)) {
14049                 throw new IllegalArgumentException(
14050                         "Receiver can't specify both RECEIVER_EXPORTED and RECEIVER_NOT_EXPORTED"
14051                                 + "flag");
14052             }
14053 
14054             // Don't enforce the flag check if we're EITHER registering for only protected
14055             // broadcasts, or the receiver is null (a sticky broadcast). Sticky broadcasts should
14056             // not be used generally, so we will be marking them as exported by default
14057             boolean requireExplicitFlagForDynamicReceivers = CompatChanges.isChangeEnabled(
14058                     DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED, callingUid);
14059 
14060             // A receiver that is visible to instant apps must also be exported.
14061             final boolean unexportedReceiverVisibleToInstantApps =
14062                     ((flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0) && (
14063                             (flags & Context.RECEIVER_NOT_EXPORTED) != 0);
14064             if (unexportedReceiverVisibleToInstantApps && requireExplicitFlagForDynamicReceivers) {
14065                 throw new IllegalArgumentException(
14066                         "Receiver can't specify both RECEIVER_VISIBLE_TO_INSTANT_APPS and "
14067                                 + "RECEIVER_NOT_EXPORTED flag");
14068             }
14069 
14070             if (!onlyProtectedBroadcasts) {
14071                 if (receiver == null && !explicitExportStateDefined) {
14072                     // sticky broadcast, no flag specified (flag isn't required)
14073                     flags |= Context.RECEIVER_EXPORTED;
14074                 } else if (requireExplicitFlagForDynamicReceivers && !explicitExportStateDefined) {
14075                     throw new SecurityException(
14076                             callerPackage + ": One of RECEIVER_EXPORTED or "
14077                                     + "RECEIVER_NOT_EXPORTED should be specified when a receiver "
14078                                     + "isn't being registered exclusively for system broadcasts");
14079                     // Assume default behavior-- flag check is not enforced
14080                 } else if (!requireExplicitFlagForDynamicReceivers && (
14081                         (flags & Context.RECEIVER_NOT_EXPORTED) == 0)) {
14082                     // Change is not enabled, assume exported unless otherwise specified.
14083                     flags |= Context.RECEIVER_EXPORTED;
14084                 }
14085             } else if ((flags & Context.RECEIVER_NOT_EXPORTED) == 0) {
14086                 flags |= Context.RECEIVER_EXPORTED;
14087             }
14088         }
14089 
14090         // Dynamic receivers are exported by default for versions prior to T
14091         final boolean exported = (flags & Context.RECEIVER_EXPORTED) != 0;
14092 
14093         ArrayList<StickyBroadcast> allSticky = null;
14094         if (stickyBroadcasts != null) {
14095             final ContentResolver resolver = mContext.getContentResolver();
14096             // Look for any matching sticky broadcasts...
14097             for (int i = 0, N = stickyBroadcasts.size(); i < N; i++) {
14098                 final StickyBroadcast broadcast = stickyBroadcasts.get(i);
14099                 Intent intent = broadcast.intent;
14100                 // Don't provided intents that aren't available to instant apps.
14101                 if (instantApp &&
14102                         (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) {
14103                     continue;
14104                 }
14105                 // If intent has scheme "content", it will need to access
14106                 // provider that needs to lock mProviderMap in ActivityThread
14107                 // and also it may need to wait application response, so we
14108                 // cannot lock ActivityManagerService here.
14109                 if (filter.match(resolver, intent, true, TAG) >= 0) {
14110                     if (allSticky == null) {
14111                         allSticky = new ArrayList<>();
14112                     }
14113                     allSticky.add(broadcast);
14114                 }
14115             }
14116         }
14117 
14118         // The first sticky in the list is returned directly back to the client.
14119         Intent sticky = allSticky != null ? allSticky.get(0).intent : null;
14120         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky);
14121         if (receiver == null) {
14122             return sticky;
14123         }
14124 
14125         // SafetyNet logging for b/177931370. If any process other than system_server tries to
14126         // listen to this broadcast action, then log it.
14127         if (callingPid != Process.myPid()) {
14128             if (filter.hasAction("com.android.server.net.action.SNOOZE_WARNING")
14129                     || filter.hasAction("com.android.server.net.action.SNOOZE_RAPID")) {
14130                 EventLog.writeEvent(0x534e4554, "177931370", callingUid, "");
14131             }
14132         }
14133 
14134         synchronized (this) {
14135             IApplicationThread thread;
14136             if (callerApp != null && ((thread = callerApp.getThread()) == null
14137                     || thread.asBinder() != caller.asBinder())) {
14138                 // Original caller already died
14139                 return null;
14140             }
14141             ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14142             if (rl == null) {
14143                 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
14144                         userId, receiver);
14145                 if (rl.app != null) {
14146                     final int totalReceiversForApp = rl.app.mReceivers.numberOfReceivers();
14147                     if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) {
14148                         throw new IllegalStateException("Too many receivers, total of "
14149                                 + totalReceiversForApp + ", registered for pid: "
14150                                 + rl.pid + ", callerPackage: " + callerPackage);
14151                     }
14152                     rl.app.mReceivers.addReceiver(rl);
14153                 } else {
14154                     try {
14155                         receiver.asBinder().linkToDeath(rl, 0);
14156                     } catch (RemoteException e) {
14157                         return sticky;
14158                     }
14159                     rl.linkedToDeath = true;
14160                 }
14161                 mRegisteredReceivers.put(receiver.asBinder(), rl);
14162             } else if (rl.uid != callingUid) {
14163                 throw new IllegalArgumentException(
14164                         "Receiver requested to register for uid " + callingUid
14165                         + " was previously registered for uid " + rl.uid
14166                         + " callerPackage is " + callerPackage);
14167             } else if (rl.pid != callingPid) {
14168                 throw new IllegalArgumentException(
14169                         "Receiver requested to register for pid " + callingPid
14170                         + " was previously registered for pid " + rl.pid
14171                         + " callerPackage is " + callerPackage);
14172             } else if (rl.userId != userId) {
14173                 throw new IllegalArgumentException(
14174                         "Receiver requested to register for user " + userId
14175                         + " was previously registered for user " + rl.userId
14176                         + " callerPackage is " + callerPackage);
14177             }
14178             BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId,
14179                     receiverId, permission, callingUid, userId, instantApp, visibleToInstantApps,
14180                     exported);
14181             if (rl.containsFilter(filter)) {
14182                 Slog.w(TAG, "Receiver with filter " + filter
14183                         + " already registered for pid " + rl.pid
14184                         + ", callerPackage is " + callerPackage);
14185             } else {
14186                 rl.add(bf);
14187                 if (!bf.debugCheck()) {
14188                     Slog.w(TAG, "==> For Dynamic broadcast");
14189                 }
14190                 mReceiverResolver.addFilter(getPackageManagerInternal().snapshot(), bf);
14191             }
14192 
14193             // Enqueue broadcasts for all existing stickies that match
14194             // this filter.
14195             if (allSticky != null) {
14196                 ArrayList receivers = new ArrayList();
14197                 receivers.add(bf);
14198                 sticky = null;
14199 
14200                 final int stickyCount = allSticky.size();
14201                 for (int i = 0; i < stickyCount; i++) {
14202                     final StickyBroadcast broadcast = allSticky.get(i);
14203                     final int originalStickyCallingUid = allSticky.get(i).originalCallingUid;
14204                     // TODO(b/281889567): consider using checkComponentPermission instead of
14205                     //  canAccessUnexportedComponents
14206                     if (sticky == null && (exported || originalStickyCallingUid == callingUid
14207                             || ActivityManager.canAccessUnexportedComponents(
14208                             originalStickyCallingUid))) {
14209                         sticky = broadcast.intent;
14210                     }
14211                     BroadcastQueue queue = broadcastQueueForIntent(broadcast.intent);
14212                     BroadcastRecord r = new BroadcastRecord(queue, broadcast.intent, null,
14213                             null, null, -1, -1, false, null, null, null, null, OP_NONE,
14214                             BroadcastOptions.makeWithDeferUntilActive(broadcast.deferUntilActive),
14215                             receivers, null, null, 0, null, null, false, true, true, -1,
14216                             originalStickyCallingUid, BackgroundStartPrivileges.NONE,
14217                             false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */,
14218                             null /* filterExtrasForReceiver */,
14219                             broadcast.originalCallingAppProcessState);
14220                     queue.enqueueBroadcastLocked(r);
14221                 }
14222             }
14223 
14224             return sticky;
14225         }
14226     }
14227 
unregisterReceiver(IIntentReceiver receiver)14228     public void unregisterReceiver(IIntentReceiver receiver) {
14229         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver);
14230 
14231         final long origId = Binder.clearCallingIdentity();
14232         try {
14233             boolean doTrim = false;
14234             synchronized(this) {
14235                 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14236                 if (rl != null) {
14237                     final BroadcastRecord r = rl.curBroadcast;
14238                     if (r != null) {
14239                         final boolean doNext = r.queue.finishReceiverLocked(
14240                                 rl.app, r.resultCode, r.resultData, r.resultExtras,
14241                                 r.resultAbort, false);
14242                         if (doNext) {
14243                             doTrim = true;
14244                         }
14245                     }
14246                     if (rl.app != null) {
14247                         rl.app.mReceivers.removeReceiver(rl);
14248                     }
14249                     removeReceiverLocked(rl);
14250                     if (rl.linkedToDeath) {
14251                         rl.linkedToDeath = false;
14252                         rl.receiver.asBinder().unlinkToDeath(rl, 0);
14253                     }
14254                 }
14255 
14256                 // If we actually concluded any broadcasts, we might now be able
14257                 // to trim the recipients' apps from our working set
14258                 if (doTrim) {
14259                     trimApplicationsLocked(false, OOM_ADJ_REASON_FINISH_RECEIVER);
14260                     return;
14261                 }
14262             }
14263 
14264         } finally {
14265             Binder.restoreCallingIdentity(origId);
14266         }
14267     }
14268 
removeReceiverLocked(ReceiverList rl)14269     void removeReceiverLocked(ReceiverList rl) {
14270         mRegisteredReceivers.remove(rl.receiver.asBinder());
14271         for (int i = rl.size() - 1; i >= 0; i--) {
14272             mReceiverResolver.removeFilter(rl.get(i));
14273         }
14274     }
14275 
sendPackageBroadcastLocked(int cmd, String[] packages, int userId)14276     private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
14277         mProcessList.sendPackageBroadcastLocked(cmd, packages, userId);
14278     }
14279 
collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users, int[] broadcastAllowList)14280     private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
14281             int callingUid, int[] users, int[] broadcastAllowList) {
14282         // TODO: come back and remove this assumption to triage all broadcasts
14283         int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING;
14284 
14285         List<ResolveInfo> receivers = null;
14286         HashSet<ComponentName> singleUserReceivers = null;
14287         boolean scannedFirstReceivers = false;
14288         for (int user : users) {
14289             // Skip users that have Shell restrictions
14290             if (callingUid == SHELL_UID
14291                     && mUserController.hasUserRestriction(
14292                     UserManager.DISALLOW_DEBUGGING_FEATURES, user)) {
14293                 continue;
14294             }
14295             List<ResolveInfo> newReceivers = mPackageManagerInt.queryIntentReceivers(
14296                     intent, resolvedType, pmFlags, callingUid, user, true /* forSend */);
14297             if (user != UserHandle.USER_SYSTEM && newReceivers != null) {
14298                 // If this is not the system user, we need to check for
14299                 // any receivers that should be filtered out.
14300                 for (int i = 0; i < newReceivers.size(); i++) {
14301                     ResolveInfo ri = newReceivers.get(i);
14302                     if ((ri.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
14303                         newReceivers.remove(i);
14304                         i--;
14305                     }
14306                 }
14307             }
14308             // Replace the alias receivers with their targets.
14309             if (newReceivers != null) {
14310                 for (int i = newReceivers.size() - 1; i >= 0; i--) {
14311                     final ResolveInfo ri = newReceivers.get(i);
14312                     final Resolution<ResolveInfo> resolution =
14313                             mComponentAliasResolver.resolveReceiver(intent, ri, resolvedType,
14314                                     pmFlags, user, callingUid, true /* forSend */);
14315                     if (resolution == null) {
14316                         // It was an alias, but the target was not found.
14317                         newReceivers.remove(i);
14318                         continue;
14319                     }
14320                     if (resolution.isAlias()) {
14321                         newReceivers.set(i, resolution.getTarget());
14322                     }
14323                 }
14324             }
14325             if (newReceivers != null && newReceivers.size() == 0) {
14326                 newReceivers = null;
14327             }
14328 
14329             if (receivers == null) {
14330                 receivers = newReceivers;
14331             } else if (newReceivers != null) {
14332                 // We need to concatenate the additional receivers
14333                 // found with what we have do far.  This would be easy,
14334                 // but we also need to de-dup any receivers that are
14335                 // singleUser.
14336                 if (!scannedFirstReceivers) {
14337                     // Collect any single user receivers we had already retrieved.
14338                     scannedFirstReceivers = true;
14339                     for (int i = 0; i < receivers.size(); i++) {
14340                         ResolveInfo ri = receivers.get(i);
14341                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
14342                             ComponentName cn = new ComponentName(
14343                                     ri.activityInfo.packageName, ri.activityInfo.name);
14344                             if (singleUserReceivers == null) {
14345                                 singleUserReceivers = new HashSet<ComponentName>();
14346                             }
14347                             singleUserReceivers.add(cn);
14348                         }
14349                     }
14350                 }
14351                 // Add the new results to the existing results, tracking
14352                 // and de-dupping single user receivers.
14353                 for (int i = 0; i < newReceivers.size(); i++) {
14354                     ResolveInfo ri = newReceivers.get(i);
14355                     if ((ri.activityInfo.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
14356                         ComponentName cn = new ComponentName(
14357                                 ri.activityInfo.packageName, ri.activityInfo.name);
14358                         if (singleUserReceivers == null) {
14359                             singleUserReceivers = new HashSet<ComponentName>();
14360                         }
14361                         if (!singleUserReceivers.contains(cn)) {
14362                             singleUserReceivers.add(cn);
14363                             receivers.add(ri);
14364                         }
14365                     } else {
14366                         receivers.add(ri);
14367                     }
14368                 }
14369             }
14370         }
14371         if (receivers != null && broadcastAllowList != null) {
14372             for (int i = receivers.size() - 1; i >= 0; i--) {
14373                 final int receiverAppId = UserHandle.getAppId(
14374                         receivers.get(i).activityInfo.applicationInfo.uid);
14375                 if (receiverAppId >= Process.FIRST_APPLICATION_UID
14376                         && Arrays.binarySearch(broadcastAllowList, receiverAppId) < 0) {
14377                     receivers.remove(i);
14378                 }
14379             }
14380         }
14381         return receivers;
14382     }
14383 
checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)14384     private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp,
14385             String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) {
14386         if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
14387             // Don't yell about broadcasts sent via shell
14388             return;
14389         }
14390 
14391         final String action = intent.getAction();
14392         if (isProtectedBroadcast
14393                 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
14394                 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action)
14395                 || Intent.ACTION_MEDIA_BUTTON.equals(action)
14396                 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action)
14397                 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action)
14398                 || Intent.ACTION_MASTER_CLEAR.equals(action)
14399                 || Intent.ACTION_FACTORY_RESET.equals(action)
14400                 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
14401                 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)
14402                 || TelephonyManager.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action)
14403                 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action)
14404                 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action)
14405                 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) {
14406             // Broadcast is either protected, or it's a public action that
14407             // we've relaxed, so it's fine for system internals to send.
14408             return;
14409         }
14410 
14411         // This broadcast may be a problem...  but there are often system components that
14412         // want to send an internal broadcast to themselves, which is annoying to have to
14413         // explicitly list each action as a protected broadcast, so we will check for that
14414         // one safe case and allow it: an explicit broadcast, only being received by something
14415         // that has protected itself.
14416         if (intent.getPackage() != null || intent.getComponent() != null) {
14417             if (receivers == null || receivers.size() == 0) {
14418                 // Intent is explicit and there's no receivers.
14419                 // This happens, e.g. , when a system component sends a broadcast to
14420                 // its own runtime receiver, and there's no manifest receivers for it,
14421                 // because this method is called twice for each broadcast,
14422                 // for runtime receivers and manifest receivers and the later check would find
14423                 // no receivers.
14424                 return;
14425             }
14426             boolean allProtected = true;
14427             for (int i = receivers.size()-1; i >= 0; i--) {
14428                 Object target = receivers.get(i);
14429                 if (target instanceof ResolveInfo) {
14430                     ResolveInfo ri = (ResolveInfo)target;
14431                     if (ri.activityInfo.exported && ri.activityInfo.permission == null) {
14432                         allProtected = false;
14433                         break;
14434                     }
14435                 } else {
14436                     BroadcastFilter bf = (BroadcastFilter)target;
14437                     if (bf.exported && bf.requiredPermission == null) {
14438                         allProtected = false;
14439                         break;
14440                     }
14441                 }
14442             }
14443             if (allProtected) {
14444                 // All safe!
14445                 return;
14446             }
14447         }
14448 
14449         // The vast majority of broadcasts sent from system internals
14450         // should be protected to avoid security holes, so yell loudly
14451         // to ensure we examine these cases.
14452         if (callerApp != null) {
14453             Log.wtf(TAG, "Sending non-protected broadcast " + action
14454                             + " from system " + callerApp.toShortString() + " pkg " + callerPackage,
14455                     new Throwable());
14456         } else {
14457             Log.wtf(TAG, "Sending non-protected broadcast " + action
14458                             + " from system uid " + UserHandle.formatUid(callingUid)
14459                             + " pkg " + callerPackage,
14460                     new Throwable());
14461         }
14462     }
14463 
14464     // Apply permission policy around the use of specific broadcast options
enforceBroadcastOptionPermissionsInternal( @ullable Bundle options, int callingUid)14465     void enforceBroadcastOptionPermissionsInternal(
14466             @Nullable Bundle options, int callingUid) {
14467         enforceBroadcastOptionPermissionsInternal(BroadcastOptions.fromBundleNullable(options),
14468                 callingUid);
14469     }
14470 
enforceBroadcastOptionPermissionsInternal( @ullable BroadcastOptions options, int callingUid)14471     void enforceBroadcastOptionPermissionsInternal(
14472             @Nullable BroadcastOptions options, int callingUid) {
14473         if (options != null && callingUid != Process.SYSTEM_UID) {
14474             if (options.isAlarmBroadcast()) {
14475                 if (DEBUG_BROADCAST_LIGHT) {
14476                     Slog.w(TAG, "Non-system caller " + callingUid
14477                             + " may not flag broadcast as alarm");
14478                 }
14479                 throw new SecurityException(
14480                         "Non-system callers may not flag broadcasts as alarm");
14481             }
14482             if (options.isInteractive()) {
14483                 enforceCallingPermission(
14484                         android.Manifest.permission.BROADCAST_OPTION_INTERACTIVE,
14485                         "setInteractive");
14486             }
14487         }
14488     }
14489 
14490     @GuardedBy("this")
broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, String callerFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId)14491     final int broadcastIntentLocked(ProcessRecord callerApp,
14492             String callerPackage, String callerFeatureId, Intent intent, String resolvedType,
14493             IIntentReceiver resultTo, int resultCode, String resultData,
14494             Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions,
14495             String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered,
14496             boolean sticky, int callingPid,
14497             int callingUid, int realCallingUid, int realCallingPid, int userId) {
14498         return broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, intent,
14499                 resolvedType, null, resultTo, resultCode, resultData, resultExtras,
14500                 requiredPermissions, excludedPermissions, excludedPackages, appOp, bOptions,
14501                 ordered, sticky, callingPid, callingUid, realCallingUid, realCallingPid, userId,
14502                 BackgroundStartPrivileges.NONE,
14503                 null /* broadcastAllowList */, null /* filterExtrasForReceiver */);
14504     }
14505 
14506     @GuardedBy("this")
broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver)14507     final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage,
14508             @Nullable String callerFeatureId, Intent intent, String resolvedType,
14509             ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData,
14510             Bundle resultExtras, String[] requiredPermissions,
14511             String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions,
14512             boolean ordered, boolean sticky, int callingPid, int callingUid,
14513             int realCallingUid, int realCallingPid, int userId,
14514             BackgroundStartPrivileges backgroundStartPrivileges,
14515             @Nullable int[] broadcastAllowList,
14516             @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver) {
14517         final int cookie = BroadcastQueue.traceBegin("broadcastIntentLockedTraced");
14518         final int res = broadcastIntentLockedTraced(callerApp, callerPackage, callerFeatureId,
14519                 intent, resolvedType, resultToApp, resultTo, resultCode, resultData, resultExtras,
14520                 requiredPermissions, excludedPermissions, excludedPackages, appOp,
14521                 BroadcastOptions.fromBundleNullable(bOptions), ordered, sticky,
14522                 callingPid, callingUid, realCallingUid, realCallingPid, userId,
14523                 backgroundStartPrivileges, broadcastAllowList, filterExtrasForReceiver);
14524         BroadcastQueue.traceEnd(cookie);
14525         return res;
14526     }
14527 
14528     @GuardedBy("this")
broadcastIntentLockedTraced(ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, BroadcastOptions brOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver)14529     final int broadcastIntentLockedTraced(ProcessRecord callerApp, String callerPackage,
14530             @Nullable String callerFeatureId, Intent intent, String resolvedType,
14531             ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData,
14532             Bundle resultExtras, String[] requiredPermissions,
14533             String[] excludedPermissions, String[] excludedPackages, int appOp,
14534             BroadcastOptions brOptions, boolean ordered, boolean sticky, int callingPid,
14535             int callingUid, int realCallingUid, int realCallingPid, int userId,
14536             BackgroundStartPrivileges backgroundStartPrivileges,
14537             @Nullable int[] broadcastAllowList,
14538             @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver) {
14539         // Ensure all internal loopers are registered for idle checks
14540         BroadcastLoopers.addMyLooper();
14541 
14542         if (Process.isSdkSandboxUid(realCallingUid)) {
14543             final SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager(
14544                     SdkSandboxManagerLocal.class);
14545             if (sdkSandboxManagerLocal == null) {
14546                 throw new IllegalStateException("SdkSandboxManagerLocal not found when sending"
14547                         + " a broadcast from an SDK sandbox uid.");
14548             }
14549             if (!sdkSandboxManagerLocal.canSendBroadcast(intent)) {
14550                 throw new SecurityException(
14551                         "Intent " + intent.getAction() + " may not be broadcast from an SDK sandbox"
14552                         + " uid. Given caller package " + callerPackage + " (pid=" + callingPid
14553                         + ", realCallingUid=" + realCallingUid + ", callingUid= " + callingUid
14554                         + ")");
14555             }
14556         }
14557 
14558         if ((resultTo != null) && (resultToApp == null)) {
14559             if (resultTo.asBinder() instanceof BinderProxy) {
14560                 // Warn when requesting results without a way to deliver them
14561                 Slog.wtf(TAG, "Sending broadcast " + intent.getAction()
14562                         + " with resultTo requires resultToApp", new Throwable());
14563             } else {
14564                 // If not a BinderProxy above, then resultTo is an in-process
14565                 // receiver, so splice in system_server process
14566                 resultToApp = getProcessRecordLocked("system", SYSTEM_UID);
14567             }
14568         }
14569 
14570         intent = new Intent(intent);
14571 
14572         final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid);
14573         // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS
14574         if (callerInstantApp) {
14575             intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
14576         }
14577 
14578         if (userId == UserHandle.USER_ALL && broadcastAllowList != null) {
14579                 Slog.e(TAG, "broadcastAllowList only applies when sending to individual users. "
14580                         + "Assuming restrictive whitelist.");
14581                 broadcastAllowList = new int[]{};
14582         }
14583 
14584         // By default broadcasts do not go to stopped apps.
14585         intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
14586 
14587         // If we have not finished booting, don't allow this to launch new processes.
14588         if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
14589             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14590         }
14591 
14592         if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
14593                 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
14594                         + " ordered=" + ordered + " userid=" + userId
14595                         + " options=" + (brOptions == null ? "null" : brOptions.toBundle()));
14596         if ((resultTo != null) && !ordered) {
14597             if (!mEnableModernQueue) {
14598                 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
14599             }
14600             if (!UserHandle.isCore(callingUid)) {
14601                 String msg = "Unauthorized unordered resultTo broadcast "
14602                              + intent + " sent from uid " + callingUid;
14603                 Slog.w(TAG, msg);
14604                 throw new SecurityException(msg);
14605             }
14606         }
14607 
14608         userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
14609                 ALLOW_NON_FULL, "broadcast", callerPackage);
14610 
14611         // Make sure that the user who is receiving this broadcast or its parent is running.
14612         // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps.
14613         if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) {
14614             if ((callingUid != SYSTEM_UID
14615                     || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0)
14616                     && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
14617                 Slog.w(TAG, "Skipping broadcast of " + intent
14618                         + ": user " + userId + " and its parent (if any) are stopped");
14619                 scheduleCanceledResultTo(resultToApp, resultTo, intent, userId,
14620                         brOptions, callingUid, callerPackage);
14621                 return ActivityManager.BROADCAST_FAILED_USER_STOPPED;
14622             }
14623         }
14624 
14625         final String action = intent.getAction();
14626         if (brOptions != null) {
14627             if (brOptions.getTemporaryAppAllowlistDuration() > 0) {
14628                 // See if the caller is allowed to do this.  Note we are checking against
14629                 // the actual real caller (not whoever provided the operation as say a
14630                 // PendingIntent), because that who is actually supplied the arguments.
14631                 if (checkComponentPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
14632                         realCallingPid, realCallingUid, -1, true)
14633                         != PackageManager.PERMISSION_GRANTED
14634                         && checkComponentPermission(START_ACTIVITIES_FROM_BACKGROUND,
14635                         realCallingPid, realCallingUid, -1, true)
14636                         != PackageManager.PERMISSION_GRANTED
14637                         && checkComponentPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND,
14638                         realCallingPid, realCallingUid, -1, true)
14639                         != PackageManager.PERMISSION_GRANTED) {
14640                     String msg = "Permission Denial: " + intent.getAction()
14641                             + " broadcast from " + callerPackage + " (pid=" + callingPid
14642                             + ", uid=" + callingUid + ")"
14643                             + " requires "
14644                             + CHANGE_DEVICE_IDLE_TEMP_WHITELIST + " or "
14645                             + START_ACTIVITIES_FROM_BACKGROUND + " or "
14646                             + START_FOREGROUND_SERVICES_FROM_BACKGROUND;
14647                     Slog.w(TAG, msg);
14648                     throw new SecurityException(msg);
14649                 }
14650             }
14651             if (brOptions.isDontSendToRestrictedApps()
14652                     && !isUidActiveLOSP(callingUid)
14653                     && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) {
14654                 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage
14655                         + " has background restrictions");
14656                 return ActivityManager.START_CANCELED;
14657             }
14658             if (brOptions.allowsBackgroundActivityStarts()) {
14659                 // See if the caller is allowed to do this.  Note we are checking against
14660                 // the actual real caller (not whoever provided the operation as say a
14661                 // PendingIntent), because that who is actually supplied the arguments.
14662                 if (checkComponentPermission(
14663                         android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
14664                         realCallingPid, realCallingUid, -1, true)
14665                         != PackageManager.PERMISSION_GRANTED) {
14666                     String msg = "Permission Denial: " + intent.getAction()
14667                             + " broadcast from " + callerPackage + " (pid=" + callingPid
14668                             + ", uid=" + callingUid + ")"
14669                             + " requires "
14670                             + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
14671                     Slog.w(TAG, msg);
14672                     throw new SecurityException(msg);
14673                 } else {
14674                     // We set the token to null since if it wasn't for it we'd allow anyway here
14675                     backgroundStartPrivileges = BackgroundStartPrivileges.ALLOW_BAL;
14676                 }
14677             }
14678 
14679             if (brOptions.getIdForResponseEvent() > 0) {
14680                 enforcePermission(android.Manifest.permission.ACCESS_BROADCAST_RESPONSE_STATS,
14681                         callingPid, callingUid, "recordResponseEventWhileInBackground");
14682             }
14683         }
14684 
14685         // Verify that protected broadcasts are only being sent by system code,
14686         // and that system code is only sending protected broadcasts.
14687         final boolean isProtectedBroadcast;
14688         try {
14689             isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
14690         } catch (RemoteException e) {
14691             Slog.w(TAG, "Remote exception", e);
14692             scheduleCanceledResultTo(resultToApp, resultTo, intent,
14693                     userId, brOptions, callingUid, callerPackage);
14694             return ActivityManager.BROADCAST_SUCCESS;
14695         }
14696 
14697         final boolean isCallerSystem;
14698         switch (UserHandle.getAppId(callingUid)) {
14699             case ROOT_UID:
14700             case SYSTEM_UID:
14701             case PHONE_UID:
14702             case BLUETOOTH_UID:
14703             case NFC_UID:
14704             case SE_UID:
14705             case NETWORK_STACK_UID:
14706                 isCallerSystem = true;
14707                 break;
14708             default:
14709                 isCallerSystem = (callerApp != null) && callerApp.isPersistent();
14710                 break;
14711         }
14712 
14713         // First line security check before anything else: stop non-system apps from
14714         // sending protected broadcasts.
14715         if (!isCallerSystem) {
14716             if (isProtectedBroadcast) {
14717                 String msg = "Permission Denial: not allowed to send broadcast "
14718                         + action + " from pid="
14719                         + callingPid + ", uid=" + callingUid;
14720                 Slog.w(TAG, msg);
14721                 throw new SecurityException(msg);
14722 
14723             } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
14724                     || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
14725                 // Special case for compatibility: we don't want apps to send this,
14726                 // but historically it has not been protected and apps may be using it
14727                 // to poke their own app widget.  So, instead of making it protected,
14728                 // just limit it to the caller.
14729                 if (callerPackage == null) {
14730                     String msg = "Permission Denial: not allowed to send broadcast "
14731                             + action + " from unknown caller.";
14732                     Slog.w(TAG, msg);
14733                     throw new SecurityException(msg);
14734                 } else if (intent.getComponent() != null) {
14735                     // They are good enough to send to an explicit component...  verify
14736                     // it is being sent to the calling app.
14737                     if (!intent.getComponent().getPackageName().equals(
14738                             callerPackage)) {
14739                         String msg = "Permission Denial: not allowed to send broadcast "
14740                                 + action + " to "
14741                                 + intent.getComponent().getPackageName() + " from "
14742                                 + callerPackage;
14743                         Slog.w(TAG, msg);
14744                         throw new SecurityException(msg);
14745                     }
14746                 } else {
14747                     // Limit broadcast to their own package.
14748                     intent.setPackage(callerPackage);
14749                 }
14750             }
14751         }
14752 
14753         boolean timeoutExempt = false;
14754 
14755         if (action != null) {
14756             if (getBackgroundLaunchBroadcasts().contains(action)) {
14757                 if (DEBUG_BACKGROUND_CHECK) {
14758                     Slog.i(TAG, "Broadcast action " + action + " forcing include-background");
14759                 }
14760                 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
14761             }
14762 
14763             switch (action) {
14764                 case Intent.ACTION_MEDIA_SCANNER_SCAN_FILE:
14765                     UserManagerInternal umInternal = LocalServices.getService(
14766                             UserManagerInternal.class);
14767                     UserInfo userInfo = umInternal.getUserInfo(userId);
14768                     if (userInfo != null && userInfo.isCloneProfile()) {
14769                         userId = umInternal.getProfileParentId(userId);
14770                     }
14771                     break;
14772                 case Intent.ACTION_UID_REMOVED:
14773                 case Intent.ACTION_PACKAGE_REMOVED:
14774                 case Intent.ACTION_PACKAGE_CHANGED:
14775                 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
14776                 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
14777                 case Intent.ACTION_PACKAGES_SUSPENDED:
14778                 case Intent.ACTION_PACKAGES_UNSUSPENDED:
14779                     // Handle special intents: if this broadcast is from the package
14780                     // manager about a package being removed, we need to remove all of
14781                     // its activities from the history stack.
14782                     if (checkComponentPermission(
14783                             android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
14784                             callingPid, callingUid, -1, true)
14785                             != PackageManager.PERMISSION_GRANTED) {
14786                         String msg = "Permission Denial: " + intent.getAction()
14787                                 + " broadcast from " + callerPackage + " (pid=" + callingPid
14788                                 + ", uid=" + callingUid + ")"
14789                                 + " requires "
14790                                 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
14791                         Slog.w(TAG, msg);
14792                         throw new SecurityException(msg);
14793                     }
14794                     switch (action) {
14795                         case Intent.ACTION_UID_REMOVED:
14796                             final int uid = getUidFromIntent(intent);
14797                             if (uid >= 0) {
14798                                 mBatteryStatsService.removeUid(uid);
14799                                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
14800                                     mAppOpsService.resetAllModes(UserHandle.getUserId(uid),
14801                                             intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME));
14802                                 } else {
14803                                     mAppOpsService.uidRemoved(uid);
14804                                 }
14805                             }
14806                             break;
14807                         case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
14808                             // If resources are unavailable just force stop all those packages
14809                             // and flush the attribute cache as well.
14810                             String list[] =
14811                                     intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
14812                             if (list != null && list.length > 0) {
14813                                 for (int i = 0; i < list.length; i++) {
14814                                     forceStopPackageLocked(list[i], -1, false, true, true,
14815                                             false, false, userId, "storage unmount");
14816                                 }
14817                                 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
14818                                 sendPackageBroadcastLocked(
14819                                         ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE,
14820                                         list, userId);
14821                             }
14822                             break;
14823                         case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
14824                             mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
14825                             break;
14826                         case Intent.ACTION_PACKAGE_REMOVED:
14827                         case Intent.ACTION_PACKAGE_CHANGED:
14828                             Uri data = intent.getData();
14829                             String ssp;
14830                             if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
14831                                 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action);
14832                                 final boolean replacing =
14833                                         intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
14834                                 final boolean killProcess =
14835                                         !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false);
14836                                 final boolean fullUninstall = removed && !replacing;
14837 
14838                                 if (removed) {
14839                                     if (killProcess) {
14840                                         forceStopPackageLocked(ssp, UserHandle.getAppId(
14841                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
14842                                                 false, true, true, false, fullUninstall, userId,
14843                                                 "pkg removed");
14844                                         getPackageManagerInternal()
14845                                                 .onPackageProcessKilledForUninstall(ssp);
14846                                     } else {
14847                                         // Kill any app zygotes always, since they can't fork new
14848                                         // processes with references to the old code
14849                                         forceStopAppZygoteLocked(ssp, UserHandle.getAppId(
14850                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
14851                                                 userId);
14852                                     }
14853                                     final int cmd = killProcess
14854                                             ? ApplicationThreadConstants.PACKAGE_REMOVED
14855                                             : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL;
14856                                     sendPackageBroadcastLocked(cmd,
14857                                             new String[] {ssp}, userId);
14858                                     if (fullUninstall) {
14859                                         // Remove all permissions granted from/to this package
14860                                         mUgmInternal.removeUriPermissionsForPackage(ssp, userId,
14861                                                 true, false);
14862 
14863                                         mAtmInternal.removeRecentTasksByPackageName(ssp, userId);
14864 
14865                                         mServices.forceStopPackageLocked(ssp, userId);
14866                                         mAtmInternal.onPackageUninstalled(ssp, userId);
14867                                         mBatteryStatsService.notePackageUninstalled(ssp);
14868                                     }
14869                                 } else {
14870                                     if (killProcess) {
14871                                         int reason;
14872                                         int subReason;
14873                                         if (replacing) {
14874                                             reason = ApplicationExitInfo.REASON_PACKAGE_UPDATED;
14875                                             subReason = ApplicationExitInfo.SUBREASON_UNKNOWN;
14876                                         } else {
14877                                             reason =
14878                                                     ApplicationExitInfo.REASON_PACKAGE_STATE_CHANGE;
14879                                             subReason = ApplicationExitInfo.SUBREASON_UNKNOWN;
14880                                         }
14881 
14882                                         final int extraUid = intent.getIntExtra(Intent.EXTRA_UID,
14883                                                 -1);
14884                                         synchronized (mProcLock) {
14885                                             mProcessList.killPackageProcessesLSP(ssp,
14886                                                     UserHandle.getAppId(extraUid),
14887                                                     userId, ProcessList.INVALID_ADJ,
14888                                                     reason,
14889                                                     subReason,
14890                                                     "change " + ssp);
14891                                         }
14892                                     }
14893                                     cleanupDisabledPackageComponentsLocked(ssp, userId,
14894                                             intent.getStringArrayExtra(
14895                                                     Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST));
14896                                     mServices.schedulePendingServiceStartLocked(ssp, userId);
14897                                 }
14898                             }
14899                             break;
14900                         case Intent.ACTION_PACKAGES_SUSPENDED:
14901                         case Intent.ACTION_PACKAGES_UNSUSPENDED:
14902                             final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals(
14903                                     intent.getAction());
14904                             final String[] packageNames = intent.getStringArrayExtra(
14905                                     Intent.EXTRA_CHANGED_PACKAGE_LIST);
14906                             final int userIdExtra = intent.getIntExtra(
14907                                     Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
14908 
14909                             mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended,
14910                                     userIdExtra);
14911                             break;
14912                     }
14913                     break;
14914                 case Intent.ACTION_PACKAGE_REPLACED:
14915                 {
14916                     final Uri data = intent.getData();
14917                     final String ssp;
14918                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
14919                         ApplicationInfo aInfo = null;
14920                         try {
14921                             aInfo = AppGlobals.getPackageManager()
14922                                     .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId);
14923                         } catch (RemoteException ignore) {}
14924                         if (aInfo == null) {
14925                             Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:"
14926                                     + " ssp=" + ssp + " data=" + data);
14927                             scheduleCanceledResultTo(resultToApp, resultTo, intent,
14928                                     userId, brOptions, callingUid, callerPackage);
14929                             return ActivityManager.BROADCAST_SUCCESS;
14930                         }
14931                         updateAssociationForApp(aInfo);
14932                         mAtmInternal.onPackageReplaced(aInfo);
14933                         mServices.updateServiceApplicationInfoLocked(aInfo);
14934                         sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED,
14935                                 new String[] {ssp}, userId);
14936                     }
14937                     break;
14938                 }
14939                 case Intent.ACTION_PACKAGE_ADDED:
14940                 {
14941                     // Special case for adding a package: by default turn on compatibility mode.
14942                     Uri data = intent.getData();
14943                     String ssp;
14944                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
14945                         final boolean replacing =
14946                                 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
14947                         mAtmInternal.onPackageAdded(ssp, replacing);
14948 
14949                         try {
14950                             ApplicationInfo ai = AppGlobals.getPackageManager().
14951                                     getApplicationInfo(ssp, STOCK_PM_FLAGS, 0);
14952                             mBatteryStatsService.notePackageInstalled(ssp,
14953                                     ai != null ? ai.longVersionCode : 0);
14954                         } catch (RemoteException e) {
14955                         }
14956                     }
14957                     break;
14958                 }
14959                 case Intent.ACTION_PACKAGE_DATA_CLEARED:
14960                 {
14961                     Uri data = intent.getData();
14962                     String ssp;
14963                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
14964                         mAtmInternal.onPackageDataCleared(ssp, userId);
14965                     }
14966                     break;
14967                 }
14968                 case Intent.ACTION_TIMEZONE_CHANGED:
14969                     // If this is the time zone changed action, queue up a message that will reset
14970                     // the timezone of all currently running processes. This message will get
14971                     // queued up before the broadcast happens.
14972                     mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
14973                     break;
14974                 case Intent.ACTION_TIME_CHANGED:
14975                     // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between
14976                     // the tri-state value it may contain and "unknown".
14977                     // For convenience we re-use the Intent extra values.
14978                     final int NO_EXTRA_VALUE_FOUND = -1;
14979                     final int timeFormatPreferenceMsgValue = intent.getIntExtra(
14980                             Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT,
14981                             NO_EXTRA_VALUE_FOUND /* defaultValue */);
14982                     // Only send a message if the time preference is available.
14983                     if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) {
14984                         Message updateTimePreferenceMsg =
14985                                 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG,
14986                                         timeFormatPreferenceMsgValue, 0);
14987                         mHandler.sendMessage(updateTimePreferenceMsg);
14988                     }
14989                     mBatteryStatsService.noteCurrentTimeChanged();
14990                     break;
14991                 case ConnectivityManager.ACTION_CLEAR_DNS_CACHE:
14992                     mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
14993                     break;
14994                 case Proxy.PROXY_CHANGE_ACTION:
14995                     mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG));
14996                     break;
14997                 case android.hardware.Camera.ACTION_NEW_PICTURE:
14998                 case android.hardware.Camera.ACTION_NEW_VIDEO:
14999                     // In N we just turned these off; in O we are turing them back on partly,
15000                     // only for registered receivers.  This will still address the main problem
15001                     // (a spam of apps waking up when a picture is taken putting significant
15002                     // memory pressure on the system at a bad point), while still allowing apps
15003                     // that are already actively running to know about this happening.
15004                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
15005                     break;
15006                 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED:
15007                     mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG);
15008                     break;
15009                 case "com.android.launcher.action.INSTALL_SHORTCUT":
15010                     // As of O, we no longer support this broadcasts, even for pre-O apps.
15011                     // Apps should now be using ShortcutManager.pinRequestShortcut().
15012                     Log.w(TAG, "Broadcast " + action
15013                             + " no longer supported. It will not be delivered.");
15014                     scheduleCanceledResultTo(resultToApp, resultTo, intent,
15015                             userId, brOptions, callingUid, callerPackage);
15016                     return ActivityManager.BROADCAST_SUCCESS;
15017                 case Intent.ACTION_PRE_BOOT_COMPLETED:
15018                     timeoutExempt = true;
15019                     break;
15020                 case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
15021                     if (!mAtmInternal.checkCanCloseSystemDialogs(callingPid, callingUid,
15022                             callerPackage)) {
15023                         scheduleCanceledResultTo(resultToApp, resultTo, intent,
15024                                 userId, brOptions, callingUid, callerPackage);
15025                         // Returning success seems to be the pattern here
15026                         return ActivityManager.BROADCAST_SUCCESS;
15027                     }
15028                     break;
15029             }
15030 
15031             if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
15032                     Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
15033                     Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
15034                 final int uid = getUidFromIntent(intent);
15035                 if (uid != -1) {
15036                     final UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
15037                     if (uidRec != null) {
15038                         uidRec.updateHasInternetPermission();
15039                     }
15040                 }
15041             }
15042         }
15043 
15044         final int callerAppProcessState = getRealProcessStateLocked(callerApp, realCallingPid);
15045         // Add to the sticky list if requested.
15046         if (sticky) {
15047             if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
15048                     callingPid, callingUid)
15049                     != PackageManager.PERMISSION_GRANTED) {
15050                 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
15051                         + callingPid + ", uid=" + callingUid
15052                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15053                 Slog.w(TAG, msg);
15054                 throw new SecurityException(msg);
15055             }
15056             if (requiredPermissions != null && requiredPermissions.length > 0) {
15057                 Slog.w(TAG, "Can't broadcast sticky intent " + intent
15058                         + " and enforce permissions " + Arrays.toString(requiredPermissions));
15059                 scheduleCanceledResultTo(resultToApp, resultTo, intent,
15060                         userId, brOptions, callingUid, callerPackage);
15061                 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
15062             }
15063             if (intent.getComponent() != null) {
15064                 throw new SecurityException(
15065                         "Sticky broadcasts can't target a specific component");
15066             }
15067             // We use userId directly here, since the "all" target is maintained
15068             // as a separate set of sticky broadcasts.
15069             if (userId != UserHandle.USER_ALL) {
15070                 // But first, if this is not a broadcast to all users, then
15071                 // make sure it doesn't conflict with an existing broadcast to
15072                 // all users.
15073                 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get(
15074                         UserHandle.USER_ALL);
15075                 if (stickies != null) {
15076                     ArrayList<StickyBroadcast> list = stickies.get(intent.getAction());
15077                     if (list != null) {
15078                         int N = list.size();
15079                         int i;
15080                         for (i=0; i<N; i++) {
15081                             if (intent.filterEquals(list.get(i).intent)) {
15082                                 throw new IllegalArgumentException(
15083                                         "Sticky broadcast " + intent + " for user "
15084                                         + userId + " conflicts with existing global broadcast");
15085                             }
15086                         }
15087                     }
15088                 }
15089             }
15090             ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get(userId);
15091             if (stickies == null) {
15092                 stickies = new ArrayMap<>();
15093                 mStickyBroadcasts.put(userId, stickies);
15094             }
15095             ArrayList<StickyBroadcast> list = stickies.get(intent.getAction());
15096             if (list == null) {
15097                 list = new ArrayList<>();
15098                 stickies.put(intent.getAction(), list);
15099             }
15100             final boolean deferUntilActive = BroadcastRecord.calculateDeferUntilActive(
15101                     callingUid, brOptions, resultTo, ordered,
15102                     BroadcastRecord.calculateUrgent(intent, brOptions));
15103             final int stickiesCount = list.size();
15104             int i;
15105             for (i = 0; i < stickiesCount; i++) {
15106                 if (intent.filterEquals(list.get(i).intent)) {
15107                     // This sticky already exists, replace it.
15108                     list.set(i, StickyBroadcast.create(new Intent(intent), deferUntilActive,
15109                             callingUid, callerAppProcessState));
15110                     break;
15111                 }
15112             }
15113             if (i >= stickiesCount) {
15114                 list.add(StickyBroadcast.create(new Intent(intent), deferUntilActive, callingUid,
15115                         callerAppProcessState));
15116             }
15117         }
15118 
15119         int[] users;
15120         if (userId == UserHandle.USER_ALL) {
15121             // Caller wants broadcast to go to all started users.
15122             users = mUserController.getStartedUserArray();
15123         } else {
15124             // Caller wants broadcast to go to one specific user.
15125             users = new int[] {userId};
15126         }
15127 
15128         // Figure out who all will receive this broadcast.
15129         final int cookie = BroadcastQueue.traceBegin("queryReceivers");
15130         List receivers = null;
15131         List<BroadcastFilter> registeredReceivers = null;
15132         // Need to resolve the intent to interested receivers...
15133         if ((intent.getFlags() & Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15134             receivers = collectReceiverComponents(
15135                     intent, resolvedType, callingUid, users, broadcastAllowList);
15136         }
15137         if (intent.getComponent() == null) {
15138             final PackageDataSnapshot snapshot = getPackageManagerInternal().snapshot();
15139             if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) {
15140                 // Query one target user at a time, excluding shell-restricted users
15141                 for (int i = 0; i < users.length; i++) {
15142                     if (mUserController.hasUserRestriction(
15143                             UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
15144                         continue;
15145                     }
15146                     List<BroadcastFilter> registeredReceiversForUser =
15147                             mReceiverResolver.queryIntent(snapshot, intent,
15148                                     resolvedType, false /*defaultOnly*/, users[i]);
15149                     if (registeredReceivers == null) {
15150                         registeredReceivers = registeredReceiversForUser;
15151                     } else if (registeredReceiversForUser != null) {
15152                         registeredReceivers.addAll(registeredReceiversForUser);
15153                     }
15154                 }
15155             } else {
15156                 registeredReceivers = mReceiverResolver.queryIntent(snapshot, intent,
15157                         resolvedType, false /*defaultOnly*/, userId);
15158             }
15159         }
15160         BroadcastQueue.traceEnd(cookie);
15161 
15162         final boolean replacePending =
15163                 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
15164 
15165         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction()
15166                 + " replacePending=" + replacePending);
15167         if (registeredReceivers != null && broadcastAllowList != null) {
15168             // if a uid whitelist was provided, remove anything in the application space that wasn't
15169             // in it.
15170             for (int i = registeredReceivers.size() - 1; i >= 0; i--) {
15171                 final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid);
15172                 if (owningAppId >= Process.FIRST_APPLICATION_UID
15173                         && Arrays.binarySearch(broadcastAllowList, owningAppId) < 0) {
15174                     registeredReceivers.remove(i);
15175                 }
15176             }
15177         }
15178 
15179         filterNonExportedComponents(intent, callingUid, callingPid, registeredReceivers,
15180                 mPlatformCompat, callerPackage, resolvedType);
15181         int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
15182         if (!ordered && NR > 0 && !mEnableModernQueue) {
15183             // If we are not serializing this broadcast, then send the
15184             // registered receivers separately so they don't wait for the
15185             // components to be launched. We don't do this split for the modern
15186             // queue because delivery to registered receivers isn't blocked
15187             // behind manifest receivers.
15188             if (isCallerSystem) {
15189                 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
15190                         isProtectedBroadcast, registeredReceivers);
15191             }
15192             final BroadcastQueue queue = broadcastQueueForIntent(intent);
15193             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
15194                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
15195                     requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions,
15196                     registeredReceivers, resultToApp, resultTo, resultCode, resultData,
15197                     resultExtras, ordered, sticky, false, userId,
15198                     backgroundStartPrivileges, timeoutExempt, filterExtrasForReceiver,
15199                     callerAppProcessState);
15200             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
15201             queue.enqueueBroadcastLocked(r);
15202             registeredReceivers = null;
15203             NR = 0;
15204         }
15205 
15206         // Merge into one list.
15207         int ir = 0;
15208         if (receivers != null) {
15209             // A special case for PACKAGE_ADDED: do not allow the package
15210             // being added to see this broadcast.  This prevents them from
15211             // using this as a back door to get run as soon as they are
15212             // installed.  Maybe in the future we want to have a special install
15213             // broadcast or such for apps, but we'd like to deliberately make
15214             // this decision.
15215             String skipPackages[] = null;
15216             if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
15217                     || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
15218                     || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
15219                 Uri data = intent.getData();
15220                 if (data != null) {
15221                     String pkgName = data.getSchemeSpecificPart();
15222                     if (pkgName != null) {
15223                         skipPackages = new String[] { pkgName };
15224                     }
15225                 }
15226             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
15227                 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
15228             }
15229             if (skipPackages != null && (skipPackages.length > 0)) {
15230                 for (String skipPackage : skipPackages) {
15231                     if (skipPackage != null) {
15232                         int NT = receivers.size();
15233                         for (int it=0; it<NT; it++) {
15234                             ResolveInfo curt = (ResolveInfo)receivers.get(it);
15235                             if (curt.activityInfo.packageName.equals(skipPackage)) {
15236                                 receivers.remove(it);
15237                                 it--;
15238                                 NT--;
15239                             }
15240                         }
15241                     }
15242                 }
15243             }
15244 
15245             int NT = receivers != null ? receivers.size() : 0;
15246             int it = 0;
15247             ResolveInfo curt = null;
15248             BroadcastFilter curr = null;
15249             while (it < NT && ir < NR) {
15250                 if (curt == null) {
15251                     curt = (ResolveInfo)receivers.get(it);
15252                 }
15253                 if (curr == null) {
15254                     curr = registeredReceivers.get(ir);
15255                 }
15256                 if (curr.getPriority() >= curt.priority) {
15257                     // Insert this broadcast record into the final list.
15258                     receivers.add(it, curr);
15259                     ir++;
15260                     curr = null;
15261                     it++;
15262                     NT++;
15263                 } else {
15264                     // Skip to the next ResolveInfo in the final list.
15265                     it++;
15266                     curt = null;
15267                 }
15268             }
15269         }
15270         while (ir < NR) {
15271             if (receivers == null) {
15272                 receivers = new ArrayList();
15273             }
15274             receivers.add(registeredReceivers.get(ir));
15275             ir++;
15276         }
15277 
15278         if (isCallerSystem) {
15279             checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
15280                     isProtectedBroadcast, receivers);
15281         }
15282 
15283         if ((receivers != null && receivers.size() > 0)
15284                 || resultTo != null) {
15285             BroadcastQueue queue = broadcastQueueForIntent(intent);
15286             filterNonExportedComponents(intent, callingUid, callingPid, receivers,
15287                     mPlatformCompat, callerPackage, resolvedType);
15288             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
15289                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
15290                     requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions,
15291                     receivers, resultToApp, resultTo, resultCode, resultData, resultExtras,
15292                     ordered, sticky, false, userId,
15293                     backgroundStartPrivileges, timeoutExempt, filterExtrasForReceiver,
15294                     callerAppProcessState);
15295 
15296             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
15297             queue.enqueueBroadcastLocked(r);
15298         } else {
15299             // There was nobody interested in the broadcast, but we still want to record
15300             // that it happened.
15301             if (intent.getComponent() == null && intent.getPackage() == null
15302                     && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15303                 // This was an implicit broadcast... let's record it for posterity.
15304                 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0);
15305             }
15306         }
15307 
15308         return ActivityManager.BROADCAST_SUCCESS;
15309     }
15310 
15311     @GuardedBy("this")
scheduleCanceledResultTo(ProcessRecord resultToApp, IIntentReceiver resultTo, Intent intent, int userId, BroadcastOptions options, int callingUid, String callingPackage)15312     private void scheduleCanceledResultTo(ProcessRecord resultToApp, IIntentReceiver resultTo,
15313             Intent intent, int userId, BroadcastOptions options, int callingUid,
15314             String callingPackage) {
15315         if (resultTo == null) {
15316             return;
15317         }
15318         final ProcessRecord app = resultToApp;
15319         final IApplicationThread thread  = (app != null) ? app.getOnewayThread() : null;
15320         if (thread != null) {
15321             try {
15322                 final boolean shareIdentity = (options != null && options.isShareIdentityEnabled());
15323                 thread.scheduleRegisteredReceiver(
15324                         resultTo, intent, Activity.RESULT_CANCELED, null, null,
15325                         false, false, true, userId, app.mState.getReportedProcState(),
15326                         shareIdentity ? callingUid : Process.INVALID_UID,
15327                         shareIdentity ? callingPackage : null);
15328             } catch (RemoteException e) {
15329                 final String msg = "Failed to schedule result of " + intent + " via "
15330                         + app + ": " + e;
15331                 app.killLocked("Can't schedule resultTo", ApplicationExitInfo.REASON_OTHER,
15332                         ApplicationExitInfo.SUBREASON_UNDELIVERED_BROADCAST, true);
15333                 Slog.d(TAG, msg);
15334             }
15335         }
15336     }
15337 
15338     @GuardedBy("this")
getRealProcessStateLocked(ProcessRecord app, int pid)15339     private int getRealProcessStateLocked(ProcessRecord app, int pid) {
15340         if (app == null) {
15341             synchronized (mPidsSelfLocked) {
15342                 app = mPidsSelfLocked.get(pid);
15343             }
15344         }
15345         if (app != null && app.getThread() != null && !app.isKilled()) {
15346             return app.mState.getCurProcState();
15347         }
15348         return PROCESS_STATE_NONEXISTENT;
15349     }
15350 
15351     @VisibleForTesting
getStickyBroadcasts(String action, int userId)15352     ArrayList<StickyBroadcast> getStickyBroadcasts(String action, int userId) {
15353         final ArrayMap<String, ArrayList<StickyBroadcast>> stickyBroadcasts =
15354                 mStickyBroadcasts.get(userId);
15355         if (stickyBroadcasts == null) {
15356             return null;
15357         }
15358         return stickyBroadcasts.get(action);
15359     }
15360 
15361     /**
15362      * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1
15363      */
getUidFromIntent(Intent intent)15364     private int getUidFromIntent(Intent intent) {
15365         if (intent == null) {
15366             return -1;
15367         }
15368         final Bundle intentExtras = intent.getExtras();
15369         return intent.hasExtra(Intent.EXTRA_UID)
15370                 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
15371     }
15372 
rotateBroadcastStatsIfNeededLocked()15373     final void rotateBroadcastStatsIfNeededLocked() {
15374         final long now = SystemClock.elapsedRealtime();
15375         if (mCurBroadcastStats == null ||
15376                 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) {
15377             mLastBroadcastStats = mCurBroadcastStats;
15378             if (mLastBroadcastStats != null) {
15379                 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime();
15380                 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis();
15381             }
15382             mCurBroadcastStats = new BroadcastStats();
15383         }
15384     }
15385 
addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)15386     final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount,
15387             int skipCount, long dispatchTime) {
15388         rotateBroadcastStatsIfNeededLocked();
15389         mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime);
15390     }
15391 
addBackgroundCheckViolationLocked(String action, String targetPackage)15392     final void addBackgroundCheckViolationLocked(String action, String targetPackage) {
15393         rotateBroadcastStatsIfNeededLocked();
15394         mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage);
15395     }
15396 
notifyBroadcastFinishedLocked(@onNull BroadcastRecord original)15397     final void notifyBroadcastFinishedLocked(@NonNull BroadcastRecord original) {
15398         final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null;
15399         final String callerPackage = info != null ? info.packageName : original.callerPackage;
15400         if (callerPackage != null) {
15401             mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT,
15402                     original.callingUid, 0, callerPackage).sendToTarget();
15403         }
15404     }
15405 
verifyBroadcastLocked(Intent intent)15406     final Intent verifyBroadcastLocked(Intent intent) {
15407         // Refuse possible leaked file descriptors
15408         if (intent != null && intent.hasFileDescriptors() == true) {
15409             throw new IllegalArgumentException("File descriptors passed in Intent");
15410         }
15411 
15412         int flags = intent.getFlags();
15413 
15414         if (!mProcessesReady) {
15415             // if the caller really truly claims to know what they're doing, go
15416             // ahead and allow the broadcast without launching any receivers
15417             if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
15418                 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed.
15419             } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15420                 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
15421                         + " before boot completion");
15422                 throw new IllegalStateException("Cannot broadcast before boot completed");
15423             }
15424         }
15425 
15426         if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
15427             throw new IllegalArgumentException(
15428                     "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
15429         }
15430 
15431         if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
15432             switch (Binder.getCallingUid()) {
15433                 case ROOT_UID:
15434                 case SHELL_UID:
15435                     break;
15436                 default:
15437                     Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID "
15438                             + Binder.getCallingUid());
15439                     intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL);
15440                     break;
15441             }
15442         }
15443 
15444         return intent;
15445     }
15446 
15447     /**
15448      * @deprecated Use {@link #broadcastIntentWithFeature}
15449      */
15450     @Deprecated
broadcastIntent(IApplicationThread caller, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, boolean serialized, boolean sticky, int userId)15451     public final int broadcastIntent(IApplicationThread caller,
15452             Intent intent, String resolvedType, IIntentReceiver resultTo,
15453             int resultCode, String resultData, Bundle resultExtras,
15454             String[] requiredPermissions, int appOp, Bundle bOptions,
15455             boolean serialized, boolean sticky, int userId) {
15456         return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode,
15457                 resultData, resultExtras, requiredPermissions, null, null, appOp, bOptions,
15458                 serialized, sticky, userId);
15459     }
15460 
15461     @Override
broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, boolean serialized, boolean sticky, int userId)15462     public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId,
15463             Intent intent, String resolvedType, IIntentReceiver resultTo,
15464             int resultCode, String resultData, Bundle resultExtras,
15465             String[] requiredPermissions, String[] excludedPermissions,
15466             String[] excludedPackages, int appOp, Bundle bOptions,
15467             boolean serialized, boolean sticky, int userId) {
15468         enforceNotIsolatedCaller("broadcastIntent");
15469         synchronized(this) {
15470             intent = verifyBroadcastLocked(intent);
15471 
15472             final ProcessRecord callerApp = getRecordForAppLOSP(caller);
15473             final int callingPid = Binder.getCallingPid();
15474             final int callingUid = Binder.getCallingUid();
15475 
15476             // We're delivering the result to the caller
15477             final ProcessRecord resultToApp = callerApp;
15478 
15479             // Permission regimes around sender-supplied broadcast options.
15480             enforceBroadcastOptionPermissionsInternal(bOptions, callingUid);
15481 
15482             final long origId = Binder.clearCallingIdentity();
15483             try {
15484                 return broadcastIntentLocked(callerApp,
15485                         callerApp != null ? callerApp.info.packageName : null, callingFeatureId,
15486                         intent, resolvedType, resultToApp, resultTo, resultCode, resultData,
15487                         resultExtras, requiredPermissions, excludedPermissions, excludedPackages,
15488                         appOp, bOptions, serialized, sticky, callingPid, callingUid, callingUid,
15489                         callingPid, userId, BackgroundStartPrivileges.NONE, null, null);
15490             } finally {
15491                 Binder.restoreCallingIdentity(origId);
15492             }
15493         }
15494     }
15495 
15496     // Not the binder call surface
broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList)15497     int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid,
15498             int realCallingUid, int realCallingPid, Intent intent, String resolvedType,
15499             ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode,
15500             String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions,
15501             boolean serialized, boolean sticky, int userId,
15502             BackgroundStartPrivileges backgroundStartPrivileges,
15503             @Nullable int[] broadcastAllowList) {
15504         synchronized(this) {
15505             intent = verifyBroadcastLocked(intent);
15506 
15507             final long origId = Binder.clearCallingIdentity();
15508             String[] requiredPermissions = requiredPermission == null ? null
15509                     : new String[] {requiredPermission};
15510             try {
15511                 return broadcastIntentLocked(null, packageName, featureId, intent, resolvedType,
15512                         resultToApp, resultTo, resultCode, resultData, resultExtras,
15513                         requiredPermissions, null, null, OP_NONE, bOptions, serialized, sticky, -1,
15514                         uid, realCallingUid, realCallingPid, userId,
15515                         backgroundStartPrivileges, broadcastAllowList,
15516                         null /* filterExtrasForReceiver */);
15517             } finally {
15518                 Binder.restoreCallingIdentity(origId);
15519             }
15520         }
15521     }
15522 
unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)15523     public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
15524         // Refuse possible leaked file descriptors
15525         if (intent != null && intent.hasFileDescriptors() == true) {
15526             throw new IllegalArgumentException("File descriptors passed in Intent");
15527         }
15528 
15529         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
15530                 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null);
15531 
15532         synchronized(this) {
15533             if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
15534                     != PackageManager.PERMISSION_GRANTED) {
15535                 String msg = "Permission Denial: unbroadcastIntent() from pid="
15536                         + Binder.getCallingPid()
15537                         + ", uid=" + Binder.getCallingUid()
15538                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15539                 Slog.w(TAG, msg);
15540                 throw new SecurityException(msg);
15541             }
15542             ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get(userId);
15543             if (stickies != null) {
15544                 ArrayList<StickyBroadcast> list = stickies.get(intent.getAction());
15545                 if (list != null) {
15546                     int N = list.size();
15547                     int i;
15548                     for (i=0; i<N; i++) {
15549                         if (intent.filterEquals(list.get(i).intent)) {
15550                             list.remove(i);
15551                             break;
15552                         }
15553                     }
15554                     if (list.size() <= 0) {
15555                         stickies.remove(intent.getAction());
15556                     }
15557                 }
15558                 if (stickies.size() <= 0) {
15559                     mStickyBroadcasts.remove(userId);
15560                 }
15561             }
15562         }
15563     }
15564 
backgroundServicesFinishedLocked(int userId)15565     void backgroundServicesFinishedLocked(int userId) {
15566         for (BroadcastQueue queue : mBroadcastQueues) {
15567             queue.backgroundServicesFinishedLocked(userId);
15568         }
15569     }
15570 
finishReceiver(IBinder caller, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)15571     public void finishReceiver(IBinder caller, int resultCode, String resultData,
15572             Bundle resultExtras, boolean resultAbort, int flags) {
15573         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + caller);
15574 
15575         // Refuse possible leaked file descriptors
15576         if (resultExtras != null && resultExtras.hasFileDescriptors()) {
15577             throw new IllegalArgumentException("File descriptors passed in Bundle");
15578         }
15579 
15580         final long origId = Binder.clearCallingIdentity();
15581         try {
15582             synchronized(this) {
15583                 final ProcessRecord callerApp = getRecordForAppLOSP(caller);
15584                 if (callerApp == null) {
15585                     Slog.w(TAG, "finishReceiver: no app for " + caller);
15586                     return;
15587                 }
15588 
15589                 final BroadcastQueue queue = broadcastQueueForFlags(flags);
15590                 queue.finishReceiverLocked(callerApp, resultCode,
15591                         resultData, resultExtras, resultAbort, true);
15592                 // updateOomAdjLocked() will be done here
15593                 trimApplicationsLocked(false, OOM_ADJ_REASON_FINISH_RECEIVER);
15594             }
15595 
15596         } finally {
15597             Binder.restoreCallingIdentity(origId);
15598         }
15599     }
15600 
15601     // =========================================================
15602     // INSTRUMENTATION
15603     // =========================================================
15604 
startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)15605     public boolean startInstrumentation(ComponentName className,
15606             String profileFile, int flags, Bundle arguments,
15607             IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
15608             int userId, String abiOverride) {
15609         enforceNotIsolatedCaller("startInstrumentation");
15610         final int callingUid = Binder.getCallingUid();
15611         final int callingPid = Binder.getCallingPid();
15612         userId = mUserController.handleIncomingUser(callingPid, callingUid,
15613                 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null);
15614         // Refuse possible leaked file descriptors
15615         if (arguments != null && arguments.hasFileDescriptors()) {
15616             throw new IllegalArgumentException("File descriptors passed in Bundle");
15617         }
15618         final IPackageManager pm = AppGlobals.getPackageManager();
15619 
15620         synchronized(this) {
15621             InstrumentationInfo ii = null;
15622             ApplicationInfo ai = null;
15623 
15624             boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0;
15625 
15626             try {
15627                 ii = pm.getInstrumentationInfoAsUser(className, STOCK_PM_FLAGS, userId);
15628                 if (ii == null) {
15629                     reportStartInstrumentationFailureLocked(watcher, className,
15630                             "Unable to find instrumentation info for: " + className);
15631                     return false;
15632                 }
15633                 ai = pm.getApplicationInfo(ii.targetPackage, STOCK_PM_FLAGS, userId);
15634                 if (ai == null) {
15635                     reportStartInstrumentationFailureLocked(watcher, className,
15636                             "Unable to find instrumentation target package: " + ii.targetPackage);
15637                     return false;
15638                 }
15639             } catch (RemoteException e) {
15640             }
15641 
15642             if (ii.targetPackage.equals("android")) {
15643                 if (!noRestart) {
15644                     reportStartInstrumentationFailureLocked(watcher, className,
15645                             "Cannot instrument system server without 'no-restart'");
15646                     return false;
15647                 }
15648             } else if (!ai.hasCode()) {
15649                 reportStartInstrumentationFailureLocked(watcher, className,
15650                         "Instrumentation target has no code: " + ii.targetPackage);
15651                 return false;
15652             }
15653 
15654             int match = SIGNATURE_NO_MATCH;
15655             try {
15656                 match = pm.checkSignatures(ii.targetPackage, ii.packageName, userId);
15657             } catch (RemoteException e) {
15658             }
15659             if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
15660                 if (Build.IS_DEBUGGABLE && (callingUid == Process.ROOT_UID)
15661                         && (flags & INSTR_FLAG_ALWAYS_CHECK_SIGNATURE) == 0) {
15662                     Slog.w(TAG, "Instrumentation test " + ii.packageName
15663                             + " doesn't have a signature matching the target " + ii.targetPackage
15664                             + ", which would not be allowed on the production Android builds");
15665                 } else {
15666                     String msg = "Permission Denial: starting instrumentation "
15667                             + className + " from pid="
15668                             + Binder.getCallingPid()
15669                             + ", uid=" + Binder.getCallingUid()
15670                             + " not allowed because package " + ii.packageName
15671                             + " does not have a signature matching the target "
15672                             + ii.targetPackage;
15673                     reportStartInstrumentationFailureLocked(watcher, className, msg);
15674                     throw new SecurityException(msg);
15675                 }
15676             }
15677 
15678             if (!Build.IS_DEBUGGABLE && callingUid != ROOT_UID && callingUid != SHELL_UID
15679                     && callingUid != SYSTEM_UID && !hasActiveInstrumentationLocked(callingPid)) {
15680                 // If it's not debug build and not called from root/shell/system uid, reject it.
15681                 final String msg = "Permission Denial: instrumentation test "
15682                         + className + " from pid=" + callingPid + ", uid=" + callingUid
15683                         + ", pkgName=" + mInternal.getPackageNameByPid(callingPid)
15684                         + " not allowed because it's not started from SHELL";
15685                 Slog.wtfQuiet(TAG, msg);
15686                 reportStartInstrumentationFailureLocked(watcher, className, msg);
15687                 throw new SecurityException(msg);
15688             }
15689 
15690             boolean disableHiddenApiChecks = ai.usesNonSdkApi()
15691                     || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0;
15692             boolean disableTestApiChecks = disableHiddenApiChecks
15693                     || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0;
15694 
15695             if (disableHiddenApiChecks || disableTestApiChecks) {
15696                 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS,
15697                         "disable hidden API checks");
15698             }
15699 
15700             if ((flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_SANDBOX) != 0) {
15701                 return startInstrumentationOfSdkSandbox(
15702                         className,
15703                         profileFile,
15704                         arguments,
15705                         watcher,
15706                         uiAutomationConnection,
15707                         userId,
15708                         abiOverride,
15709                         ii,
15710                         ai,
15711                         noRestart,
15712                         disableHiddenApiChecks,
15713                         disableTestApiChecks);
15714             }
15715 
15716             ActiveInstrumentation activeInstr = new ActiveInstrumentation(this);
15717             activeInstr.mClass = className;
15718             String defProcess = ai.processName;;
15719             if (ii.targetProcesses == null) {
15720                 activeInstr.mTargetProcesses = new String[]{ai.processName};
15721             } else if (ii.targetProcesses.equals("*")) {
15722                 activeInstr.mTargetProcesses = new String[0];
15723             } else {
15724                 activeInstr.mTargetProcesses = ii.targetProcesses.split(",");
15725                 defProcess = activeInstr.mTargetProcesses[0];
15726             }
15727             activeInstr.mTargetInfo = ai;
15728             activeInstr.mProfileFile = profileFile;
15729             activeInstr.mArguments = arguments;
15730             activeInstr.mWatcher = watcher;
15731             activeInstr.mUiAutomationConnection = uiAutomationConnection;
15732             activeInstr.mResultClass = className;
15733             activeInstr.mHasBackgroundActivityStartsPermission = checkPermission(
15734                     START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
15735                             == PackageManager.PERMISSION_GRANTED;
15736             activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission(
15737                     START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid)
15738                             == PackageManager.PERMISSION_GRANTED;
15739             activeInstr.mNoRestart = noRestart;
15740 
15741             final long origId = Binder.clearCallingIdentity();
15742 
15743             ProcessRecord app;
15744             synchronized (mProcLock) {
15745                 if (noRestart) {
15746                     app = getProcessRecordLocked(ai.processName, ai.uid);
15747                 } else {
15748                     // Instrumentation can kill and relaunch even persistent processes
15749                     forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false,
15750                             userId, "start instr");
15751                     // Inform usage stats to make the target package active
15752                     if (mUsageStatsService != null) {
15753                         mUsageStatsService.reportEvent(ii.targetPackage, userId,
15754                                 UsageEvents.Event.SYSTEM_INTERACTION);
15755                     }
15756                     app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks,
15757                             disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY);
15758                     app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION);
15759                 }
15760 
15761                 app.setActiveInstrumentation(activeInstr);
15762                 activeInstr.mFinished = false;
15763                 activeInstr.mSourceUid = callingUid;
15764                 activeInstr.mRunningProcesses.add(app);
15765                 if (!mActiveInstrumentation.contains(activeInstr)) {
15766                     mActiveInstrumentation.add(activeInstr);
15767                 }
15768             }
15769 
15770             if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) {
15771                 // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with
15772                 // --no-isolated-storage flag.
15773                 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid,
15774                         ii.packageName, AppOpsManager.MODE_ALLOWED);
15775             }
15776             Binder.restoreCallingIdentity(origId);
15777 
15778             if (noRestart) {
15779                 instrumentWithoutRestart(activeInstr, ai);
15780             }
15781         }
15782 
15783         return true;
15784     }
15785 
15786     @GuardedBy("this")
hasActiveInstrumentationLocked(int pid)15787     private boolean hasActiveInstrumentationLocked(int pid) {
15788         if (pid == 0) {
15789             return false;
15790         }
15791         synchronized (mPidsSelfLocked) {
15792             ProcessRecord process = mPidsSelfLocked.get(pid);
15793             return process != null && process.getActiveInstrumentation() != null;
15794         }
15795     }
15796 
15797     @GuardedBy("this")
startInstrumentationOfSdkSandbox( ComponentName className, String profileFile, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride, InstrumentationInfo instrumentationInfo, ApplicationInfo sdkSandboxClientAppInfo, boolean noRestart, boolean disableHiddenApiChecks, boolean disableTestApiChecks)15798     private boolean startInstrumentationOfSdkSandbox(
15799             ComponentName className,
15800             String profileFile,
15801             Bundle arguments,
15802             IInstrumentationWatcher watcher,
15803             IUiAutomationConnection uiAutomationConnection,
15804             int userId,
15805             String abiOverride,
15806             InstrumentationInfo instrumentationInfo,
15807             ApplicationInfo sdkSandboxClientAppInfo,
15808             boolean noRestart,
15809             boolean disableHiddenApiChecks,
15810             boolean disableTestApiChecks) {
15811 
15812         if (noRestart) {
15813             reportStartInstrumentationFailureLocked(
15814                     watcher,
15815                     className,
15816                     "Instrumenting sdk sandbox with --no-restart flag is not supported");
15817             return false;
15818         }
15819 
15820         final ApplicationInfo sdkSandboxInfo;
15821         try {
15822             final PackageManager pm = mContext.getPackageManager();
15823             sdkSandboxInfo = pm.getApplicationInfoAsUser(pm.getSdkSandboxPackageName(), 0, userId);
15824         } catch (NameNotFoundException e) {
15825             reportStartInstrumentationFailureLocked(
15826                     watcher, className, "Can't find SdkSandbox package");
15827             return false;
15828         }
15829 
15830         final SdkSandboxManagerLocal sandboxManagerLocal =
15831                 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class);
15832         if (sandboxManagerLocal == null) {
15833             reportStartInstrumentationFailureLocked(
15834                     watcher, className, "Can't locate SdkSandboxManagerLocal");
15835             return false;
15836         }
15837 
15838         final String processName = sandboxManagerLocal.getSdkSandboxProcessNameForInstrumentation(
15839                 sdkSandboxClientAppInfo);
15840 
15841         ActiveInstrumentation activeInstr = new ActiveInstrumentation(this);
15842         activeInstr.mClass = className;
15843         activeInstr.mTargetProcesses = new String[]{processName};
15844         activeInstr.mTargetInfo = sdkSandboxInfo;
15845         activeInstr.mProfileFile = profileFile;
15846         activeInstr.mArguments = arguments;
15847         activeInstr.mWatcher = watcher;
15848         activeInstr.mUiAutomationConnection = uiAutomationConnection;
15849         activeInstr.mResultClass = className;
15850         activeInstr.mHasBackgroundActivityStartsPermission = false;
15851         activeInstr.mHasBackgroundForegroundServiceStartsPermission = false;
15852         // Instrumenting sdk sandbox without a restart is not supported
15853         activeInstr.mNoRestart = false;
15854 
15855         final int callingUid = Binder.getCallingUid();
15856         final long token = Binder.clearCallingIdentity();
15857         try {
15858             sandboxManagerLocal.notifyInstrumentationStarted(
15859                     sdkSandboxClientAppInfo.packageName, sdkSandboxClientAppInfo.uid);
15860             synchronized (mProcLock) {
15861                 int sdkSandboxUid = Process.toSdkSandboxUid(sdkSandboxClientAppInfo.uid);
15862                 // Kill the package sdk sandbox process belong to. At this point sdk sandbox is
15863                 // already killed.
15864                 forceStopPackageLocked(
15865                         instrumentationInfo.targetPackage,
15866                         /* appId= */ -1,
15867                         /* callerWillRestart= */ true,
15868                         /* purgeCache= */ false,
15869                         /* doIt= */ true,
15870                         /* evenPersistent= */ true,
15871                         /* uninstalling= */ false,
15872                         userId,
15873                         "start instr");
15874 
15875                 ProcessRecord app = addAppLocked(
15876                         sdkSandboxInfo,
15877                         processName,
15878                         /* isolated= */ false,
15879                         /* isSdkSandbox= */ true,
15880                         sdkSandboxUid,
15881                         sdkSandboxClientAppInfo.packageName,
15882                         disableHiddenApiChecks,
15883                         disableTestApiChecks,
15884                         abiOverride,
15885                         ZYGOTE_POLICY_FLAG_EMPTY);
15886 
15887                 app.setActiveInstrumentation(activeInstr);
15888                 activeInstr.mFinished = false;
15889                 activeInstr.mSourceUid = callingUid;
15890                 activeInstr.mRunningProcesses.add(app);
15891                 if (!mActiveInstrumentation.contains(activeInstr)) {
15892                     mActiveInstrumentation.add(activeInstr);
15893                 }
15894                 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION);
15895             }
15896         } finally {
15897             Binder.restoreCallingIdentity(token);
15898         }
15899 
15900         return true;
15901     }
15902 
instrumentWithoutRestart(ActiveInstrumentation activeInstr, ApplicationInfo targetInfo)15903     private void instrumentWithoutRestart(ActiveInstrumentation activeInstr,
15904             ApplicationInfo targetInfo) {
15905         ProcessRecord pr;
15906         synchronized (this) {
15907             pr = getProcessRecordLocked(targetInfo.processName, targetInfo.uid);
15908         }
15909 
15910         try {
15911             pr.getThread().instrumentWithoutRestart(
15912                     activeInstr.mClass,
15913                     activeInstr.mArguments,
15914                     activeInstr.mWatcher,
15915                     activeInstr.mUiAutomationConnection,
15916                     targetInfo);
15917         } catch (RemoteException e) {
15918             Slog.i(TAG, "RemoteException from instrumentWithoutRestart", e);
15919         }
15920     }
15921 
isCallerShell()15922     private boolean isCallerShell() {
15923         final int callingUid = Binder.getCallingUid();
15924         return callingUid == SHELL_UID || callingUid == ROOT_UID;
15925     }
15926 
15927     /**
15928      * Report errors that occur while attempting to start Instrumentation.  Always writes the
15929      * error to the logs, but if somebody is watching, send the report there too.  This enables
15930      * the "am" command to report errors with more information.
15931      *
15932      * @param watcher The IInstrumentationWatcher.  Null if there isn't one.
15933      * @param cn The component name of the instrumentation.
15934      * @param report The error report.
15935      */
reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)15936     private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher,
15937             ComponentName cn, String report) {
15938         Slog.w(TAG, report);
15939         if (watcher != null) {
15940             Bundle results = new Bundle();
15941             results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
15942             results.putString("Error", report);
15943             mInstrumentationReporter.reportStatus(watcher, cn, -1, results);
15944         }
15945     }
15946 
addInstrumentationResultsLocked(ProcessRecord app, Bundle results)15947     void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) {
15948         final ActiveInstrumentation instr = app.getActiveInstrumentation();
15949         if (instr == null) {
15950             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
15951             return;
15952         }
15953 
15954         if (!instr.mFinished && results != null) {
15955             if (instr.mCurResults == null) {
15956                 instr.mCurResults = new Bundle(results);
15957             } else {
15958                 instr.mCurResults.putAll(results);
15959             }
15960         }
15961     }
15962 
addInstrumentationResults(IApplicationThread target, Bundle results)15963     public void addInstrumentationResults(IApplicationThread target, Bundle results) {
15964         int userId = UserHandle.getCallingUserId();
15965         // Refuse possible leaked file descriptors
15966         if (results != null && results.hasFileDescriptors()) {
15967             throw new IllegalArgumentException("File descriptors passed in Intent");
15968         }
15969 
15970         synchronized(this) {
15971             ProcessRecord app = getRecordForAppLOSP(target);
15972             if (app == null) {
15973                 Slog.w(TAG, "addInstrumentationResults: no app for " + target);
15974                 return;
15975             }
15976             final long origId = Binder.clearCallingIdentity();
15977             try {
15978                 addInstrumentationResultsLocked(app, results);
15979             } finally {
15980                 Binder.restoreCallingIdentity(origId);
15981             }
15982         }
15983     }
15984 
15985     @GuardedBy("this")
finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)15986     void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
15987         try {
15988             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "finishInstrumentationLocked()");
15989             final ActiveInstrumentation instr = app.getActiveInstrumentation();
15990             if (instr == null) {
15991                 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
15992                 return;
15993             }
15994 
15995             synchronized (mProcLock) {
15996                 if (!instr.mFinished) {
15997                     if (instr.mWatcher != null) {
15998                         Bundle finalResults = instr.mCurResults;
15999                         if (finalResults != null) {
16000                             if (instr.mCurResults != null && results != null) {
16001                                 finalResults.putAll(results);
16002                             }
16003                         } else {
16004                             finalResults = results;
16005                         }
16006                         mInstrumentationReporter.reportFinished(instr.mWatcher,
16007                                 instr.mClass, resultCode, finalResults);
16008                     }
16009 
16010                     // Can't call out of the system process with a lock held, so post a message.
16011                     if (instr.mUiAutomationConnection != null) {
16012                         // Go back to the default mode of denying OP_NO_ISOLATED_STORAGE app op.
16013                         mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, app.uid,
16014                                 app.info.packageName, AppOpsManager.MODE_ERRORED);
16015                         mAppOpsService.setAppOpsServiceDelegate(null);
16016                         getPermissionManagerInternal().stopShellPermissionIdentityDelegation();
16017                         mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG,
16018                                 instr.mUiAutomationConnection).sendToTarget();
16019                     }
16020                     instr.mFinished = true;
16021                 }
16022 
16023                 instr.removeProcess(app);
16024                 app.setActiveInstrumentation(null);
16025             }
16026             app.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION);
16027 
16028             if (app.isSdkSandbox) {
16029                 // For sharedUid apps this will kill all sdk sandbox processes, which is not ideal.
16030                 // TODO(b/209061624): should we call ProcessList.removeProcessLocked instead?
16031                 killUid(UserHandle.getAppId(app.uid), UserHandle.getUserId(app.uid),
16032                         "finished instr");
16033                 final SdkSandboxManagerLocal sandboxManagerLocal =
16034                         LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class);
16035                 if (sandboxManagerLocal != null) {
16036                     sandboxManagerLocal.notifyInstrumentationFinished(
16037                             app.sdkSandboxClientAppPackage,
16038                             Process.getAppUidForSdkSandboxUid(app.uid));
16039                 }
16040             } else if (!instr.mNoRestart) {
16041                 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false,
16042                         app.userId,
16043                         "finished inst");
16044             }
16045         } finally {
16046             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
16047         }
16048     }
16049 
finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)16050     public void finishInstrumentation(IApplicationThread target,
16051             int resultCode, Bundle results) {
16052         int userId = UserHandle.getCallingUserId();
16053         // Refuse possible leaked file descriptors
16054         if (results != null && results.hasFileDescriptors()) {
16055             throw new IllegalArgumentException("File descriptors passed in Intent");
16056         }
16057 
16058         synchronized(this) {
16059             ProcessRecord app = getRecordForAppLOSP(target);
16060             if (app == null) {
16061                 Slog.w(TAG, "finishInstrumentation: no app for " + target);
16062                 return;
16063             }
16064             final long origId = Binder.clearCallingIdentity();
16065             finishInstrumentationLocked(app, resultCode, results);
16066             Binder.restoreCallingIdentity(origId);
16067         }
16068     }
16069 
16070     @Override
getFocusedRootTaskInfo()16071     public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException {
16072         return mActivityTaskManager.getFocusedRootTaskInfo();
16073     }
16074 
16075     @Override
getConfiguration()16076     public Configuration getConfiguration() {
16077         return mActivityTaskManager.getConfiguration();
16078     }
16079 
16080     @Override
suppressResizeConfigChanges(boolean suppress)16081     public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
16082         mActivityTaskManager.suppressResizeConfigChanges(suppress);
16083     }
16084 
16085     @Override
updatePersistentConfiguration(Configuration values)16086     public void updatePersistentConfiguration(Configuration values) {
16087         updatePersistentConfigurationWithAttribution(values,
16088                 Settings.getPackageNameForUid(mContext, Binder.getCallingUid()), null);
16089     }
16090 
16091     @Override
updatePersistentConfigurationWithAttribution(Configuration values, String callingPackage, String callingAttributionTag)16092     public void updatePersistentConfigurationWithAttribution(Configuration values,
16093             String callingPackage, String callingAttributionTag) {
16094         enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()");
16095         enforceWriteSettingsPermission("updatePersistentConfiguration()", callingPackage,
16096                 callingAttributionTag);
16097         if (values == null) {
16098             throw new NullPointerException("Configuration must not be null");
16099         }
16100 
16101         int userId = UserHandle.getCallingUserId();
16102 
16103         mActivityTaskManager.updatePersistentConfiguration(values, userId);
16104     }
16105 
enforceWriteSettingsPermission(String func, String callingPackage, String callingAttributionTag)16106     private void enforceWriteSettingsPermission(String func, String callingPackage,
16107             String callingAttributionTag) {
16108         int uid = Binder.getCallingUid();
16109         if (uid == ROOT_UID) {
16110             return;
16111         }
16112 
16113         if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
16114                 callingPackage, callingAttributionTag, false)) {
16115             return;
16116         }
16117 
16118         String msg = "Permission Denial: " + func + " from pid="
16119                 + Binder.getCallingPid()
16120                 + ", uid=" + uid
16121                 + " requires " + android.Manifest.permission.WRITE_SETTINGS;
16122         Slog.w(TAG, msg);
16123         throw new SecurityException(msg);
16124     }
16125 
16126     @Override
updateConfiguration(Configuration values)16127     public boolean updateConfiguration(Configuration values) {
16128         return mActivityTaskManager.updateConfiguration(values);
16129     }
16130 
16131     @Override
updateMccMncConfiguration(String mcc, String mnc)16132     public boolean updateMccMncConfiguration(String mcc, String mnc) {
16133         int mccInt, mncInt;
16134         try {
16135             mccInt = Integer.parseInt(mcc);
16136             mncInt = Integer.parseInt(mnc);
16137         } catch (NumberFormatException | StringIndexOutOfBoundsException ex) {
16138             Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex);
16139             return false;
16140         }
16141         Configuration config = new Configuration();
16142         config.mcc = mccInt;
16143         config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt;
16144         return mActivityTaskManager.updateConfiguration(config);
16145     }
16146 
16147     @Override
getLaunchedFromUid(IBinder activityToken)16148     public int getLaunchedFromUid(IBinder activityToken) {
16149         return ActivityClient.getInstance().getLaunchedFromUid(activityToken);
16150     }
16151 
getLaunchedFromPackage(IBinder activityToken)16152     public String getLaunchedFromPackage(IBinder activityToken) {
16153         return ActivityClient.getInstance().getLaunchedFromPackage(activityToken);
16154     }
16155 
16156     // =========================================================
16157     // LIFETIME MANAGEMENT
16158     // =========================================================
16159 
isReceivingBroadcastLocked(ProcessRecord app, int[] outSchedGroup)16160     boolean isReceivingBroadcastLocked(ProcessRecord app, int[] outSchedGroup) {
16161         int res = ProcessList.SCHED_GROUP_UNDEFINED;
16162         for (BroadcastQueue queue : mBroadcastQueues) {
16163             res = Math.max(res, queue.getPreferredSchedulingGroupLocked(app));
16164         }
16165         outSchedGroup[0] = res;
16166         return res != ProcessList.SCHED_GROUP_UNDEFINED;
16167     }
16168 
startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16169     Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState,
16170             int targetUid, long targetVersionCode, ComponentName targetComponent,
16171             String targetProcess) {
16172         if (!mTrackingAssociations) {
16173             return null;
16174         }
16175         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
16176                 = mAssociations.get(targetUid);
16177         if (components == null) {
16178             components = new ArrayMap<>();
16179             mAssociations.put(targetUid, components);
16180         }
16181         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
16182         if (sourceUids == null) {
16183             sourceUids = new SparseArray<>();
16184             components.put(targetComponent, sourceUids);
16185         }
16186         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
16187         if (sourceProcesses == null) {
16188             sourceProcesses = new ArrayMap<>();
16189             sourceUids.put(sourceUid, sourceProcesses);
16190         }
16191         Association ass = sourceProcesses.get(sourceProcess);
16192         if (ass == null) {
16193             ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent,
16194                     targetProcess);
16195             sourceProcesses.put(sourceProcess, ass);
16196         }
16197         ass.mCount++;
16198         ass.mNesting++;
16199         if (ass.mNesting == 1) {
16200             ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis();
16201             ass.mLastState = sourceState;
16202         }
16203         return ass;
16204     }
16205 
stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16206     void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid,
16207             long targetVersionCode, ComponentName targetComponent, String targetProcess) {
16208         if (!mTrackingAssociations) {
16209             return;
16210         }
16211         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
16212                 = mAssociations.get(targetUid);
16213         if (components == null) {
16214             return;
16215         }
16216         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
16217         if (sourceUids == null) {
16218             return;
16219         }
16220         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
16221         if (sourceProcesses == null) {
16222             return;
16223         }
16224         Association ass = sourceProcesses.get(sourceProcess);
16225         if (ass == null || ass.mNesting <= 0) {
16226             return;
16227         }
16228         ass.mNesting--;
16229         if (ass.mNesting == 0) {
16230             long uptime = SystemClock.uptimeMillis();
16231             ass.mTime += uptime - ass.mStartTime;
16232             ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
16233                     += uptime - ass.mLastStateUptime;
16234             ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2;
16235         }
16236     }
16237 
noteUidProcessState(final int uid, final int state, final @ProcessCapability int capability)16238     void noteUidProcessState(final int uid, final int state,
16239                 final @ProcessCapability int capability) {
16240         mBatteryStatsService.noteUidProcessState(uid, state);
16241         mAppOpsService.updateUidProcState(uid, state, capability);
16242         if (mTrackingAssociations) {
16243             for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
16244                 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
16245                         = mAssociations.valueAt(i1);
16246                 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
16247                     SparseArray<ArrayMap<String, Association>> sourceUids
16248                             = targetComponents.valueAt(i2);
16249                     ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid);
16250                     if (sourceProcesses != null) {
16251                         for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
16252                             Association ass = sourceProcesses.valueAt(i4);
16253                             if (ass.mNesting >= 1) {
16254                                 // currently associated
16255                                 long uptime = SystemClock.uptimeMillis();
16256                                 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
16257                                         += uptime - ass.mLastStateUptime;
16258                                 ass.mLastState = state;
16259                                 ass.mLastStateUptime = uptime;
16260                             }
16261                         }
16262                     }
16263                 }
16264             }
16265         }
16266     }
16267 
16268     /**
16269      * Returns true if things are idle enough to perform GCs.
16270      */
16271     @GuardedBy("this")
canGcNowLocked()16272     final boolean canGcNowLocked() {
16273         for (BroadcastQueue q : mBroadcastQueues) {
16274             if (!q.isIdleLocked()) {
16275                 return false;
16276             }
16277         }
16278         return mAtmInternal.canGcNow();
16279     }
16280 
checkExcessivePowerUsage()16281     private void checkExcessivePowerUsage() {
16282         updateCpuStatsNow();
16283 
16284         final boolean monitorPhantomProcs = mSystemReady && FeatureFlagUtils.isEnabled(mContext,
16285                 SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS);
16286         synchronized (mProcLock) {
16287             final boolean doCpuKills = mLastPowerCheckUptime != 0;
16288             final long curUptime = SystemClock.uptimeMillis();
16289             final long uptimeSince = curUptime - mLastPowerCheckUptime;
16290             mLastPowerCheckUptime = curUptime;
16291             mProcessList.forEachLruProcessesLOSP(false, app -> {
16292                 if (app.getThread() == null) {
16293                     return;
16294                 }
16295                 if (app.mState.getSetProcState() >= ActivityManager.PROCESS_STATE_HOME) {
16296                     int cpuLimit;
16297                     long checkDur = curUptime - app.mState.getWhenUnimportant();
16298                     if (checkDur <= mConstants.POWER_CHECK_INTERVAL) {
16299                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1;
16300                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 2)
16301                             || app.mState.getSetProcState() <= ActivityManager.PROCESS_STATE_HOME) {
16302                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2;
16303                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 3)) {
16304                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3;
16305                     } else {
16306                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4;
16307                     }
16308 
16309                     updateAppProcessCpuTimeLPr(uptimeSince, doCpuKills, checkDur, cpuLimit, app);
16310 
16311                     if (monitorPhantomProcs) {
16312                         // Also check the phantom processes if there is any
16313                         updatePhantomProcessCpuTimeLPr(
16314                                 uptimeSince, doCpuKills, checkDur, cpuLimit, app);
16315                     }
16316                 }
16317             });
16318         }
16319     }
16320 
16321     @GuardedBy("mProcLock")
updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)16322     private void updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills,
16323             final long checkDur, final int cpuLimit, final ProcessRecord app) {
16324         synchronized (mAppProfiler.mProfilerLock) {
16325             final ProcessProfileRecord profile = app.mProfile;
16326             final long curCpuTime = profile.mCurCpuTime.get();
16327             final long lastCpuTime = profile.mLastCpuTime.get();
16328             if (lastCpuTime > 0) {
16329                 final long cpuTimeUsed = curCpuTime - lastCpuTime;
16330                 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed,
16331                             app.processName, app.toShortString(), cpuLimit, app)) {
16332                     mHandler.post(() -> {
16333                         synchronized (ActivityManagerService.this) {
16334                             if (app.getThread() == null
16335                                || app.mState.getSetProcState() < ActivityManager.PROCESS_STATE_HOME) {
16336                                    return;
16337                             }
16338                             app.killLocked("excessive cpu " + cpuTimeUsed + " during "
16339                                     + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit,
16340                                     ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
16341                                     ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU,
16342                                     true);
16343                         }
16344                     });
16345                     profile.reportExcessiveCpu();
16346                 }
16347             }
16348 
16349             profile.mLastCpuTime.set(curCpuTime);
16350         }
16351     }
16352 
16353     @GuardedBy("mProcLock")
updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)16354     private void updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills,
16355             final long checkDur, final int cpuLimit, final ProcessRecord app) {
16356         mPhantomProcessList.forEachPhantomProcessOfApp(app, r -> {
16357             if (r.mLastCputime > 0) {
16358                 final long cpuTimeUsed = r.mCurrentCputime - r.mLastCputime;
16359                 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed,
16360                             app.processName, r.toString(), cpuLimit, app)) {
16361                     mHandler.post(() -> {
16362                         synchronized (ActivityManagerService.this) {
16363                             if (app.getThread() == null
16364                                || app.mState.getSetProcState() < ActivityManager.PROCESS_STATE_HOME) {
16365                                    return;
16366                             }
16367                             mPhantomProcessList.killPhantomProcessGroupLocked(app, r,
16368                                     ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
16369                                     ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU,
16370                                     "excessive cpu " + cpuTimeUsed + " during "
16371                                     + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit);
16372                         }
16373                     });
16374                     return false;
16375                 }
16376             }
16377             r.mLastCputime = r.mCurrentCputime;
16378             return true;
16379         });
16380     }
16381 
16382     @GuardedBy("mProcLock")
checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, final long cputimeUsed, final String processName, final String description, final int cpuLimit, final ProcessRecord app)16383     private boolean checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills,
16384             final long cputimeUsed, final String processName, final String description,
16385             final int cpuLimit, final ProcessRecord app) {
16386         if (DEBUG_POWER && (uptimeSince > 0)) {
16387             StringBuilder sb = new StringBuilder(128);
16388             sb.append("CPU for ");
16389             sb.append(description);
16390             sb.append(": over ");
16391             TimeUtils.formatDuration(uptimeSince, sb);
16392             sb.append(" used ");
16393             TimeUtils.formatDuration(cputimeUsed, sb);
16394             sb.append(" (");
16395             sb.append((cputimeUsed * 100.0) / uptimeSince);
16396             sb.append("%)");
16397             Slog.i(TAG_POWER, sb.toString());
16398         }
16399         // If the process has used too much CPU over the last duration, the
16400         // user probably doesn't want this, so kill!
16401         if (doCpuKills && uptimeSince > 0) {
16402             if (((cputimeUsed * 100) / uptimeSince) >= cpuLimit) {
16403                 mBatteryStatsService.reportExcessiveCpu(app.info.uid, app.processName,
16404                         uptimeSince, cputimeUsed);
16405                 app.getPkgList().forEachPackageProcessStats(holder -> {
16406                     final ProcessState state = holder.state;
16407                     FrameworkStatsLog.write(
16408                             FrameworkStatsLog.EXCESSIVE_CPU_USAGE_REPORTED,
16409                             app.info.uid,
16410                             processName,
16411                             state != null ? state.getPackage() : app.info.packageName,
16412                             holder.appVersion);
16413                 });
16414                 return true;
16415             }
16416         }
16417         return false;
16418     }
16419 
isEphemeralLocked(int uid)16420     private boolean isEphemeralLocked(int uid) {
16421         final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
16422         if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid
16423             return false;
16424         }
16425         return getPackageManagerInternal().isPackageEphemeral(
16426                 UserHandle.getUserId(uid), packages[0]);
16427     }
16428 
16429     @GuardedBy("this")
enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)16430     void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) {
16431         uid = uidRec != null ? uidRec.getUid() : uid;
16432         if (uid < 0) {
16433             throw new IllegalArgumentException("No UidRecord or uid");
16434         }
16435 
16436         final int procState = uidRec != null
16437                 ? uidRec.getSetProcState() : PROCESS_STATE_NONEXISTENT;
16438         final int procAdj = uidRec != null
16439                 ? uidRec.getMinProcAdj() : ProcessList.INVALID_ADJ;
16440         final long procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0;
16441         final int capability = uidRec != null ? uidRec.getSetCapability() : 0;
16442         final boolean ephemeral = uidRec != null ? uidRec.isEphemeral() : isEphemeralLocked(uid);
16443 
16444         if (uidRec != null && uidRec.isIdle() && (change & UidRecord.CHANGE_IDLE) != 0) {
16445             mProcessList.killAppIfBgRestrictedAndCachedIdleLocked(uidRec);
16446         }
16447 
16448         if (uidRec != null && !uidRec.isIdle() && (change & UidRecord.CHANGE_GONE) != 0) {
16449             // If this uid is going away, and we haven't yet reported it is gone,
16450             // then do so now.
16451             change |= UidRecord.CHANGE_IDLE;
16452         }
16453         final int enqueuedChange = mUidObserverController.enqueueUidChange(
16454                 uidRec == null ? null : uidRec.pendingChange,
16455                 uid, change, procState, procAdj, procStateSeq, capability, ephemeral);
16456         if (uidRec != null) {
16457             uidRec.setLastReportedChange(enqueuedChange);
16458         }
16459 
16460         // Directly update the power manager, since we sit on top of it and it is critical
16461         // it be kept in sync (so wake locks will be held as soon as appropriate).
16462         if (mLocalPowerManager != null) {
16463             // TODO: dispatch cached/uncached changes here, so we don't need to report
16464             // all proc state changes.
16465             if ((enqueuedChange & UidRecord.CHANGE_ACTIVE) != 0) {
16466                 mLocalPowerManager.uidActive(uid);
16467             }
16468             if ((enqueuedChange & UidRecord.CHANGE_IDLE) != 0) {
16469                 mLocalPowerManager.uidIdle(uid);
16470             }
16471             if ((enqueuedChange & UidRecord.CHANGE_GONE) != 0) {
16472                 mLocalPowerManager.uidGone(uid);
16473             } else if ((enqueuedChange & UidRecord.CHANGE_PROCSTATE) != 0) {
16474                 mLocalPowerManager.updateUidProcState(uid, procState);
16475             }
16476         }
16477     }
16478 
16479     @GuardedBy(anyOf = {"this", "mProcLock"})
setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor)16480     final void setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor) {
16481         if (proc.getThread() != null) {
16482             proc.mProfile.setProcessTrackerState(
16483                     proc.mState.getReportedProcState(), memFactor);
16484         }
16485     }
16486 
16487     @GuardedBy("this")
clearProcessForegroundLocked(ProcessRecord proc)16488     final void clearProcessForegroundLocked(ProcessRecord proc) {
16489         updateProcessForegroundLocked(proc, /* isForeground =*/ false,
16490                 /* fgsTypes =*/0, /* hasTypeNoneFgs =*/false, /* oomAdj= */ false);
16491     }
16492 
16493     @GuardedBy("this")
updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean hasTypeNoneFgs, boolean oomAdj)16494     final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
16495             int fgServiceTypes, boolean hasTypeNoneFgs, boolean oomAdj) {
16496         final ProcessServiceRecord psr = proc.mServices;
16497         final boolean foregroundStateChanged = isForeground != psr.hasForegroundServices();
16498         if (foregroundStateChanged
16499                 || !psr.areForegroundServiceTypesSame(fgServiceTypes, hasTypeNoneFgs)) {
16500             if (foregroundStateChanged) {
16501                 // Notify internal listeners.
16502                 for (int i = mForegroundServiceStateListeners.size() - 1; i >= 0; i--) {
16503                     mForegroundServiceStateListeners.get(i).onForegroundServiceStateChanged(
16504                             proc.info.packageName, proc.info.uid, proc.getPid(), isForeground);
16505                 }
16506             }
16507             psr.setHasForegroundServices(isForeground, fgServiceTypes, hasTypeNoneFgs);
16508             ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
16509                     proc.info.uid);
16510             if (isForeground) {
16511                 if (curProcs == null) {
16512                     curProcs = new ArrayList<ProcessRecord>();
16513                     mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs);
16514                 }
16515                 if (!curProcs.contains(proc)) {
16516                     curProcs.add(proc);
16517                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START,
16518                             proc.info.packageName, proc.info.uid);
16519                 }
16520             } else {
16521                 if (curProcs != null) {
16522                     if (curProcs.remove(proc)) {
16523                         mBatteryStatsService.noteEvent(
16524                                 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH,
16525                                 proc.info.packageName, proc.info.uid);
16526                         if (curProcs.size() <= 0) {
16527                             mForegroundPackages.remove(proc.info.packageName, proc.info.uid);
16528                         }
16529                     }
16530                 }
16531             }
16532 
16533             psr.setReportedForegroundServiceTypes(fgServiceTypes);
16534             ProcessChangeItem item = mProcessList.enqueueProcessChangeItemLocked(
16535                     proc.getPid(), proc.info.uid);
16536             item.changes |= ProcessChangeItem.CHANGE_FOREGROUND_SERVICES;
16537             item.foregroundServiceTypes = fgServiceTypes;
16538         }
16539         if (oomAdj) {
16540             updateOomAdjLocked(proc, OOM_ADJ_REASON_UI_VISIBILITY);
16541         }
16542     }
16543 
16544     // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update
16545     // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities
16546     @Nullable
getTopApp()16547     ProcessRecord getTopApp() {
16548         final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null;
16549         final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null;
16550         String pkg;
16551         int uid;
16552         if (r != null) {
16553             pkg = r.processName;
16554             uid = r.info.uid;
16555         } else {
16556             pkg = null;
16557             uid = -1;
16558         }
16559         // Has the UID or resumed package name changed?
16560         synchronized (mCurResumedAppLock) {
16561             if (uid != mCurResumedUid || (pkg != mCurResumedPackage
16562                         && (pkg == null || !pkg.equals(mCurResumedPackage)))) {
16563 
16564                 final long identity = Binder.clearCallingIdentity();
16565                 try {
16566                     if (mCurResumedPackage != null) {
16567                         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH,
16568                                 mCurResumedPackage, mCurResumedUid);
16569                     }
16570                     mCurResumedPackage = pkg;
16571                     mCurResumedUid = uid;
16572                     if (mCurResumedPackage != null) {
16573                         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START,
16574                                 mCurResumedPackage, mCurResumedUid);
16575                     }
16576                 } finally {
16577                     Binder.restoreCallingIdentity(identity);
16578                 }
16579             }
16580         }
16581         return r;
16582     }
16583 
16584     /**
16585      * Enqueue the given process into a todo list, and the caller should
16586      * call {@link #updateOomAdjPendingTargetsLocked} to kick off a pass of the oom adj update.
16587      */
16588     @GuardedBy("this")
enqueueOomAdjTargetLocked(ProcessRecord app)16589     void enqueueOomAdjTargetLocked(ProcessRecord app) {
16590         mOomAdjuster.enqueueOomAdjTargetLocked(app);
16591     }
16592 
16593     /**
16594      * Remove the given process into a todo list.
16595      */
16596     @GuardedBy("this")
removeOomAdjTargetLocked(ProcessRecord app, boolean procDied)16597     void removeOomAdjTargetLocked(ProcessRecord app, boolean procDied) {
16598         mOomAdjuster.removeOomAdjTargetLocked(app, procDied);
16599     }
16600 
16601     /**
16602      * Kick off an oom adj update pass for the pending targets which are enqueued via
16603      * {@link #enqueueOomAdjTargetLocked}.
16604      */
16605     @GuardedBy("this")
updateOomAdjPendingTargetsLocked(@omAdjReason int oomAdjReason)16606     void updateOomAdjPendingTargetsLocked(@OomAdjReason int oomAdjReason) {
16607         mOomAdjuster.updateOomAdjPendingTargetsLocked(oomAdjReason);
16608     }
16609 
16610     static final class ProcStatsRunnable implements Runnable {
16611         private final ActivityManagerService mService;
16612         private final ProcessStatsService mProcessStats;
16613 
ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)16614         ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) {
16615             this.mService = service;
16616             this.mProcessStats = mProcessStats;
16617         }
16618 
run()16619         @Override public void run() {
16620             mProcessStats.writeStateAsync();
16621         }
16622     }
16623 
16624     @GuardedBy("this")
updateOomAdjLocked(@omAdjReason int oomAdjReason)16625     final void updateOomAdjLocked(@OomAdjReason int oomAdjReason) {
16626         mOomAdjuster.updateOomAdjLocked(oomAdjReason);
16627     }
16628 
16629     /**
16630      * Update OomAdj for a specific process and its reachable processes.
16631      *
16632      * @param app The process to update
16633      * @param oomAdjReason
16634      * @return whether updateOomAdjLocked(app) was successful.
16635      */
16636     @GuardedBy("this")
updateOomAdjLocked(ProcessRecord app, @OomAdjReason int oomAdjReason)16637     final boolean updateOomAdjLocked(ProcessRecord app, @OomAdjReason int oomAdjReason) {
16638         return mOomAdjuster.updateOomAdjLocked(app, oomAdjReason);
16639     }
16640 
16641     @Override
makePackageIdle(String packageName, int userId)16642     public void makePackageIdle(String packageName, int userId) {
16643         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
16644                 != PackageManager.PERMISSION_GRANTED) {
16645             String msg = "Permission Denial: makePackageIdle() from pid="
16646                     + Binder.getCallingPid()
16647                     + ", uid=" + Binder.getCallingUid()
16648                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
16649             Slog.w(TAG, msg);
16650             throw new SecurityException(msg);
16651         }
16652         final int callingPid = Binder.getCallingPid();
16653         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
16654                 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null);
16655         final long callingId = Binder.clearCallingIdentity();
16656         try {
16657             IPackageManager pm = AppGlobals.getPackageManager();
16658             int pkgUid = -1;
16659             try {
16660                 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES
16661                         | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM);
16662             } catch (RemoteException e) {
16663             }
16664             if (pkgUid == -1) {
16665                 throw new IllegalArgumentException("Unknown package name " + packageName);
16666             }
16667 
16668             synchronized (this) {
16669                 try {
16670                     if (mLocalPowerManager != null) {
16671                         mLocalPowerManager.startUidChanges();
16672                     }
16673                     final int appId = UserHandle.getAppId(pkgUid);
16674                     for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; i--) {
16675                         final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
16676                         final long bgTime = uidRec.getLastBackgroundTime();
16677                         if (bgTime > 0 && !uidRec.isIdle()) {
16678                             final int uid = uidRec.getUid();
16679                             if (UserHandle.getAppId(uid) == appId) {
16680                                 if (userId == UserHandle.USER_ALL
16681                                         || userId == UserHandle.getUserId(uid)) {
16682                                     EventLogTags.writeAmUidIdle(uid);
16683                                     synchronized (mProcLock) {
16684                                         uidRec.setIdle(true);
16685                                         uidRec.setSetIdle(true);
16686                                     }
16687                                     Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uid)
16688                                             + " from package " + packageName + " user " + userId);
16689                                     doStopUidLocked(uid, uidRec);
16690                                 }
16691                             }
16692                         }
16693                     }
16694                 } finally {
16695                     if (mLocalPowerManager != null) {
16696                         mLocalPowerManager.finishUidChanges();
16697                     }
16698                 }
16699             }
16700         } finally {
16701             Binder.restoreCallingIdentity(callingId);
16702         }
16703     }
16704 
16705     @Override
setDeterministicUidIdle(boolean deterministic)16706     public void setDeterministicUidIdle(boolean deterministic) {
16707         mDeterministicUidIdle = deterministic;
16708     }
16709 
16710     /** Make the currently active UIDs idle after a certain grace period. */
idleUids()16711     final void idleUids() {
16712         synchronized (this) {
16713             mOomAdjuster.idleUidsLocked();
16714         }
16715     }
16716 
runInBackgroundDisabled(int uid)16717     final void runInBackgroundDisabled(int uid) {
16718         synchronized (this) {
16719             UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
16720             if (uidRec != null) {
16721                 // This uid is actually running...  should it be considered background now?
16722                 if (uidRec.isIdle()) {
16723                     doStopUidLocked(uidRec.getUid(), uidRec);
16724                 }
16725             } else {
16726                 // This uid isn't actually running...  still send a report about it being "stopped".
16727                 doStopUidLocked(uid, null);
16728             }
16729         }
16730     }
16731 
cameraActiveChanged(@serIdInt int uid, boolean active)16732     final void cameraActiveChanged(@UserIdInt int uid, boolean active) {
16733         synchronized (mActiveCameraUids) {
16734             final int curIndex = mActiveCameraUids.indexOf(uid);
16735             if (active) {
16736                 if (curIndex < 0) {
16737                     mActiveCameraUids.add(uid);
16738                 }
16739             } else {
16740                 if (curIndex >= 0) {
16741                     mActiveCameraUids.remove(curIndex);
16742                 }
16743             }
16744         }
16745     }
16746 
isCameraActiveForUid(@serIdInt int uid)16747     final boolean isCameraActiveForUid(@UserIdInt int uid) {
16748         synchronized (mActiveCameraUids) {
16749             return mActiveCameraUids.indexOf(uid) >= 0;
16750         }
16751     }
16752 
16753     @GuardedBy("this")
doStopUidLocked(int uid, final UidRecord uidRec)16754     final void doStopUidLocked(int uid, final UidRecord uidRec) {
16755         mServices.stopInBackgroundLocked(uid);
16756         enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE | UidRecord.CHANGE_PROCSTATE);
16757     }
16758 
16759     /**
16760      * Allowlists {@code targetUid} to temporarily bypass Power Save mode.
16761      */
16762     @GuardedBy("this")
tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)16763     void tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid,
16764             long duration, int type, @ReasonCode int reasonCode, String reason) {
16765         if (DEBUG_ALLOWLISTS) {
16766             Slog.d(TAG, "tempAllowlistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", "
16767                     + targetUid + ", " + duration + ", " + type + ")");
16768         }
16769 
16770         synchronized (mPidsSelfLocked) {
16771             final ProcessRecord pr = mPidsSelfLocked.get(callerPid);
16772             if (pr == null) {
16773                 Slog.w(TAG, "tempAllowlistForPendingIntentLocked() no ProcessRecord for pid "
16774                         + callerPid);
16775                 return;
16776             }
16777             if (!pr.mServices.mAllowlistManager) {
16778                 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid)
16779                         != PackageManager.PERMISSION_GRANTED
16780                         && checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callerPid, callerUid)
16781                         != PackageManager.PERMISSION_GRANTED
16782                         && checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callerPid,
16783                         callerUid) != PackageManager.PERMISSION_GRANTED) {
16784                     if (DEBUG_ALLOWLISTS) {
16785                         Slog.d(TAG, "tempAllowlistForPendingIntentLocked() for target " + targetUid
16786                                 + ": pid " + callerPid + " is not allowed");
16787                     }
16788                     return;
16789                 }
16790             }
16791         }
16792 
16793         tempAllowlistUidLocked(targetUid, duration, reasonCode, reason, type, callerUid);
16794     }
16795 
16796     /**
16797      * Allowlists {@code targetUid} to temporarily bypass Power Save mode.
16798      */
16799     @GuardedBy("this")
tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, String reason, @TempAllowListType int type, int callingUid)16800     void tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode,
16801             String reason, @TempAllowListType int type, int callingUid) {
16802         synchronized (mProcLock) {
16803             // The temp allowlist type could change according to the reasonCode.
16804             if (mLocalDeviceIdleController != null) {
16805                 type = mLocalDeviceIdleController.getTempAllowListType(reasonCode, type);
16806             }
16807             if (type == TEMPORARY_ALLOW_LIST_TYPE_NONE) {
16808                 return;
16809             }
16810             mPendingTempAllowlist.put(targetUid,
16811                     new PendingTempAllowlist(targetUid, duration, reasonCode, reason, type,
16812                             callingUid));
16813             setUidTempAllowlistStateLSP(targetUid, true);
16814             mUiHandler.obtainMessage(PUSH_TEMP_ALLOWLIST_UI_MSG).sendToTarget();
16815 
16816             if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) {
16817                 mFgsStartTempAllowList.add(targetUid, duration,
16818                         new FgsTempAllowListItem(duration, reasonCode, reason, callingUid));
16819             }
16820         }
16821     }
16822 
pushTempAllowlist()16823     void pushTempAllowlist() {
16824         final int N;
16825         final PendingTempAllowlist[] list;
16826 
16827         // First copy out the pending changes...  we need to leave them in the map for now,
16828         // in case someone needs to check what is coming up while we don't have the lock held.
16829         synchronized (this) {
16830             synchronized (mProcLock) {
16831                 N = mPendingTempAllowlist.size();
16832                 list = new PendingTempAllowlist[N];
16833                 for (int i = 0; i < N; i++) {
16834                     list[i] = mPendingTempAllowlist.valueAt(i);
16835                 }
16836             }
16837         }
16838 
16839         // Now safely dispatch changes to device idle controller.  Skip this if we're early
16840         // in boot and the controller hasn't yet been brought online:  we do not apply
16841         // device idle policy anyway at this phase.
16842         if (mLocalDeviceIdleController != null) {
16843             for (int i = 0; i < N; i++) {
16844                 PendingTempAllowlist ptw = list[i];
16845                 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid,
16846                         ptw.duration, ptw.type, false, ptw.reasonCode, ptw.tag,
16847                         ptw.callingUid);
16848             }
16849         }
16850 
16851         // And now we can safely remove them from the map.
16852         synchronized (this) {
16853             synchronized (mProcLock) {
16854                 for (int i = 0; i < N; i++) {
16855                     PendingTempAllowlist ptw = list[i];
16856                     int index = mPendingTempAllowlist.indexOfKey(ptw.targetUid);
16857                     if (index >= 0 && mPendingTempAllowlist.valueAt(index) == ptw) {
16858                         mPendingTempAllowlist.removeAt(index);
16859                     }
16860                 }
16861             }
16862         }
16863     }
16864 
16865     @GuardedBy({"this", "mProcLock"})
setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist)16866     final void setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist) {
16867         mOomAdjuster.setAppIdTempAllowlistStateLSP(uid, onAllowlist);
16868     }
16869 
16870     @GuardedBy({"this", "mProcLock"})
setUidTempAllowlistStateLSP(int uid, boolean onAllowlist)16871     final void setUidTempAllowlistStateLSP(int uid, boolean onAllowlist) {
16872         mOomAdjuster.setUidTempAllowlistStateLSP(uid, onAllowlist);
16873     }
16874 
trimApplications(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason)16875     private void trimApplications(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason) {
16876         synchronized (this) {
16877             trimApplicationsLocked(forceFullOomAdj, oomAdjReason);
16878         }
16879     }
16880 
16881     @GuardedBy("this")
trimApplicationsLocked(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason)16882     private void trimApplicationsLocked(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason) {
16883         // First remove any unused application processes whose package
16884         // has been removed.
16885         boolean didSomething = false;
16886         for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) {
16887             final ProcessRecord app = mProcessList.mRemovedProcesses.get(i);
16888             if (!app.hasActivitiesOrRecentTasks()
16889                     && app.mReceivers.numberOfCurReceivers() == 0
16890                     && app.mServices.numberOfRunningServices() == 0) {
16891                 final IApplicationThread thread = app.getThread();
16892                 Slog.i(TAG, "Exiting empty application process "
16893                         + app.toShortString() + " ("
16894                         + (thread != null ? thread.asBinder() : null)
16895                         + ")\n");
16896                 final int pid = app.getPid();
16897                 if (pid > 0 && pid != MY_PID) {
16898                     app.killLocked("empty",
16899                             ApplicationExitInfo.REASON_OTHER,
16900                             ApplicationExitInfo.SUBREASON_TRIM_EMPTY,
16901                             false);
16902                 } else if (thread != null) {
16903                     try {
16904                         thread.scheduleExit();
16905                     } catch (Exception e) {
16906                         // Ignore exceptions.
16907                     }
16908                 }
16909                 didSomething = true;
16910                 cleanUpApplicationRecordLocked(app, pid, false, true, -1, false /*replacingPid*/,
16911                         false /* fromBinderDied */);
16912                 mProcessList.mRemovedProcesses.remove(i);
16913 
16914                 if (app.isPersistent()) {
16915                     addAppLocked(app.info, null, false, null /* ABI override */,
16916                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
16917                     app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_PERSISTENT);
16918                 }
16919             }
16920         }
16921 
16922         // Now update the oom adj for all processes. Don't skip this, since other callers
16923         // might be depending on it.
16924         if (didSomething || forceFullOomAdj) {
16925             updateOomAdjLocked(oomAdjReason);
16926         } else {
16927             // Process any pending oomAdj targets, it'll be a no-op if nothing is pending.
16928             updateOomAdjPendingTargetsLocked(oomAdjReason);
16929         }
16930     }
16931 
16932     /** This method sends the specified signal to each of the persistent apps */
signalPersistentProcesses(final int sig)16933     public void signalPersistentProcesses(final int sig) throws RemoteException {
16934         if (sig != SIGNAL_USR1) {
16935             throw new SecurityException("Only SIGNAL_USR1 is allowed");
16936         }
16937 
16938         if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
16939                 != PackageManager.PERMISSION_GRANTED) {
16940             throw new SecurityException("Requires permission "
16941                     + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
16942         }
16943 
16944         synchronized (mProcLock) {
16945             mProcessList.forEachLruProcessesLOSP(false, app -> {
16946                 if (app.getThread() != null && app.isPersistent()) {
16947                     sendSignal(app.getPid(), sig);
16948                 }
16949             });
16950         }
16951     }
16952 
profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)16953     public boolean profileControl(String process, int userId, boolean start,
16954             ProfilerInfo profilerInfo, int profileType) throws RemoteException {
16955         // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
16956         // its own permission.
16957         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
16958                 != PackageManager.PERMISSION_GRANTED) {
16959             throw new SecurityException("Requires permission "
16960                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
16961         }
16962 
16963         if (start && (profilerInfo == null || profilerInfo.profileFd == null)) {
16964             throw new IllegalArgumentException("null profile info or fd");
16965         }
16966 
16967         ProcessRecord proc = null;
16968         synchronized (mProcLock) {
16969             if (process != null) {
16970                 proc = findProcessLOSP(process, userId, "profileControl");
16971             }
16972 
16973             if (start && (proc == null || proc.getThread() == null)) {
16974                 throw new IllegalArgumentException("Unknown process: " + process);
16975             }
16976         }
16977 
16978         synchronized (mAppProfiler.mProfilerLock) {
16979             return mAppProfiler.profileControlLPf(proc, start, profilerInfo, profileType);
16980         }
16981     }
16982 
16983     @GuardedBy(anyOf = {"this", "mProcLock"})
findProcessLOSP(String process, int userId, String callName)16984     private ProcessRecord findProcessLOSP(String process, int userId, String callName) {
16985         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
16986                 userId, true, ALLOW_FULL_ONLY, callName, null);
16987         ProcessRecord proc = null;
16988         try {
16989             int pid = Integer.parseInt(process);
16990             synchronized (mPidsSelfLocked) {
16991                 proc = mPidsSelfLocked.get(pid);
16992             }
16993         } catch (NumberFormatException e) {
16994         }
16995 
16996         if (proc == null) {
16997             ArrayMap<String, SparseArray<ProcessRecord>> all =
16998                     mProcessList.getProcessNamesLOSP().getMap();
16999             SparseArray<ProcessRecord> procs = all.get(process);
17000             if (procs != null && procs.size() > 0) {
17001                 proc = procs.valueAt(0);
17002                 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
17003                     for (int i=1; i<procs.size(); i++) {
17004                         ProcessRecord thisProc = procs.valueAt(i);
17005                         if (thisProc.userId == userId) {
17006                             proc = thisProc;
17007                             break;
17008                         }
17009                     }
17010                 }
17011             }
17012         }
17013 
17014         return proc;
17015     }
17016 
17017     @Override
dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)17018     public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo,
17019             boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) {
17020         try {
17021             // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
17022             // its own permission (same as profileControl).
17023             if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17024                     != PackageManager.PERMISSION_GRANTED) {
17025                 throw new SecurityException("Requires permission "
17026                         + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17027             }
17028 
17029             if (fd == null) {
17030                 throw new IllegalArgumentException("null fd");
17031             }
17032 
17033             synchronized (this) {
17034                 ProcessRecord proc = findProcessLOSP(process, userId, "dumpHeap");
17035                 IApplicationThread thread;
17036                 if (proc == null || (thread = proc.getThread()) == null) {
17037                     throw new IllegalArgumentException("Unknown process: " + process);
17038                 }
17039 
17040                 enforceDebuggable(proc);
17041 
17042                 mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
17043 
17044                 final RemoteCallback intermediateCallback = new RemoteCallback(
17045                         new RemoteCallback.OnResultListener() {
17046                         @Override
17047                         public void onResult(Bundle result) {
17048                             finishCallback.sendResult(result);
17049                             mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
17050                         }
17051                     }, null);
17052 
17053                 thread.dumpHeap(managed, mallocInfo, runGc, path, fd, intermediateCallback);
17054                 fd = null;
17055                 return true;
17056             }
17057         } catch (RemoteException e) {
17058             throw new IllegalStateException("Process disappeared");
17059         } finally {
17060             if (fd != null) {
17061                 try {
17062                     fd.close();
17063                 } catch (IOException e) {
17064                 }
17065             }
17066         }
17067     }
17068 
17069     /**
17070      * Dump the resources structure for the given process
17071      *
17072      * @param process The process to dump resource info for
17073      * @param fd The FileDescriptor to dump it into
17074      * @throws RemoteException
17075      */
dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback)17076     public boolean dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback)
17077             throws RemoteException {
17078         synchronized (this) {
17079             ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_CURRENT, "dumpResources");
17080             IApplicationThread thread;
17081             if (proc == null || (thread = proc.getThread()) == null) {
17082                 throw new IllegalArgumentException("Unknown process: " + process);
17083             }
17084             thread.dumpResources(fd, callback);
17085             return true;
17086         }
17087     }
17088 
17089     /**
17090      * Dump the resources structure for all processes
17091      *
17092      * @param fd The FileDescriptor to dump it into
17093      * @throws RemoteException
17094      */
dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw)17095     public void dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw) throws RemoteException {
17096         final ArrayList<ProcessRecord> processes = new ArrayList<>();
17097         synchronized (this) {
17098             processes.addAll(mProcessList.getLruProcessesLOSP());
17099         }
17100         for (int i = 0, size = processes.size(); i < size; i++) {
17101             ProcessRecord app = processes.get(i);
17102             pw.println(String.format("Resources History for %s (%s)",
17103                     app.processName,
17104                     app.info.packageName));
17105             if (app.mOptRecord.isFrozen()) {
17106                 pw.println("  Skipping frozen process");
17107                 pw.flush();
17108                 continue;
17109             }
17110             pw.flush();
17111             try {
17112                 TransferPipe tp = new TransferPipe("  ");
17113                 try {
17114                     IApplicationThread thread = app.getThread();
17115                     if (thread != null) {
17116                         app.getThread().dumpResources(tp.getWriteFd(), null);
17117                         tp.go(fd.getFileDescriptor(), 2000);
17118                     } else {
17119                         pw.println(String.format(
17120                                 "  Resources history for %s (%s) failed, no thread",
17121                                 app.processName,
17122                                 app.info.packageName));
17123                     }
17124                 } finally {
17125                     tp.kill();
17126                 }
17127             } catch (IOException e) {
17128                 pw.println("  " + e.getMessage());
17129                 pw.flush();
17130             }
17131 
17132         }
17133     }
17134 
17135     @Override
setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)17136     public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize,
17137             String reportPackage) {
17138         if (processName != null) {
17139             enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
17140                     "setDumpHeapDebugLimit()");
17141         } else {
17142             synchronized (mPidsSelfLocked) {
17143                 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid());
17144                 if (proc == null) {
17145                     throw new SecurityException("No process found for calling pid "
17146                             + Binder.getCallingPid());
17147                 }
17148                 enforceDebuggable(proc);
17149                 processName = proc.processName;
17150                 uid = proc.uid;
17151                 if (reportPackage != null && !proc.getPkgList().containsKey(reportPackage)) {
17152                     throw new SecurityException("Package " + reportPackage + " is not running in "
17153                             + proc);
17154                 }
17155             }
17156         }
17157         mAppProfiler.setDumpHeapDebugLimit(processName, uid, maxMemSize, reportPackage);
17158     }
17159 
17160     @Override
dumpHeapFinished(String path)17161     public void dumpHeapFinished(String path) {
17162         mAppProfiler.dumpHeapFinished(path, Binder.getCallingPid());
17163     }
17164 
17165     /** In this method we try to acquire our lock to make sure that we have not deadlocked */
monitor()17166     public void monitor() {
17167         synchronized (this) { }
17168     }
17169 
onCoreSettingsChange(Bundle settings)17170     void onCoreSettingsChange(Bundle settings) {
17171         synchronized (mProcLock) {
17172             mProcessList.updateCoreSettingsLOSP(settings);
17173         }
17174     }
17175 
17176     // Multi-user methods
17177 
17178     /**
17179      * Start user, if its not already running, but don't bring it to foreground.
17180      */
17181     @Override
startUserInBackground(final int userId)17182     public boolean startUserInBackground(final int userId) {
17183         return startUserInBackgroundWithListener(userId, null);
17184     }
17185 
17186     @Override
startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17187     public boolean startUserInBackgroundWithListener(final int userId,
17188                 @Nullable IProgressListener unlockListener) {
17189         return mUserController.startUser(userId, USER_START_MODE_BACKGROUND, unlockListener);
17190     }
17191 
17192     @Override
startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17193     public boolean startUserInForegroundWithListener(final int userId,
17194             @Nullable IProgressListener unlockListener) {
17195         // Permission check done inside UserController.
17196         return mUserController.startUser(userId, USER_START_MODE_FOREGROUND, unlockListener);
17197     }
17198 
17199     @Override
startUserInBackgroundVisibleOnDisplay(int userId, int displayId, @Nullable IProgressListener unlockListener)17200     public boolean startUserInBackgroundVisibleOnDisplay(int userId, int displayId,
17201             @Nullable IProgressListener unlockListener) {
17202         int[] displayIds = getDisplayIdsForStartingVisibleBackgroundUsers();
17203         boolean validDisplay = false;
17204         if (displayIds != null) {
17205             for (int i = 0; i < displayIds.length; i++) {
17206                 if (displayId == displayIds[i]) {
17207                     validDisplay = true;
17208                     break;
17209                 }
17210             }
17211         }
17212         if (!validDisplay) {
17213             throw new IllegalArgumentException("Invalid display (" + displayId + ") to start user. "
17214                     + "Valid options are: " + Arrays.toString(displayIds));
17215         }
17216 
17217         if (DEBUG_MU) {
17218             Slogf.d(TAG_MU, "Calling startUserOnSecondaryDisplay(%d, %d, %s) using injector %s",
17219                     userId, displayId, unlockListener, mInjector);
17220         }
17221         // Permission check done inside UserController.
17222         return mInjector.startUserInBackgroundVisibleOnDisplay(userId, displayId, unlockListener);
17223     }
17224 
17225     @Override
getDisplayIdsForStartingVisibleBackgroundUsers()17226     public int[] getDisplayIdsForStartingVisibleBackgroundUsers() {
17227         enforceCallingHasAtLeastOnePermission("getDisplayIdsForStartingVisibleBackgroundUsers()",
17228                 MANAGE_USERS, INTERACT_ACROSS_USERS);
17229         return mInjector.getDisplayIdsForStartingVisibleBackgroundUsers();
17230     }
17231 
17232     /** @deprecated see the AIDL documentation {@inheritDoc} */
17233     @Override
17234     @Deprecated
unlockUser(@serIdInt int userId, @Nullable byte[] token, @Nullable byte[] secret, @Nullable IProgressListener listener)17235     public boolean unlockUser(@UserIdInt int userId, @Nullable byte[] token,
17236             @Nullable byte[] secret, @Nullable IProgressListener listener) {
17237         return mUserController.unlockUser(userId, listener);
17238     }
17239 
17240     @Override
unlockUser2(@serIdInt int userId, @Nullable IProgressListener listener)17241     public boolean unlockUser2(@UserIdInt int userId, @Nullable IProgressListener listener) {
17242         return mUserController.unlockUser(userId, listener);
17243     }
17244 
17245     @Override
switchUser(final int targetUserId)17246     public boolean switchUser(final int targetUserId) {
17247         return mUserController.switchUser(targetUserId);
17248     }
17249 
17250     @Override
getSwitchingFromUserMessage()17251     public String getSwitchingFromUserMessage() {
17252         return mUserController.getSwitchingFromSystemUserMessage();
17253     }
17254 
17255     @Override
getSwitchingToUserMessage()17256     public String getSwitchingToUserMessage() {
17257         return mUserController.getSwitchingToSystemUserMessage();
17258     }
17259 
17260     @Override
setStopUserOnSwitch(@topUserOnSwitch int value)17261     public void setStopUserOnSwitch(@StopUserOnSwitch int value) {
17262         mUserController.setStopUserOnSwitch(value);
17263     }
17264 
17265     @Override
stopUser(final int userId, boolean force, final IStopUserCallback callback)17266     public int stopUser(final int userId, boolean force, final IStopUserCallback callback) {
17267         return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ false,
17268                 /* callback= */ callback, /* keyEvictedCallback= */ null);
17269     }
17270 
17271     /**
17272      * Stops user but allow delayed locking. Delayed locking keeps user unlocked even after
17273      * stopping only if {@code config_multiuserDelayUserDataLocking} overlay is set true.
17274      *
17275      * <p>When delayed locking is not enabled through the overlay, this call becomes the same
17276      * with {@link #stopUser(int, boolean, IStopUserCallback)} call.
17277      *
17278      * @param userId User id to stop.
17279      * @param force Force stop the user even if the user is related with system user or current
17280      *              user.
17281      * @param callback Callback called when user has stopped.
17282      *
17283      * @return {@link ActivityManager#USER_OP_SUCCESS} when user is stopped successfully. Returns
17284      *         other {@code ActivityManager#USER_OP_*} codes for failure.
17285      *
17286      */
17287     @Override
stopUserWithDelayedLocking(final int userId, boolean force, final IStopUserCallback callback)17288     public int stopUserWithDelayedLocking(final int userId, boolean force,
17289             final IStopUserCallback callback) {
17290         return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ true,
17291                 /* callback= */ callback, /* keyEvictedCallback= */ null);
17292     }
17293 
17294     @Override
startProfile(@serIdInt int userId)17295     public boolean startProfile(@UserIdInt int userId) {
17296         return mUserController.startProfile(userId, /* evenWhenDisabled= */ false,
17297                 /* unlockListener= */ null);
17298     }
17299 
17300     @Override
startProfileWithListener(@serIdInt int userId, @Nullable IProgressListener unlockListener)17301     public boolean startProfileWithListener(@UserIdInt int userId,
17302             @Nullable IProgressListener unlockListener) {
17303         return mUserController.startProfile(userId, /* evenWhenDisabled= */ false, unlockListener);
17304     }
17305 
17306     @Override
stopProfile(@serIdInt int userId)17307     public boolean stopProfile(@UserIdInt int userId) {
17308         return mUserController.stopProfile(userId);
17309     }
17310 
17311     @Override
getCurrentUser()17312     public UserInfo getCurrentUser() {
17313         return mUserController.getCurrentUser();
17314     }
17315 
17316     @Override
getCurrentUserId()17317     public @UserIdInt int getCurrentUserId() {
17318         return mUserController.getCurrentUserIdChecked();
17319     }
17320 
getStartedUserState(int userId)17321     String getStartedUserState(int userId) {
17322         final UserState userState = mUserController.getStartedUserState(userId);
17323         return UserState.stateToString(userState.state);
17324     }
17325 
17326     @Override
isUserRunning(int userId, int flags)17327     public boolean isUserRunning(int userId, int flags) {
17328         if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId())
17329                 && checkCallingPermission(INTERACT_ACROSS_USERS)
17330                     != PackageManager.PERMISSION_GRANTED) {
17331             String msg = "Permission Denial: isUserRunning() from pid="
17332                     + Binder.getCallingPid()
17333                     + ", uid=" + Binder.getCallingUid()
17334                     + " requires " + INTERACT_ACROSS_USERS;
17335             Slog.w(TAG, msg);
17336             throw new SecurityException(msg);
17337         }
17338         return mUserController.isUserRunning(userId, flags);
17339     }
17340 
17341     @Override
getRunningUserIds()17342     public int[] getRunningUserIds() {
17343         if (checkCallingPermission(INTERACT_ACROSS_USERS)
17344                 != PackageManager.PERMISSION_GRANTED) {
17345             String msg = "Permission Denial: isUserRunning() from pid="
17346                     + Binder.getCallingPid()
17347                     + ", uid=" + Binder.getCallingUid()
17348                     + " requires " + INTERACT_ACROSS_USERS;
17349             Slog.w(TAG, msg);
17350             throw new SecurityException(msg);
17351         }
17352         return mUserController.getStartedUserArray();
17353     }
17354 
17355     @Override
registerUserSwitchObserver(IUserSwitchObserver observer, String name)17356     public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
17357         mUserController.registerUserSwitchObserver(observer, name);
17358     }
17359 
17360     @Override
unregisterUserSwitchObserver(IUserSwitchObserver observer)17361     public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
17362         mUserController.unregisterUserSwitchObserver(observer);
17363     }
17364 
getAppInfoForUser(ApplicationInfo info, int userId)17365     ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
17366         if (info == null) return null;
17367         ApplicationInfo newInfo = new ApplicationInfo(info);
17368         newInfo.initForUser(userId);
17369         return newInfo;
17370     }
17371 
isUserStopped(int userId)17372     public boolean isUserStopped(int userId) {
17373         return mUserController.getStartedUserState(userId) == null;
17374     }
17375 
getActivityInfoForUser(ActivityInfo aInfo, int userId)17376     ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
17377         if (aInfo == null
17378                 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
17379             return aInfo;
17380         }
17381 
17382         ActivityInfo info = new ActivityInfo(aInfo);
17383         info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
17384         return info;
17385     }
17386 
17387     @GuardedBy("mProcLock")
processSanityChecksLPr(ProcessRecord process, IApplicationThread thread)17388     private boolean processSanityChecksLPr(ProcessRecord process, IApplicationThread thread) {
17389         if (process == null || thread == null) {
17390             return false;
17391         }
17392 
17393         return Build.IS_DEBUGGABLE || process.isDebuggable();
17394     }
17395 
startBinderTracking()17396     public boolean startBinderTracking() throws RemoteException {
17397         // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
17398         // permission (same as profileControl).
17399         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17400                 != PackageManager.PERMISSION_GRANTED) {
17401             throw new SecurityException("Requires permission "
17402                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17403         }
17404 
17405         synchronized (mProcLock) {
17406             mBinderTransactionTrackingEnabled = true;
17407             mProcessList.forEachLruProcessesLOSP(true, process -> {
17408                 final IApplicationThread thread = process.getThread();
17409                 if (!processSanityChecksLPr(process, thread)) {
17410                     return;
17411                 }
17412                 try {
17413                     thread.startBinderTracking();
17414                 } catch (RemoteException e) {
17415                     Log.v(TAG, "Process disappared");
17416                 }
17417             });
17418         }
17419         return true;
17420     }
17421 
17422     @Override
stopBinderTrackingAndDump(final ParcelFileDescriptor fd)17423     public boolean stopBinderTrackingAndDump(final ParcelFileDescriptor fd) throws RemoteException {
17424         // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
17425         // permission (same as profileControl).
17426         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17427                 != PackageManager.PERMISSION_GRANTED) {
17428             throw new SecurityException("Requires permission "
17429                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17430         }
17431 
17432         boolean closeFd = true;
17433         try {
17434             synchronized (mProcLock) {
17435                 if (fd == null) {
17436                     throw new IllegalArgumentException("null fd");
17437                 }
17438                 mBinderTransactionTrackingEnabled = false;
17439 
17440                 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor()));
17441                 pw.println("Binder transaction traces for all processes.\n");
17442                 mProcessList.forEachLruProcessesLOSP(true, process -> {
17443                     final IApplicationThread thread = process.getThread();
17444                     if (!processSanityChecksLPr(process, thread)) {
17445                         return;
17446                     }
17447 
17448                     pw.println("Traces for process: " + process.processName);
17449                     pw.flush();
17450                     try {
17451                         TransferPipe tp = new TransferPipe();
17452                         try {
17453                             thread.stopBinderTrackingAndDump(tp.getWriteFd());
17454                             tp.go(fd.getFileDescriptor());
17455                         } finally {
17456                             tp.kill();
17457                         }
17458                     } catch (IOException e) {
17459                         pw.println("Failure while dumping IPC traces from " + process +
17460                                 ".  Exception: " + e);
17461                         pw.flush();
17462                     } catch (RemoteException e) {
17463                         pw.println("Got a RemoteException while dumping IPC traces from " +
17464                                 process + ".  Exception: " + e);
17465                         pw.flush();
17466                     }
17467                 });
17468                 closeFd = false;
17469                 return true;
17470             }
17471         } finally {
17472             if (fd != null && closeFd) {
17473                 try {
17474                     fd.close();
17475                 } catch (IOException e) {
17476                 }
17477             }
17478         }
17479     }
17480 
onProcessFreezableChangedLocked(ProcessRecord app)17481     void onProcessFreezableChangedLocked(ProcessRecord app) {
17482         if (mEnableModernQueue) {
17483             mBroadcastQueues[0].onProcessFreezableChangedLocked(app);
17484         }
17485     }
17486 
17487     @VisibleForTesting
17488     public final class LocalService extends ActivityManagerInternal
17489             implements ActivityManagerLocal {
17490 
17491         @Override
getPendingIntentStats()17492         public List<PendingIntentStats> getPendingIntentStats() {
17493             return mPendingIntentController.dumpPendingIntentStatsForStatsd();
17494         }
17495 
17496         @Override
getAppProfileStatsForDebugging(long time, int lines)17497         public Pair<String, String> getAppProfileStatsForDebugging(long time, int lines) {
17498             return mAppProfiler.getAppProfileStatsForDebugging(time, lines);
17499         }
17500 
17501         @Override
checkContentProviderAccess(String authority, int userId)17502         public String checkContentProviderAccess(String authority, int userId) {
17503             return mCpHelper.checkContentProviderAccess(authority, userId);
17504         }
17505 
17506         @Override
checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)17507         public int checkContentProviderUriPermission(Uri uri, int userId,
17508                 int callingUid, int modeFlags) {
17509             return mCpHelper.checkContentProviderUriPermission(uri, userId, callingUid, modeFlags);
17510         }
17511 
17512         @Override
onWakefulnessChanged(int wakefulness)17513         public void onWakefulnessChanged(int wakefulness) {
17514             ActivityManagerService.this.onWakefulnessChanged(wakefulness);
17515         }
17516 
17517         @Override
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)17518         public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
17519                 String processName, String abiOverride, int uid, Runnable crashHandler) {
17520             return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
17521                     processName, abiOverride, uid, crashHandler);
17522         }
17523 
17524         @Override
startSdkSandboxService(Intent service, int clientAppUid, String clientAppPackage, String processName)17525         public ComponentName startSdkSandboxService(Intent service, int clientAppUid,
17526                 String clientAppPackage, String processName) throws RemoteException {
17527             validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName);
17528             if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) != MODE_ALLOWED) {
17529                 throw new IllegalArgumentException("uid does not belong to provided package");
17530             }
17531             // TODO(b/269598719): Is passing the application thread of the system_server alright?
17532             // e.g. the sandbox getting privileged access due to this.
17533             ComponentName cn = ActivityManagerService.this.startService(
17534                     mContext.getIApplicationThread(), service,
17535                     service.resolveTypeIfNeeded(mContext.getContentResolver()), false,
17536                     mContext.getOpPackageName(), mContext.getAttributionTag(),
17537                     UserHandle.getUserId(clientAppUid), true, clientAppUid, clientAppPackage,
17538                     processName);
17539             if (cn != null) {
17540                 if (cn.getPackageName().equals("!")) {
17541                     throw new SecurityException(
17542                             "Not allowed to start service " + service
17543                                     + " without permission " + cn.getClassName());
17544                 } else if (cn.getPackageName().equals("!!")) {
17545                     throw new SecurityException(
17546                             "Unable to start service " + service
17547                                     + ": " + cn.getClassName());
17548                 } else if (cn.getPackageName().equals("?")) {
17549                     throw ServiceStartNotAllowedException.newInstance(false,
17550                             "Not allowed to start service " + service + ": "
17551                                     + cn.getClassName());
17552                 }
17553             }
17554 
17555             return cn;
17556         }
17557 
17558         @Override
stopSdkSandboxService(Intent service, int clientAppUid, String clientAppPackage, String processName)17559         public boolean stopSdkSandboxService(Intent service, int clientAppUid,
17560                 String clientAppPackage, String processName) {
17561             validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName);
17562             int res = ActivityManagerService.this.stopService(
17563                     mContext.getIApplicationThread(), service,
17564                     service.resolveTypeIfNeeded(mContext.getContentResolver()),
17565                     UserHandle.getUserId(clientAppUid), true, clientAppUid, clientAppPackage,
17566                     processName);
17567             if (res < 0) {
17568                 throw new SecurityException(
17569                         "Not allowed to stop service " + service);
17570             }
17571             return res != 0;
17572         }
17573 
17574         @Override
bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, int flags)17575         public boolean bindSdkSandboxService(Intent service, ServiceConnection conn,
17576                 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage,
17577                 String processName, int flags)
17578                 throws RemoteException {
17579             return bindSdkSandboxServiceInternal(service, conn, clientAppUid,
17580                     clientApplicationThread, clientAppPackage, processName,
17581                     Integer.toUnsignedLong(flags));
17582         }
17583 
17584         @Override
bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, BindServiceFlags flags)17585         public boolean bindSdkSandboxService(Intent service, ServiceConnection conn,
17586                 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage,
17587                 String processName, BindServiceFlags flags) throws RemoteException {
17588             return bindSdkSandboxServiceInternal(service, conn, clientAppUid,
17589                     clientApplicationThread, clientAppPackage, processName, flags.getValue());
17590         }
17591 
bindSdkSandboxServiceInternal(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, long flags)17592         private boolean bindSdkSandboxServiceInternal(Intent service, ServiceConnection conn,
17593                 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage,
17594                 String processName, long flags)
17595                 throws RemoteException {
17596             validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName);
17597             if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) != MODE_ALLOWED) {
17598                 throw new IllegalArgumentException("uid does not belong to provided package");
17599             }
17600             if (conn == null) {
17601                 throw new IllegalArgumentException("connection is null");
17602             }
17603 
17604             Handler handler = mContext.getMainThreadHandler();
17605             IApplicationThread clientApplicationThreadVerified = null;
17606             if (clientApplicationThread != null) {
17607                 // Make sure this is a valid application process
17608                 synchronized (this) {
17609                     final ProcessRecord rec = getRecordForAppLOSP(clientApplicationThread);
17610                     if (rec == null) {
17611                         // This could happen if the calling process has disappeared; no need for the
17612                         // sandbox to be even started in this case.
17613                         Slog.i(TAG, "clientApplicationThread process not found.");
17614                         return false;
17615                     }
17616                     if (rec.info.uid != clientAppUid) {
17617                         throw new IllegalArgumentException("clientApplicationThread does not match "
17618                                 + " client uid");
17619                     }
17620                     clientApplicationThreadVerified = rec.getThread();
17621                 }
17622             }
17623             final IServiceConnection sd = mContext.getServiceDispatcher(conn, handler,
17624                     flags);
17625             service.prepareToLeaveProcess(mContext);
17626             return ActivityManagerService.this.bindServiceInstance(
17627                     mContext.getIApplicationThread(), mContext.getActivityToken(), service,
17628                     service.resolveTypeIfNeeded(mContext.getContentResolver()), sd,
17629                     flags,
17630                     processName, /*isSdkSandboxService*/ true, clientAppUid, clientAppPackage,
17631                     clientApplicationThreadVerified, mContext.getOpPackageName(),
17632                     UserHandle.getUserId(clientAppUid)) != 0;
17633         }
17634 
validateSdkSandboxParams(Intent service, int clientAppUid, String clientAppPackage, String processName)17635         private void validateSdkSandboxParams(Intent service, int clientAppUid,
17636                 String clientAppPackage, String processName) {
17637             if (service == null) {
17638                 throw new IllegalArgumentException("intent is null");
17639             }
17640             if (clientAppPackage == null) {
17641                 throw new IllegalArgumentException("clientAppPackage is null");
17642             }
17643             if (processName == null) {
17644                 throw new IllegalArgumentException("processName is null");
17645             }
17646             if (service.getComponent() == null) {
17647                 throw new IllegalArgumentException("service must specify explicit component");
17648             }
17649             if (!UserHandle.isApp(clientAppUid)) {
17650                 throw new IllegalArgumentException("uid is not within application range");
17651             }
17652         }
17653 
17654         @Override
bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, String clientAppPackage, String processName, int flags)17655         public boolean bindSdkSandboxService(Intent service, ServiceConnection conn,
17656                 int clientAppUid, String clientAppPackage, String processName, int flags)
17657                 throws RemoteException {
17658             return bindSdkSandboxService(service, conn, clientAppUid,
17659                     null /* clientApplicationThread */, clientAppPackage, processName, flags);
17660         }
17661 
17662         @Override
killSdkSandboxClientAppProcess(IBinder clientApplicationThreadBinder)17663         public void killSdkSandboxClientAppProcess(IBinder clientApplicationThreadBinder) {
17664             synchronized (ActivityManagerService.this) {
17665                 ProcessRecord r = getRecordForAppLOSP(clientApplicationThreadBinder);
17666                 if (r != null) {
17667                     r.killLocked(
17668                             "sdk sandbox died",
17669                             ApplicationExitInfo.REASON_DEPENDENCY_DIED,
17670                             ApplicationExitInfo.SUBREASON_SDK_SANDBOX_DIED,
17671                             true);
17672                 }
17673             }
17674         }
17675 
17676         @Override
onUserRemoved(@serIdInt int userId)17677         public void onUserRemoved(@UserIdInt int userId) {
17678             // Clean up any ActivityTaskManager state (by telling it the user is stopped)
17679             mAtmInternal.onUserStopped(userId);
17680             // Clean up various services by removing the user
17681             mBatteryStatsService.onUserRemoved(userId);
17682 
17683             synchronized (mThemeOverlayReadyUsers) {
17684                 mThemeOverlayReadyUsers.remove(userId);
17685             }
17686         }
17687 
17688         @Override
killForegroundAppsForUser(@serIdInt int userId)17689         public void killForegroundAppsForUser(@UserIdInt int userId) {
17690             final ArrayList<ProcessRecord> procs = new ArrayList<>();
17691             synchronized (mProcLock) {
17692                 final int numOfProcs = mProcessList.getProcessNamesLOSP().getMap().size();
17693                 for (int ip = 0; ip < numOfProcs; ip++) {
17694                     final SparseArray<ProcessRecord> apps =
17695                             mProcessList.getProcessNamesLOSP().getMap().valueAt(ip);
17696                     final int NA = apps.size();
17697                     for (int ia = 0; ia < NA; ia++) {
17698                         final ProcessRecord app = apps.valueAt(ia);
17699                         if (app.isPersistent()) {
17700                             // We don't kill persistent processes.
17701                             continue;
17702                         }
17703                         if (app.isRemoved()
17704                                 || (app.userId == userId && app.mState.hasForegroundActivities())) {
17705                             procs.add(app);
17706                         }
17707                     }
17708                 }
17709             }
17710 
17711             final int numOfProcs = procs.size();
17712             if (numOfProcs > 0) {
17713                 synchronized (ActivityManagerService.this) {
17714                     for (int i = 0; i < numOfProcs; i++) {
17715                         mProcessList.removeProcessLocked(procs.get(i), false, true,
17716                                 ApplicationExitInfo.REASON_OTHER,
17717                                 ApplicationExitInfo.SUBREASON_KILL_ALL_FG,
17718                                 "kill all fg");
17719                     }
17720                 }
17721             }
17722         }
17723 
17724         @Override
setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, int type, @ReasonCode int reasonCode, @Nullable String reason)17725         public void setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken,
17726                 long duration, int type, @ReasonCode int reasonCode, @Nullable String reason) {
17727             mPendingIntentController.setPendingIntentAllowlistDuration(target, allowlistToken,
17728                     duration, type, reasonCode, reason);
17729         }
17730 
17731         @Override
getPendingIntentFlags(IIntentSender target)17732         public int getPendingIntentFlags(IIntentSender target) {
17733             return mPendingIntentController.getPendingIntentFlags(target);
17734         }
17735 
17736         @Override
getStartedUserIds()17737         public int[] getStartedUserIds() {
17738             return mUserController.getStartedUserArray();
17739         }
17740 
17741         @Override
setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken, int flags)17742         public void setPendingIntentAllowBgActivityStarts(IIntentSender target,
17743                 IBinder allowlistToken, int flags) {
17744             if (!(target instanceof PendingIntentRecord)) {
17745                 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():"
17746                         + " not a PendingIntentRecord: " + target);
17747                 return;
17748             }
17749             synchronized (ActivityManagerService.this) {
17750                 ((PendingIntentRecord) target).setAllowBgActivityStarts(allowlistToken, flags);
17751             }
17752         }
17753 
17754         @Override
clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)17755         public void clearPendingIntentAllowBgActivityStarts(IIntentSender target,
17756                 IBinder allowlistToken) {
17757             if (!(target instanceof PendingIntentRecord)) {
17758                 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():"
17759                         + " not a PendingIntentRecord: " + target);
17760                 return;
17761             }
17762             synchronized (ActivityManagerService.this) {
17763                 ((PendingIntentRecord) target).clearAllowBgActivityStarts(allowlistToken);
17764             }
17765         }
17766 
17767         @Override
setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)17768         public void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids) {
17769             synchronized (ActivityManagerService.this) {
17770                 synchronized (mProcLock) {
17771                     mDeviceIdleAllowlist = allAppids;
17772                     mDeviceIdleExceptIdleAllowlist = exceptIdleAppids;
17773                     mAppRestrictionController.setDeviceIdleAllowlist(allAppids, exceptIdleAppids);
17774                 }
17775             }
17776         }
17777 
17778         @Override
updateDeviceIdleTempAllowlist(@ullable int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)17779         public void updateDeviceIdleTempAllowlist(@Nullable int[] appids, int changingUid,
17780                 boolean adding, long durationMs, @TempAllowListType int type,
17781                 @ReasonCode int reasonCode, @Nullable String reason, int callingUid) {
17782             synchronized (ActivityManagerService.this) {
17783                 synchronized (mProcLock) {
17784                     if (appids != null) {
17785                         mDeviceIdleTempAllowlist = appids;
17786                     }
17787                     if (adding) {
17788                         if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) {
17789                             // Note, the device idle temp-allowlist are by app-ids, but here
17790                             // mFgsStartTempAllowList contains UIDs.
17791                             mFgsStartTempAllowList.add(changingUid, durationMs,
17792                                     new FgsTempAllowListItem(durationMs, reasonCode, reason,
17793                                     callingUid));
17794                         }
17795                     } else {
17796                         mFgsStartTempAllowList.removeUid(changingUid);
17797                     }
17798                     setAppIdTempAllowlistStateLSP(changingUid, adding);
17799                 }
17800             }
17801         }
17802 
17803         @Override
getUidProcessState(int uid)17804         public int getUidProcessState(int uid) {
17805             return getUidState(uid);
17806         }
17807 
17808         @Override
getProcessesWithPendingBindMounts(int userId)17809         public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) {
17810             return mProcessList.getProcessesWithPendingBindMounts(userId);
17811         }
17812 
17813         @Override
isSystemReady()17814         public boolean isSystemReady() {
17815             // no need to synchronize(this) just to read & return the value
17816             return mSystemReady;
17817         }
17818 
17819         @Override
isModernQueueEnabled()17820         public boolean isModernQueueEnabled() {
17821             return mEnableModernQueue;
17822         }
17823 
17824         @Override
enforceBroadcastOptionsPermissions(Bundle options, int callingUid)17825         public void enforceBroadcastOptionsPermissions(Bundle options, int callingUid) {
17826             enforceBroadcastOptionPermissionsInternal(options, callingUid);
17827         }
17828 
17829         /**
17830          * Returns package name by pid.
17831          */
17832         @Override
17833         @Nullable
getPackageNameByPid(int pid)17834         public String getPackageNameByPid(int pid) {
17835             synchronized (mPidsSelfLocked) {
17836                 final ProcessRecord app = mPidsSelfLocked.get(pid);
17837 
17838                 if (app != null && app.info != null) {
17839                     return app.info.packageName;
17840                 }
17841 
17842                 return null;
17843             }
17844         }
17845 
17846         /**
17847          * Sets if the given pid has an overlay UI or not.
17848          *
17849          * @param pid The pid we are setting overlay UI for.
17850          * @param hasOverlayUi True if the process has overlay UI.
17851          * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
17852          */
17853         @Override
setHasOverlayUi(int pid, boolean hasOverlayUi)17854         public void setHasOverlayUi(int pid, boolean hasOverlayUi) {
17855             synchronized (ActivityManagerService.this) {
17856                 final ProcessRecord pr;
17857                 synchronized (mPidsSelfLocked) {
17858                     pr = mPidsSelfLocked.get(pid);
17859                     if (pr == null) {
17860                         Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid);
17861                         return;
17862                     }
17863                 }
17864                 if (pr.mState.hasOverlayUi() == hasOverlayUi) {
17865                     return;
17866                 }
17867                 pr.mState.setHasOverlayUi(hasOverlayUi);
17868                 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid);
17869                 updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY);
17870             }
17871         }
17872 
17873         /**
17874          * Called after the network policy rules are updated by
17875          * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid}
17876          * and {@param procStateSeq}.
17877          */
17878         @Override
notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)17879         public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) {
17880             if (DEBUG_NETWORK) {
17881                 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: "
17882                         + uid + " seq: " + procStateSeq);
17883             }
17884             UidRecord record;
17885             synchronized (mProcLock) {
17886                 record = mProcessList.getUidRecordLOSP(uid);
17887                 if (record == null) {
17888                     if (DEBUG_NETWORK) {
17889                         Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid
17890                                 + " procStateSeq: " + procStateSeq);
17891                     }
17892                     return;
17893                 }
17894             }
17895             synchronized (record.networkStateLock) {
17896                 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
17897                     if (DEBUG_NETWORK) {
17898                         Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already"
17899                                 + " been handled for uid: " + uid);
17900                     }
17901                     return;
17902                 }
17903                 record.lastNetworkUpdatedProcStateSeq = procStateSeq;
17904                 if (record.procStateSeqWaitingForNetwork != 0
17905                         && procStateSeq >= record.procStateSeqWaitingForNetwork) {
17906                     if (DEBUG_NETWORK) {
17907                         Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid
17908                                 + ", procStateSeq: " + procStateSeq
17909                                 + ", procStateSeqWaitingForNetwork: "
17910                                 + record.procStateSeqWaitingForNetwork);
17911                     }
17912                     record.networkStateLock.notifyAll();
17913                 }
17914             }
17915         }
17916 
17917         @Override
onUidBlockedReasonsChanged(int uid, int blockedReasons)17918         public void onUidBlockedReasonsChanged(int uid, int blockedReasons) {
17919             synchronized (mUidNetworkBlockedReasons) {
17920                 if (blockedReasons == BLOCKED_REASON_NONE) {
17921                     mUidNetworkBlockedReasons.delete(uid);
17922                 } else {
17923                     mUidNetworkBlockedReasons.put(uid, blockedReasons);
17924                 }
17925             }
17926         }
17927 
17928         @Override
isRuntimeRestarted()17929         public boolean isRuntimeRestarted() {
17930             return mSystemServiceManager.isRuntimeRestarted();
17931         }
17932 
17933         @Override
canStartMoreUsers()17934         public boolean canStartMoreUsers() {
17935             return mUserController.canStartMoreUsers();
17936         }
17937 
17938         @Override
setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)17939         public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) {
17940             mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage);
17941         }
17942 
17943         @Override
setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)17944         public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) {
17945             mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage);
17946         }
17947 
17948         @Override
getMaxRunningUsers()17949         public int getMaxRunningUsers() {
17950             return mUserController.getMaxRunningUsers();
17951         }
17952 
17953         @Override
isUidActive(int uid)17954         public boolean isUidActive(int uid) {
17955             synchronized (mProcLock) {
17956                 return isUidActiveLOSP(uid);
17957             }
17958         }
17959 
17960         @Override
getMemoryStateForProcesses()17961         public List<ProcessMemoryState> getMemoryStateForProcesses() {
17962             List<ProcessMemoryState> processMemoryStates = new ArrayList<>();
17963             synchronized (mPidsSelfLocked) {
17964                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
17965                     final ProcessRecord r = mPidsSelfLocked.valueAt(i);
17966                     processMemoryStates.add(new ProcessMemoryState(
17967                             r.uid, r.getPid(), r.processName, r.mState.getCurAdj(),
17968                             r.mServices.hasForegroundServices(),
17969                             r.mProfile.getCurrentHostingComponentTypes(),
17970                             r.mProfile.getHistoricalHostingComponentTypes()));
17971                 }
17972             }
17973             return processMemoryStates;
17974         }
17975 
17976         @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)17977         public int handleIncomingUser(int callingPid, int callingUid, int userId,
17978                 boolean allowAll, int allowMode, String name, String callerPackage) {
17979             return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
17980                     allowMode, name, callerPackage);
17981         }
17982 
17983         @Override
enforceCallingPermission(String permission, String func)17984         public void enforceCallingPermission(String permission, String func) {
17985             ActivityManagerService.this.enforceCallingPermission(permission, func);
17986         }
17987 
17988         @Override
getCurrentAndTargetUserIds()17989         public Pair<Integer, Integer> getCurrentAndTargetUserIds() {
17990             return mUserController.getCurrentAndTargetUserIds();
17991         }
17992 
17993         @Override
getCurrentUserId()17994         public int getCurrentUserId() {
17995             return mUserController.getCurrentUserId();
17996         }
17997 
17998         @Override
isUserRunning(int userId, int flags)17999         public boolean isUserRunning(int userId, int flags) {
18000             // Holding am lock isn't required to call into user controller.
18001             return mUserController.isUserRunning(userId, flags);
18002         }
18003 
18004         @Override
trimApplications()18005         public void trimApplications() {
18006             ActivityManagerService.this.trimApplications(true, OOM_ADJ_REASON_ACTIVITY);
18007         }
18008 
killProcessesForRemovedTask(ArrayList<Object> procsToKill)18009         public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) {
18010             synchronized (ActivityManagerService.this) {
18011                 for (int i = 0; i < procsToKill.size(); i++) {
18012                     final WindowProcessController wpc =
18013                             (WindowProcessController) procsToKill.get(i);
18014                     final ProcessRecord pr = (ProcessRecord) wpc.mOwner;
18015                     if (ActivityManager.isProcStateBackground(pr.mState.getSetProcState())
18016                             && pr.mReceivers.numberOfCurReceivers() == 0) {
18017                         pr.killLocked("remove task", ApplicationExitInfo.REASON_USER_REQUESTED,
18018                                 ApplicationExitInfo.SUBREASON_REMOVE_TASK, true);
18019                     } else {
18020                         // We delay killing processes that are not in the background or running a
18021                         // receiver.
18022                         pr.setWaitingToKill("remove task");
18023                     }
18024                 }
18025             }
18026         }
18027 
18028         @Override
killProcess(String processName, int uid, String reason)18029         public void killProcess(String processName, int uid, String reason) {
18030             synchronized (ActivityManagerService.this) {
18031                 final ProcessRecord proc = getProcessRecordLocked(processName, uid);
18032                 if (proc != null) {
18033                     mProcessList.removeProcessLocked(proc, false /* callerWillRestart */,
18034                             true /* allowRestart */,  ApplicationExitInfo.REASON_OTHER, reason);
18035                 }
18036             }
18037         }
18038 
18039         @Override
hasRunningActivity(int uid, @Nullable String packageName)18040         public boolean hasRunningActivity(int uid, @Nullable String packageName) {
18041             if (packageName == null) return false;
18042 
18043             synchronized (mProcLock) {
18044                 return mProcessList.searchEachLruProcessesLOSP(true, app -> {
18045                     if (app.uid == uid
18046                             && app.getWindowProcessController().hasRunningActivity(packageName)) {
18047                         return Boolean.TRUE;
18048                     }
18049                     return null;
18050                 }) != null;
18051             }
18052         }
18053 
18054         @Override
updateOomAdj(@omAdjReason int oomAdjReason)18055         public void updateOomAdj(@OomAdjReason int oomAdjReason) {
18056             synchronized (ActivityManagerService.this) {
18057                 ActivityManagerService.this.updateOomAdjLocked(oomAdjReason);
18058             }
18059         }
18060 
18061         @Override
updateCpuStats()18062         public void updateCpuStats() {
18063             ActivityManagerService.this.updateCpuStats();
18064         }
18065 
18066         @Override
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)18067         public void updateBatteryStats(ComponentName activity, int uid, int userId,
18068                 boolean resumed) {
18069             ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed);
18070         }
18071 
18072         @Override
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)18073         public void updateActivityUsageStats(ComponentName activity, int userId, int event,
18074                 IBinder appToken, ComponentName taskRoot, ActivityId activityId) {
18075             ActivityManagerService.this.updateActivityUsageStats(activity, userId, event,
18076                     appToken, taskRoot, activityId);
18077         }
18078 
18079         @Override
updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)18080         public void updateForegroundTimeIfOnBattery(
18081                 String packageName, int uid, long cpuTimeDiff) {
18082             mBatteryStatsService.updateForegroundTimeIfOnBattery(packageName, uid, cpuTimeDiff);
18083         }
18084 
18085         @Override
sendForegroundProfileChanged(int userId)18086         public void sendForegroundProfileChanged(int userId) {
18087             mUserController.sendForegroundProfileChanged(userId);
18088         }
18089 
18090         @Override
shouldConfirmCredentials(int userId)18091         public boolean shouldConfirmCredentials(int userId) {
18092             return mUserController.shouldConfirmCredentials(userId);
18093         }
18094 
18095         @Override
noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)18096         public void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid,
18097                 String tag) {
18098             ActivityManagerService.this.noteAlarmFinish((ps != null) ? ps.getTarget() : null,
18099                     workSource, sourceUid, tag);
18100         }
18101 
18102         @Override
noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)18103         public void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid,
18104                 String tag) {
18105             ActivityManagerService.this.noteAlarmStart((ps != null) ? ps.getTarget() : null,
18106                     workSource, sourceUid, tag);
18107         }
18108 
18109         @Override
noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)18110         public void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid,
18111                 String sourcePkg, String tag) {
18112             ActivityManagerService.this.noteWakeupAlarm((ps != null) ? ps.getTarget() : null,
18113                     workSource, sourceUid, sourcePkg, tag);
18114         }
18115 
18116         @Override
isAppStartModeDisabled(int uid, String packageName)18117         public boolean isAppStartModeDisabled(int uid, String packageName) {
18118             return ActivityManagerService.this.isAppStartModeDisabled(uid, packageName);
18119         }
18120 
18121         @Override
getCurrentProfileIds()18122         public int[] getCurrentProfileIds() {
18123             return mUserController.getCurrentProfileIds();
18124         }
18125 
18126         @Override
getCurrentUser()18127         public UserInfo getCurrentUser() {
18128             return mUserController.getCurrentUser();
18129         }
18130 
18131         @Override
ensureNotSpecialUser(int userId)18132         public void ensureNotSpecialUser(int userId) {
18133             mUserController.ensureNotSpecialUser(userId);
18134         }
18135 
18136         @Override
isCurrentProfile(int userId)18137         public boolean isCurrentProfile(int userId) {
18138             return mUserController.isCurrentProfile(userId);
18139         }
18140 
18141         @Override
hasStartedUserState(int userId)18142         public boolean hasStartedUserState(int userId) {
18143             return mUserController.hasStartedUserState(userId);
18144         }
18145 
18146         @Override
finishUserSwitch(Object uss)18147         public void finishUserSwitch(Object uss) {
18148             mUserController.finishUserSwitch((UserState) uss);
18149         }
18150 
18151         @Override
scheduleAppGcs()18152         public void scheduleAppGcs() {
18153             synchronized (mAppProfiler.mProfilerLock) {
18154                 mAppProfiler.scheduleAppGcsLPf();
18155             }
18156         }
18157 
18158         @Override
getTaskIdForActivity(IBinder token, boolean onlyRoot)18159         public int getTaskIdForActivity(IBinder token, boolean onlyRoot) {
18160             return ActivityManagerService.this.getTaskForActivity(token, onlyRoot);
18161         }
18162 
18163         @Override
getActivityPresentationInfo(IBinder token)18164         public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) {
18165             final ActivityClient ac = ActivityClient.getInstance();
18166             return new ActivityPresentationInfo(ac.getTaskForActivity(token,
18167                     /*onlyRoot=*/ false), ac.getDisplayId(token),
18168                     mAtmInternal.getActivityName(token));
18169         }
18170 
18171         @Override
setBooting(boolean booting)18172         public void setBooting(boolean booting) {
18173             mBooting = booting;
18174         }
18175 
18176         @Override
isBooting()18177         public boolean isBooting() {
18178             return mBooting;
18179         }
18180 
18181         @Override
setBooted(boolean booted)18182         public void setBooted(boolean booted) {
18183             mBooted = booted;
18184         }
18185 
18186         @Override
isBooted()18187         public boolean isBooted() {
18188             return mBooted;
18189         }
18190 
18191         @Override
finishBooting()18192         public void finishBooting() {
18193             ActivityManagerService.this.finishBooting();
18194         }
18195 
18196         @Override
tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)18197         public void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid,
18198                 long duration, int type, @ReasonCode int reasonCode, String reason) {
18199             synchronized (ActivityManagerService.this) {
18200                 ActivityManagerService.this.tempAllowlistForPendingIntentLocked(
18201                         callerPid, callerUid, targetUid, duration, type, reasonCode, reason);
18202             }
18203         }
18204 
18205         @Override
broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList)18206         public int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid,
18207                 int realCallingUid, int realCallingPid, Intent intent, String resolvedType,
18208                 IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode,
18209                 String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions,
18210                 boolean serialized, boolean sticky, int userId,
18211                 BackgroundStartPrivileges backgroundStartPrivileges,
18212                 @Nullable int[] broadcastAllowList) {
18213             synchronized (ActivityManagerService.this) {
18214                 final ProcessRecord resultToApp = getRecordForAppLOSP(resultToThread);
18215                 return ActivityManagerService.this.broadcastIntentInPackage(packageName, featureId,
18216                         uid, realCallingUid, realCallingPid, intent, resolvedType, resultToApp,
18217                         resultTo, resultCode, resultData, resultExtras, requiredPermission,
18218                         bOptions, serialized, sticky, userId,
18219                         backgroundStartPrivileges,
18220                         broadcastAllowList);
18221             }
18222         }
18223 
18224         @Override
broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)18225         public int broadcastIntent(Intent intent,
18226                 IIntentReceiver resultTo,
18227                 String[] requiredPermissions,
18228                 boolean serialized, int userId, int[] appIdAllowList,
18229                 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver,
18230                 @Nullable Bundle bOptions) {
18231             synchronized (ActivityManagerService.this) {
18232                 intent = verifyBroadcastLocked(intent);
18233 
18234                 final int callingPid = Binder.getCallingPid();
18235                 final int callingUid = Binder.getCallingUid();
18236                 final long origId = Binder.clearCallingIdentity();
18237                 try {
18238                     return ActivityManagerService.this.broadcastIntentLocked(null /*callerApp*/,
18239                             null /*callerPackage*/, null /*callingFeatureId*/, intent,
18240                             null /* resolvedType */, null /* resultToApp */, resultTo,
18241                             0 /* resultCode */, null /* resultData */,
18242                             null /* resultExtras */, requiredPermissions,
18243                             null /*excludedPermissions*/, null /*excludedPackages*/,
18244                             AppOpsManager.OP_NONE, bOptions /*options*/, serialized,
18245                             false /*sticky*/, callingPid, callingUid, callingUid, callingPid,
18246                             userId, BackgroundStartPrivileges.NONE,
18247                             appIdAllowList, filterExtrasForReceiver);
18248                 } finally {
18249                     Binder.restoreCallingIdentity(origId);
18250                 }
18251             }
18252 
18253         }
18254 
18255         @Override
broadcastIntentWithCallback(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)18256         public int broadcastIntentWithCallback(Intent intent,
18257                 IIntentReceiver resultTo,
18258                 String[] requiredPermissions,
18259                 int userId, int[] appIdAllowList,
18260                 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver,
18261                 @Nullable Bundle bOptions) {
18262             // Sending broadcasts with a finish callback without the need for the broadcasts
18263             // delivery to be serialized is only supported by modern queue. So, when modern
18264             // queue is disabled, we continue to send broadcasts in a serialized fashion.
18265             final boolean serialized = !isModernQueueEnabled();
18266             return broadcastIntent(intent, resultTo, requiredPermissions, serialized, userId,
18267                     appIdAllowList, filterExtrasForReceiver, bOptions);
18268         }
18269 
18270         @Override
startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, int userId, BackgroundStartPrivileges backgroundStartPrivileges)18271         public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType,
18272                 boolean fgRequired, String callingPackage, @Nullable String callingFeatureId,
18273                 int userId, BackgroundStartPrivileges backgroundStartPrivileges)
18274                 throws TransactionTooLargeException {
18275             if (DEBUG_SERVICE) {
18276                 Slog.v(TAG_SERVICE,
18277                         "startServiceInPackage: " + service + " type=" + resolvedType);
18278             }
18279             final long origId = Binder.clearCallingIdentity();
18280             ComponentName res;
18281             try {
18282                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
18283                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startServiceInPackage: "
18284                             + "intent=" + service + ", caller=" + callingPackage
18285                             + ", fgRequired=" + fgRequired);
18286                 }
18287                 synchronized (ActivityManagerService.this) {
18288                     res = mServices.startServiceLocked(null, service,
18289                             resolvedType, -1, uid, fgRequired, callingPackage,
18290                             callingFeatureId, userId,
18291                             backgroundStartPrivileges);
18292                 }
18293             } finally {
18294                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
18295                 Binder.restoreCallingIdentity(origId);
18296             }
18297             return res;
18298         }
18299 
18300         // The arguments here are untyped because the base ActivityManagerInternal class
18301         // doesn't have compile-time visibility into ActivityServiceConnectionHolder or
18302         // ConnectionRecord.
18303         @Override
disconnectActivityFromServices(Object connectionHolder)18304         public void disconnectActivityFromServices(Object connectionHolder) {
18305             // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder
18306             final ActivityServiceConnectionsHolder holder =
18307                     (ActivityServiceConnectionsHolder) connectionHolder;
18308             synchronized (ActivityManagerService.this) {
18309                 synchronized (mProcLock) {
18310                     holder.forEachConnection(cr -> mServices.removeConnectionLocked(
18311                             (ConnectionRecord) cr, null /* skipApp */, holder /* skipAct */,
18312                             false /* enqueueOomAdj */));
18313                 }
18314             }
18315         }
18316 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)18317         public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
18318             synchronized(ActivityManagerService.this) {
18319                 mServices.cleanUpServices(userId, component, baseIntent);
18320             }
18321         }
18322 
getActivityInfoForUser(ActivityInfo aInfo, int userId)18323         public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
18324             // Locked intentionally not held as it isn't needed for this case.
18325             return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId);
18326         }
18327 
ensureBootCompleted()18328         public void ensureBootCompleted() {
18329             // Locked intentionally not held as it isn't needed for this case.
18330             ActivityManagerService.this.ensureBootCompleted();
18331         }
18332 
updateOomLevelsForDisplay(int displayId)18333         public void updateOomLevelsForDisplay(int displayId) {
18334             synchronized(ActivityManagerService.this) {
18335                 if (mWindowManager != null) {
18336                     mProcessList.applyDisplaySize(mWindowManager);
18337                 }
18338             }
18339         }
18340 
isActivityStartsLoggingEnabled()18341         public boolean isActivityStartsLoggingEnabled() {
18342             return mConstants.mFlagActivityStartsLoggingEnabled;
18343         }
18344 
isBackgroundActivityStartsEnabled()18345         public boolean isBackgroundActivityStartsEnabled() {
18346             return mConstants.mFlagBackgroundActivityStartsEnabled;
18347         }
18348 
18349         @Override
getBackgroundStartPrivileges(int uid)18350         public BackgroundStartPrivileges getBackgroundStartPrivileges(int uid) {
18351             return ActivityManagerService.this.getBackgroundStartPrivileges(uid);
18352         }
18353 
18354         @Override
canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)18355         public boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName) {
18356             return ActivityManagerService.this.canScheduleUserInitiatedJobs(uid, pid, pkgName);
18357         }
18358 
reportCurKeyguardUsageEvent(boolean keyguardShowing)18359         public void reportCurKeyguardUsageEvent(boolean keyguardShowing) {
18360             ActivityManagerService.this.reportGlobalUsageEvent(keyguardShowing
18361                     ? UsageEvents.Event.KEYGUARD_SHOWN
18362                     : UsageEvents.Event.KEYGUARD_HIDDEN);
18363         }
18364 
18365         @Override
monitor()18366         public void monitor() {
18367             ActivityManagerService.this.monitor();
18368         }
18369 
18370         @Override
inputDispatchingTimedOut(int pid, boolean aboveSystem, TimeoutRecord timeoutRecord)18371         public long inputDispatchingTimedOut(int pid, boolean aboveSystem,
18372                 TimeoutRecord timeoutRecord) {
18373             return ActivityManagerService.this.inputDispatchingTimedOut(pid, aboveSystem,
18374                     timeoutRecord);
18375         }
18376 
18377         @Override
inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, TimeoutRecord timeoutRecord)18378         public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName,
18379                 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc,
18380                 boolean aboveSystem, TimeoutRecord timeoutRecord) {
18381             return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc,
18382                     activityShortComponentName, aInfo, parentShortComponentName,
18383                     (WindowProcessController) parentProc, aboveSystem, timeoutRecord);
18384         }
18385 
18386         @Override
inputDispatchingResumed(int pid)18387         public void inputDispatchingResumed(int pid) {
18388             final ProcessRecord proc;
18389             synchronized (mPidsSelfLocked) {
18390                 proc = mPidsSelfLocked.get(pid);
18391             }
18392             if (proc != null) {
18393                 mAppErrors.handleDismissAnrDialogs(proc);
18394             }
18395         }
18396 
18397         @Override
rescheduleAnrDialog(Object data)18398         public void rescheduleAnrDialog(Object data) {
18399             Message msg = Message.obtain();
18400             msg.what = SHOW_NOT_RESPONDING_UI_MSG;
18401             msg.obj = (AppNotRespondingDialog.Data) data;
18402 
18403             mUiHandler.sendMessageDelayed(msg, InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
18404         }
18405 
18406         @Override
broadcastGlobalConfigurationChanged(int changes, boolean initLocale)18407         public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) {
18408             synchronized (ActivityManagerService.this) {
18409                 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
18410                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18411                         | Intent.FLAG_RECEIVER_REPLACE_PENDING
18412                         | Intent.FLAG_RECEIVER_FOREGROUND
18413                         | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
18414                 final Bundle configChangedOptions = new BroadcastOptions()
18415                         .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
18416                         .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
18417                         .toBundle();
18418                 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
18419                         null, null, OP_NONE, configChangedOptions, false, false, MY_PID, SYSTEM_UID,
18420                         Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
18421                 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
18422                     intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
18423                     intent.addFlags(Intent.FLAG_RECEIVER_OFFLOAD_FOREGROUND
18424                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
18425                             | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
18426                     if (initLocale || !mProcessesReady) {
18427                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
18428                     }
18429                     final BroadcastOptions bOptions = BroadcastOptions.makeBasic();
18430                     bOptions.setTemporaryAppAllowlist(mInternal.getBootTimeTempAllowListDuration(),
18431                             TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
18432                             PowerExemptionManager.REASON_LOCALE_CHANGED, "");
18433                     bOptions.setDeliveryGroupPolicy(
18434                             BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT);
18435                     bOptions.setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE);
18436                     broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
18437                             null, null, OP_NONE, bOptions.toBundle(), false, false, MY_PID,
18438                             SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(),
18439                             UserHandle.USER_ALL);
18440                 }
18441 
18442                 // Send a broadcast to PackageInstallers if the configuration change is interesting
18443                 // for the purposes of installing additional splits.
18444                 if (!initLocale && isSplitConfigurationChange(changes)) {
18445                     intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
18446                     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
18447                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
18448 
18449                     // Typically only app stores will have this permission.
18450                     String[] permissions =
18451                             new String[] { android.Manifest.permission.INSTALL_PACKAGES };
18452                     broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null,
18453                             permissions, null, null, OP_NONE, null, false, false, MY_PID,
18454                             SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(),
18455                             UserHandle.USER_ALL);
18456                 }
18457             }
18458         }
18459 
18460         /**
18461          * Returns true if this configuration change is interesting enough to send an
18462          * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
18463          */
isSplitConfigurationChange(int configDiff)18464         private boolean isSplitConfigurationChange(int configDiff) {
18465             return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
18466         }
18467 
18468         @Override
broadcastCloseSystemDialogs(String reason)18469         public void broadcastCloseSystemDialogs(String reason) {
18470             synchronized (ActivityManagerService.this) {
18471                 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
18472                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18473                         | Intent.FLAG_RECEIVER_FOREGROUND);
18474                 if (reason != null) {
18475                     intent.putExtra("reason", reason);
18476                 }
18477 
18478                 final BroadcastOptions options = new BroadcastOptions()
18479                         .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
18480                         .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE);
18481                 if (reason != null) {
18482                     options.setDeliveryGroupMatchingKey(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, reason);
18483                 }
18484                 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
18485                         null, null, OP_NONE, options.toBundle(), false, false, -1, SYSTEM_UID,
18486                         Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
18487             }
18488         }
18489 
18490         @Override
appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)18491         public void appNotResponding(@NonNull String processName, int uid,
18492                 @NonNull TimeoutRecord timeoutRecord) {
18493             ActivityManagerService.this.appNotResponding(processName, uid, timeoutRecord);
18494         }
18495 
18496         @Override
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)18497         public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
18498             synchronized (ActivityManagerService.this) {
18499                 ActivityManagerService.this.killAllBackgroundProcessesExcept(
18500                         minTargetSdk, maxProcState);
18501             }
18502         }
18503 
18504         @Override
startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)18505         public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
18506                 boolean isTop, String hostingType, ComponentName hostingName) {
18507             try {
18508                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
18509                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
18510                             + processName);
18511                 }
18512                 synchronized (ActivityManagerService.this) {
18513                     // If the process is known as top app, set a hint so when the process is
18514                     // started, the top priority can be applied immediately to avoid cpu being
18515                     // preempted by other processes before attaching the process of top app.
18516                     startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
18517                             new HostingRecord(hostingType, hostingName, isTop),
18518                             ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
18519                             false /* isolated */);
18520                 }
18521             } finally {
18522                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
18523             }
18524         }
18525 
18526         @Override
setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)18527         public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags,
18528                 ProfilerInfo profilerInfo, Object wmLock) {
18529             synchronized (ActivityManagerService.this) {
18530                 /**
18531                  * This function is called from the window manager context and needs to be executed
18532                  * synchronously.  To avoid deadlock, we pass a message to AMS to execute the
18533                  * function and notify the passed in lock when it has been completed.
18534                  */
18535                 synchronized (wmLock) {
18536                     if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
18537                         boolean suspend =
18538                                 (startFlags & ActivityManager.START_FLAG_DEBUG_SUSPEND) != 0;
18539                         setDebugApp(aInfo.processName, true, false, suspend);
18540                     }
18541 
18542                     if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
18543                         setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
18544                     }
18545 
18546                     if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
18547                         setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
18548                     }
18549 
18550                     if (profilerInfo != null) {
18551                         setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo, null);
18552                     }
18553                     wmLock.notify();
18554                 }
18555             }
18556         }
18557 
18558         @Override
getStorageMountMode(int pid, int uid)18559         public int getStorageMountMode(int pid, int uid) {
18560             if (uid == SHELL_UID || uid == ROOT_UID) {
18561                 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18562             }
18563             synchronized (mPidsSelfLocked) {
18564                 final ProcessRecord pr = mPidsSelfLocked.get(pid);
18565                 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.getMountMode();
18566             }
18567         }
18568 
18569         @Override
isAppForeground(int uid)18570         public boolean isAppForeground(int uid) {
18571             return ActivityManagerService.this.isAppForeground(uid);
18572         }
18573 
18574         @Override
isAppBad(final String processName, final int uid)18575         public boolean isAppBad(final String processName, final int uid) {
18576             return ActivityManagerService.this.isAppBad(processName, uid);
18577         }
18578 
18579         @Override
clearPendingBackup(int userId)18580         public void clearPendingBackup(int userId) {
18581             ActivityManagerService.this.clearPendingBackup(userId);
18582         }
18583 
18584         /**
18585          * When power button is very long pressed, call this interface to do some pre-shutdown work
18586          * like persisting database etc.
18587          */
18588         @Override
prepareForPossibleShutdown()18589         public void prepareForPossibleShutdown() {
18590             ActivityManagerService.this.prepareForPossibleShutdown();
18591         }
18592 
18593         @Override
hasRunningForegroundService(int uid, int foregroundServicetype)18594         public boolean hasRunningForegroundService(int uid, int foregroundServicetype) {
18595             synchronized (ActivityManagerService.this) {
18596                 final UidRecord uidRec = mProcessList.mActiveUids.get(uid);
18597                 if (uidRec == null) {
18598                     return false;
18599                 }
18600                 for (int i = uidRec.getNumOfProcs() - 1; i >= 0; i--) {
18601                     final ProcessRecord app = uidRec.getProcessRecordByIndex(i);
18602                     if ((app.mServices.containsAnyForegroundServiceTypes(foregroundServicetype))) {
18603                         return true;
18604                     }
18605                 }
18606                 return false;
18607             }
18608         }
18609 
18610         @Override
hasForegroundServiceNotification(String pkg, int userId, String channelId)18611         public boolean hasForegroundServiceNotification(String pkg, int userId,
18612                 String channelId) {
18613             synchronized (ActivityManagerService.this) {
18614                 return mServices.hasForegroundServiceNotificationLocked(pkg, userId, channelId);
18615             }
18616         }
18617 
18618         @Override
applyForegroundServiceNotification( Notification notification, String tag, int id, String pkg, int userId)18619         public ServiceNotificationPolicy applyForegroundServiceNotification(
18620                 Notification notification, String tag, int id, String pkg, int userId) {
18621             synchronized (ActivityManagerService.this) {
18622                 return mServices.applyForegroundServiceNotificationLocked(notification,
18623                         tag, id, pkg, userId);
18624             }
18625         }
18626 
18627         @Override
onForegroundServiceNotificationUpdate(boolean shown, Notification notification, int id, String pkg, @UserIdInt int userId)18628         public void onForegroundServiceNotificationUpdate(boolean shown,
18629                 Notification notification, int id, String pkg, @UserIdInt int userId) {
18630             synchronized (ActivityManagerService.this) {
18631                 mServices.onForegroundServiceNotificationUpdateLocked(shown,
18632                         notification, id, pkg, userId);
18633             }
18634         }
18635 
18636         @Override
stopAppForUser(String pkg, @UserIdInt int userId)18637         public void stopAppForUser(String pkg, @UserIdInt int userId) {
18638             ActivityManagerService.this.stopAppForUserInternal(pkg, userId);
18639         }
18640 
18641         @Override
registerProcessObserver(IProcessObserver processObserver)18642         public void registerProcessObserver(IProcessObserver processObserver) {
18643             ActivityManagerService.this.registerProcessObserver(processObserver);
18644         }
18645 
18646         @Override
unregisterProcessObserver(IProcessObserver processObserver)18647         public void unregisterProcessObserver(IProcessObserver processObserver) {
18648             ActivityManagerService.this.unregisterProcessObserver(processObserver);
18649         }
18650 
18651         @Override
getInstrumentationSourceUid(int uid)18652         public int getInstrumentationSourceUid(int uid) {
18653             synchronized (mProcLock) {
18654                 for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) {
18655                     ActiveInstrumentation activeInst = mActiveInstrumentation.get(i);
18656                     if (!activeInst.mFinished && activeInst.mTargetInfo != null
18657                             && activeInst.mTargetInfo.uid == uid) {
18658                         return activeInst.mSourceUid;
18659                     }
18660                 }
18661             }
18662             return INVALID_UID;
18663         }
18664 
18665         @Override
setDeviceOwnerUid(int uid)18666         public void setDeviceOwnerUid(int uid) {
18667             mDeviceOwnerUid = uid;
18668         }
18669 
18670         @Override
isDeviceOwner(int uid)18671         public boolean isDeviceOwner(int uid) {
18672             int cachedUid = mDeviceOwnerUid;
18673             return uid >= 0 && cachedUid == uid;
18674         }
18675 
18676 
18677         @Override
setProfileOwnerUid(ArraySet<Integer> profileOwnerUids)18678         public void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids) {
18679             synchronized (ActivityManagerService.this) {
18680                 mProfileOwnerUids = profileOwnerUids;
18681             }
18682         }
18683 
18684         @Override
isProfileOwner(int uid)18685         public boolean isProfileOwner(int uid) {
18686             synchronized (ActivityManagerService.this) {
18687                 return mProfileOwnerUids != null && mProfileOwnerUids.indexOf(uid) >= 0;
18688             }
18689         }
18690 
18691         @Override
setCompanionAppUids(int userId, Set<Integer> companionAppUids)18692         public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) {
18693             synchronized (ActivityManagerService.this) {
18694                 mCompanionAppUidsMap.put(userId, companionAppUids);
18695             }
18696         }
18697 
18698         @Override
isAssociatedCompanionApp(int userId, int uid)18699         public boolean isAssociatedCompanionApp(int userId, int uid) {
18700             final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
18701             if (allUids == null) {
18702                 return false;
18703             }
18704             return allUids.contains(uid);
18705         }
18706 
18707         @Override
addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread)18708         public void addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread) {
18709             final boolean isNewPending = mPendingStartActivityUids.add(uid, pid);
18710             // If the next top activity is in cached and frozen mode, WM should raise its priority
18711             // to unfreeze it. This is done by calling AMS.updateOomAdj that will lower its oom adj.
18712             // However, WM cannot hold the AMS clock here so the updateOomAdj operation is performed
18713             // in a separate thread asynchronously. Therefore WM can't guarantee AMS will unfreeze
18714             // next top activity on time. This race will fail the following binder transactions WM
18715             // sends to the activity. After this race issue between WM/ATMS and AMS is solved, this
18716             // workaround can be removed. (b/213288355)
18717             if (isNewPending) {
18718                 mOomAdjuster.mCachedAppOptimizer.unfreezeProcess(pid, OOM_ADJ_REASON_ACTIVITY);
18719             }
18720             // We need to update the network rules for the app coming to the top state so that
18721             // it can access network when the device or the app is in a restricted state
18722             // (e.g. battery/data saver) but since waiting for updateOomAdj to complete and then
18723             // informing NetworkPolicyManager might get delayed, informing the state change as soon
18724             // as we know app is going to come to the top state.
18725             if (isNewPending && mNetworkPolicyUidObserver != null) {
18726                 try {
18727                     final long procStateSeq = mProcessList.getNextProcStateSeq();
18728                     mNetworkPolicyUidObserver.onUidStateChanged(uid, PROCESS_STATE_TOP,
18729                             procStateSeq, PROCESS_CAPABILITY_ALL);
18730                     if (thread != null && shouldWaitForNetworkRulesUpdate(uid)) {
18731                         thread.setNetworkBlockSeq(procStateSeq);
18732                     }
18733                 } catch (RemoteException e) {
18734                     Slog.d(TAG, "Error calling setNetworkBlockSeq", e);
18735                 }
18736             }
18737         }
18738 
shouldWaitForNetworkRulesUpdate(int uid)18739         private boolean shouldWaitForNetworkRulesUpdate(int uid) {
18740             synchronized (mUidNetworkBlockedReasons) {
18741                 // TODO: We can reuse this data in
18742                 // ProcessList#incrementProcStateSeqAndNotifyAppsLOSP instead of calling into
18743                 // NetworkManagementService.
18744                 final int uidBlockedReasons = mUidNetworkBlockedReasons.get(
18745                         uid, BLOCKED_REASON_NONE);
18746                 // We should only inform the uid to block if it is currently blocked but will be
18747                 // unblocked once it comes to the TOP state.
18748                 return uidBlockedReasons != BLOCKED_REASON_NONE
18749                         && updateBlockedReasonsWithProcState(uidBlockedReasons, PROCESS_STATE_TOP)
18750                         == BLOCKED_REASON_NONE;
18751             }
18752         }
18753 
18754         @Override
deletePendingTopUid(int uid, long nowElapsed)18755         public void deletePendingTopUid(int uid, long nowElapsed) {
18756             mPendingStartActivityUids.delete(uid, nowElapsed);
18757         }
18758 
18759         @Override
isPendingTopUid(int uid)18760         public boolean isPendingTopUid(int uid) {
18761             return mPendingStartActivityUids.isPendingTopUid(uid);
18762         }
18763 
18764         @Override
getIntentForIntentSender(IIntentSender sender)18765         public Intent getIntentForIntentSender(IIntentSender sender) {
18766             return ActivityManagerService.this.getIntentForIntentSender(sender);
18767         }
18768 
18769         @Override
getPendingIntentActivityAsApp( int requestCode, @NonNull Intent intent, int flags, Bundle options, String ownerPkg, int ownerUid)18770         public PendingIntent getPendingIntentActivityAsApp(
18771                 int requestCode, @NonNull Intent intent, int flags, Bundle options,
18772                 String ownerPkg, int ownerUid) {
18773             return getPendingIntentActivityAsApp(requestCode, new Intent[] { intent }, flags,
18774                     options, ownerPkg, ownerUid);
18775         }
18776 
18777         @Override
getPendingIntentActivityAsApp( int requestCode, @NonNull Intent[] intents, int flags, Bundle options, String ownerPkg, int ownerUid)18778         public PendingIntent getPendingIntentActivityAsApp(
18779                 int requestCode, @NonNull Intent[] intents, int flags, Bundle options,
18780                 String ownerPkg, int ownerUid) {
18781             // system callers must explicitly set mutability state
18782             final boolean flagImmutableSet = (flags & PendingIntent.FLAG_IMMUTABLE) != 0;
18783             final boolean flagMutableSet = (flags & PendingIntent.FLAG_MUTABLE) != 0;
18784             if (flagImmutableSet == flagMutableSet) {
18785                 throw new IllegalArgumentException(
18786                         "Must set exactly one of FLAG_IMMUTABLE or FLAG_MUTABLE");
18787             }
18788 
18789             final Context context = ActivityManagerService.this.mContext;
18790             final ContentResolver resolver = context.getContentResolver();
18791             final int len = intents.length;
18792             final String[] resolvedTypes = new String[len];
18793             for (int i = 0; i < len; i++) {
18794                 final Intent intent = intents[i];
18795                 resolvedTypes[i] = intent.resolveTypeIfNeeded(resolver);
18796                 intent.migrateExtraStreamToClipData(context);
18797                 intent.prepareToLeaveProcess(context);
18798             }
18799             IIntentSender target =
18800                     ActivityManagerService.this.getIntentSenderWithFeatureAsApp(
18801                             INTENT_SENDER_ACTIVITY, ownerPkg,
18802                             context.getAttributionTag(), null, null, requestCode,
18803                             intents,
18804                             resolvedTypes,
18805                             flags, options, UserHandle.getUserId(ownerUid), ownerUid);
18806             return target != null ? new PendingIntent(target) : null;
18807         }
18808 
18809         @Override
getBootTimeTempAllowListDuration()18810         public long getBootTimeTempAllowListDuration() {
18811             // Do not lock ActivityManagerService.this here, this API is called by
18812             // PackageManagerService.
18813             return mConstants.mBootTimeTempAllowlistDuration;
18814         }
18815 
18816         @Override
registerAnrController(AnrController controller)18817         public void registerAnrController(AnrController controller) {
18818             mActivityTaskManager.registerAnrController(controller);
18819         }
18820 
18821         @Override
unregisterAnrController(AnrController controller)18822         public void unregisterAnrController(AnrController controller) {
18823             mActivityTaskManager.unregisterAnrController(controller);
18824         }
18825 
18826         @Override
canStartForegroundService(int pid, int uid, @NonNull String packageName)18827         public boolean canStartForegroundService(int pid, int uid, @NonNull String packageName) {
18828             synchronized (ActivityManagerService.this) {
18829                 return mServices.canStartForegroundServiceLocked(pid, uid, packageName);
18830             }
18831         }
18832 
18833         @Override
tempAllowWhileInUsePermissionInFgs(int uid, long durationMs)18834         public void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs) {
18835             mFgsWhileInUseTempAllowList.add(uid, durationMs, "");
18836         }
18837 
18838         @Override
isTempAllowlistedForFgsWhileInUse(int uid)18839         public boolean isTempAllowlistedForFgsWhileInUse(int uid) {
18840             return mFgsWhileInUseTempAllowList.isAllowed(uid);
18841         }
18842 
18843         @Override
canAllowWhileInUsePermissionInFgs(int pid, int uid, @NonNull String packageName)18844         public boolean canAllowWhileInUsePermissionInFgs(int pid, int uid,
18845                 @NonNull String packageName) {
18846             synchronized (ActivityManagerService.this) {
18847                 return mServices.canAllowWhileInUsePermissionInFgsLocked(pid, uid, packageName);
18848             }
18849         }
18850 
18851         @Override
getPushMessagingOverQuotaBehavior()18852         public @TempAllowListType int getPushMessagingOverQuotaBehavior() {
18853             synchronized (ActivityManagerService.this) {
18854                 return mConstants.mPushMessagingOverQuotaBehavior;
18855             }
18856         }
18857 
18858         @Override
getServiceStartForegroundTimeout()18859         public int getServiceStartForegroundTimeout() {
18860             return mConstants.mServiceStartForegroundTimeoutMs;
18861         }
18862 
18863         @Override
getUidCapability(int uid)18864         public int getUidCapability(int uid) {
18865             synchronized (ActivityManagerService.this) {
18866                 UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
18867                 if (uidRecord == null) {
18868                     throw new IllegalArgumentException("uid record for " + uid + " not found");
18869                 }
18870                 return uidRecord.getCurCapability();
18871             }
18872         }
18873 
18874         /**
18875          * @return The PID list of the isolated process with packages matching the given uid.
18876          */
18877         @Nullable
getIsolatedProcesses(int uid)18878         public List<Integer> getIsolatedProcesses(int uid) {
18879             synchronized (ActivityManagerService.this) {
18880                 return mProcessList.getIsolatedProcessesLocked(uid);
18881             }
18882         }
18883 
18884         /** @see ActivityManagerService#sendIntentSender */
18885         @Override
sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)18886         public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code,
18887                 Intent intent, String resolvedType,
18888                 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
18889             return ActivityManagerService.this.sendIntentSender(null, target, allowlistToken, code,
18890                     intent, resolvedType, finishedReceiver, requiredPermission, options);
18891         }
18892 
18893         @Override
setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)18894         public void setVoiceInteractionManagerProvider(
18895                 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) {
18896             ActivityManagerService.this.setVoiceInteractionManagerProvider(provider);
18897         }
18898 
18899         @Override
setStopUserOnSwitch(int value)18900         public void setStopUserOnSwitch(int value) {
18901             ActivityManagerService.this.setStopUserOnSwitch(value);
18902         }
18903 
18904         @Override
getRestrictionLevel(int uid)18905         public @RestrictionLevel int getRestrictionLevel(int uid) {
18906             return mAppRestrictionController.getRestrictionLevel(uid);
18907         }
18908 
18909         @Override
getRestrictionLevel(String pkg, @UserIdInt int userId)18910         public @RestrictionLevel int getRestrictionLevel(String pkg, @UserIdInt int userId) {
18911             return mAppRestrictionController.getRestrictionLevel(pkg, userId);
18912         }
18913 
18914         @Override
isBgAutoRestrictedBucketFeatureFlagEnabled()18915         public boolean isBgAutoRestrictedBucketFeatureFlagEnabled() {
18916             return mAppRestrictionController.isBgAutoRestrictedBucketFeatureFlagEnabled();
18917         }
18918 
18919         @Override
addAppBackgroundRestrictionListener( @onNull ActivityManagerInternal.AppBackgroundRestrictionListener listener)18920         public void addAppBackgroundRestrictionListener(
18921                 @NonNull ActivityManagerInternal.AppBackgroundRestrictionListener listener) {
18922             mAppRestrictionController.addAppBackgroundRestrictionListener(listener);
18923         }
18924 
18925         @Override
addForegroundServiceStateListener( @onNull ForegroundServiceStateListener listener)18926         public void addForegroundServiceStateListener(
18927                 @NonNull ForegroundServiceStateListener listener) {
18928             synchronized (ActivityManagerService.this) {
18929                 mForegroundServiceStateListeners.add(listener);
18930             }
18931         }
18932 
18933         @Override
addBroadcastEventListener(@onNull BroadcastEventListener listener)18934         public void addBroadcastEventListener(@NonNull BroadcastEventListener listener) {
18935             // It's a CopyOnWriteArrayList, so no lock is needed.
18936             mBroadcastEventListeners.add(listener);
18937         }
18938 
18939         @Override
addBindServiceEventListener(@onNull BindServiceEventListener listener)18940         public void addBindServiceEventListener(@NonNull BindServiceEventListener listener) {
18941             // It's a CopyOnWriteArrayList, so no lock is needed.
18942             mBindServiceEventListeners.add(listener);
18943         }
18944 
18945         @Override
restart()18946         public void restart() {
18947             ActivityManagerService.this.restart();
18948         }
18949 
18950         @Override
registerNetworkPolicyUidObserver(@onNull IUidObserver observer, int which, int cutpoint, @NonNull String callingPackage)18951         public void registerNetworkPolicyUidObserver(@NonNull IUidObserver observer,
18952                 int which, int cutpoint, @NonNull String callingPackage) {
18953             mNetworkPolicyUidObserver = observer;
18954             mUidObserverController.register(observer, which, cutpoint, callingPackage,
18955                     Binder.getCallingUid(), /*uids*/null);
18956         }
18957 
18958         @Override
startForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options, @Nullable ServiceConnection connection)18959         public boolean startForegroundServiceDelegate(
18960                 @NonNull ForegroundServiceDelegationOptions options,
18961                 @Nullable ServiceConnection connection) {
18962             synchronized (ActivityManagerService.this) {
18963                 return mServices.startForegroundServiceDelegateLocked(options, connection);
18964             }
18965         }
18966 
18967         @Override
stopForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options)18968         public void stopForegroundServiceDelegate(
18969                 @NonNull ForegroundServiceDelegationOptions options) {
18970             synchronized (ActivityManagerService.this) {
18971                 mServices.stopForegroundServiceDelegateLocked(options);
18972             }
18973         }
18974 
18975         @Override
stopForegroundServiceDelegate(@onNull ServiceConnection connection)18976         public void stopForegroundServiceDelegate(@NonNull ServiceConnection connection) {
18977             synchronized (ActivityManagerService.this) {
18978                 mServices.stopForegroundServiceDelegateLocked(connection);
18979             }
18980         }
18981 
18982         @Override
getClientPackages(String servicePackageName)18983         public ArraySet<String> getClientPackages(String servicePackageName) {
18984             synchronized (ActivityManagerService.this) {
18985                 return mServices.getClientPackagesLocked(servicePackageName);
18986             }
18987         }
18988 
18989         @Override
getRegisteredStrictModeCallback(int callingPid)18990         public IUnsafeIntentStrictModeCallback getRegisteredStrictModeCallback(int callingPid) {
18991             return mStrictModeCallbacks.get(callingPid);
18992         }
18993 
18994         @Override
unregisterStrictModeCallback(int callingPid)18995         public void unregisterStrictModeCallback(int callingPid) {
18996             mStrictModeCallbacks.remove(callingPid);
18997         }
18998 
18999         @Override
startProfileEvenWhenDisabled(@serIdInt int userId)19000         public boolean startProfileEvenWhenDisabled(@UserIdInt int userId) {
19001             return mUserController.startProfile(userId, /* evenWhenDisabled= */ true,
19002                     /* unlockListener= */ null);
19003         }
19004 
19005         @Override
logFgsApiBegin(@oregroundServiceApiType int apiType, int uid, int pid)19006         public void logFgsApiBegin(@ForegroundServiceApiType int apiType,
19007                 int uid, int pid) {
19008             synchronized (this) {
19009                 mServices.logFgsApiBeginLocked(apiType, uid, pid);
19010             }
19011         }
19012 
19013         @Override
logFgsApiEnd(@oregroundServiceApiType int apiType, int uid, int pid)19014         public void logFgsApiEnd(@ForegroundServiceApiType int apiType,
19015                 int uid, int pid) {
19016             synchronized (this) {
19017                 mServices.logFgsApiEndLocked(apiType, uid, pid);
19018             }
19019         }
19020 
19021         @Override
notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, @MediaProjectionTokenEvent int event)19022         public void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken,
19023                 @MediaProjectionTokenEvent int event) {
19024             ActivityManagerService.this.notifyMediaProjectionEvent(uid, projectionToken, event);
19025         }
19026 
19027         @Override
19028         @NonNull
getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull)19029         public StatsEvent getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull) {
19030             return mAppProfiler.mCachedAppsWatermarkData.getCachedAppsHighWatermarkStats(
19031                     atomTag, resetAfterPull);
19032         }
19033 
19034         @Override
clearApplicationUserData(final String packageName, boolean keepState, boolean isRestore, final IPackageDataObserver observer, int userId)19035         public boolean clearApplicationUserData(final String packageName, boolean keepState,
19036                 boolean isRestore, final IPackageDataObserver observer, int userId) {
19037             return ActivityManagerService.this.clearApplicationUserData(packageName, keepState,
19038                     isRestore, observer, userId);
19039         }
19040 
19041         @Override
isThemeOverlayReady(int userId)19042         public boolean isThemeOverlayReady(int userId) {
19043             return ActivityManagerService.this.isThemeOverlayReady(userId);
19044         }
19045     }
19046 
19047     long inputDispatchingTimedOut(int pid, final boolean aboveSystem, TimeoutRecord timeoutRecord) {
19048         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
19049             throw new SecurityException("Requires permission " + FILTER_EVENTS);
19050         }
19051         ProcessRecord proc;
19052         timeoutRecord.mLatencyTracker.waitingOnPidLockStarted();
19053         synchronized (mPidsSelfLocked) {
19054             timeoutRecord.mLatencyTracker.waitingOnPidLockEnded();
19055             proc = mPidsSelfLocked.get(pid);
19056         }
19057         final long timeoutMillis = proc != null ? proc.getInputDispatchingTimeoutMillis() :
19058                 DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
19059 
19060         if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, timeoutRecord)) {
19061             return 0;
19062         }
19063 
19064         return timeoutMillis;
19065     }
19066 
19067     /**
19068      * Handle input dispatching timeouts.
19069      * @return whether input dispatching should be aborted or not.
19070      */
19071     boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName,
19072             ApplicationInfo aInfo, String parentShortComponentName,
19073             WindowProcessController parentProcess, boolean aboveSystem,
19074             TimeoutRecord timeoutRecord) {
19075         try {
19076             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "inputDispatchingTimedOut()");
19077             if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
19078                 throw new SecurityException("Requires permission " + FILTER_EVENTS);
19079             }
19080 
19081             if (proc != null) {
19082                 timeoutRecord.mLatencyTracker.waitingOnAMSLockStarted();
19083                 synchronized (this) {
19084                     timeoutRecord.mLatencyTracker.waitingOnAMSLockEnded();
19085                     if (proc.isDebugging()) {
19086                         return false;
19087                     }
19088 
19089                     if (proc.getActiveInstrumentation() != null) {
19090                         Bundle info = new Bundle();
19091                         info.putString("shortMsg", "keyDispatchingTimedOut");
19092                         info.putString("longMsg", timeoutRecord.mReason);
19093                         finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
19094                         return true;
19095                     }
19096                 }
19097                 mAnrHelper.appNotResponding(proc, activityShortComponentName, aInfo,
19098                         parentShortComponentName, parentProcess, aboveSystem, timeoutRecord,
19099                         /*isContinuousAnr*/ true);
19100             }
19101 
19102             return true;
19103         } finally {
19104             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
19105         }
19106     }
19107 
19108     /**
19109      * Called by app main thread to wait for the network policy rules to get updated.
19110      *
19111      * @param procStateSeq The sequence number indicating the process state change that the main
19112      *                     thread is interested in.
19113      */
19114     @Override
19115     public void waitForNetworkStateUpdate(long procStateSeq) {
19116         final int callingUid = Binder.getCallingUid();
19117         if (DEBUG_NETWORK) {
19118             Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq);
19119         }
19120         UidRecord record;
19121         synchronized (mProcLock) {
19122             record = mProcessList.getUidRecordLOSP(callingUid);
19123             if (record == null) {
19124                 return;
19125             }
19126         }
19127         synchronized (record.networkStateLock) {
19128             if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
19129                 if (DEBUG_NETWORK) {
19130                     Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. "
19131                             + procStateSeq + ", so no need to wait. Uid: "
19132                             + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: "
19133                             + record.lastNetworkUpdatedProcStateSeq);
19134                 }
19135                 return;
19136             }
19137             try {
19138                 if (DEBUG_NETWORK) {
19139                     Slog.d(TAG_NETWORK, "Starting to wait for the network rules update."
19140                         + " Uid: " + callingUid + " procStateSeq: " + procStateSeq);
19141                 }
19142                 final long startTime = SystemClock.uptimeMillis();
19143                 record.procStateSeqWaitingForNetwork = procStateSeq;
19144                 record.networkStateLock.wait(mConstants.mNetworkAccessTimeoutMs);
19145                 record.procStateSeqWaitingForNetwork = 0;
19146                 final long totalTime = SystemClock.uptimeMillis() - startTime;
19147                 if (totalTime >= mConstants.mNetworkAccessTimeoutMs || DEBUG_NETWORK) {
19148                     Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: "
19149                             + totalTime + ". Uid: " + callingUid + " procStateSeq: "
19150                             + procStateSeq + " UidRec: " + record
19151                             + " validateUidRec: "
19152                             + mUidObserverController.getValidateUidRecord(callingUid));
19153                 }
19154             } catch (InterruptedException e) {
19155                 Thread.currentThread().interrupt();
19156             }
19157         }
19158     }
19159 
19160     @Override
19161     public void waitForBroadcastIdle() {
19162         waitForBroadcastIdle(LOG_WRITER_INFO, false);
19163     }
19164 
19165     void waitForBroadcastIdle(@NonNull PrintWriter pw, boolean flushBroadcastLoopers) {
19166         enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()");
19167         if (flushBroadcastLoopers) {
19168             BroadcastLoopers.waitForIdle(pw);
19169         }
19170         for (BroadcastQueue queue : mBroadcastQueues) {
19171             queue.waitForIdle(pw);
19172         }
19173         pw.println("All broadcast queues are idle!");
19174         pw.flush();
19175     }
19176 
19177     @Override
19178     public void waitForBroadcastBarrier() {
19179         waitForBroadcastBarrier(LOG_WRITER_INFO, false, false);
19180     }
19181 
19182     void waitForBroadcastBarrier(@NonNull PrintWriter pw,
19183             boolean flushBroadcastLoopers, boolean flushApplicationThreads) {
19184         enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()");
19185         if (flushBroadcastLoopers) {
19186             BroadcastLoopers.waitForBarrier(pw);
19187         }
19188         for (BroadcastQueue queue : mBroadcastQueues) {
19189             queue.waitForBarrier(pw);
19190         }
19191         if (flushApplicationThreads) {
19192             waitForApplicationBarrier(pw);
19193         }
19194     }
19195 
19196     /**
19197      * Wait for all pending {@link IApplicationThread} events to be processed in
19198      * all currently running apps.
19199      */
19200     void waitForApplicationBarrier(@NonNull PrintWriter pw) {
19201         final CountDownLatch finishedLatch = new CountDownLatch(1);
19202         final AtomicInteger pingCount = new AtomicInteger(0);
19203         final AtomicInteger pongCount = new AtomicInteger(0);
19204         final RemoteCallback pongCallback = new RemoteCallback((result) -> {
19205             if (pongCount.incrementAndGet() == pingCount.get()) {
19206                 finishedLatch.countDown();
19207             }
19208         });
19209 
19210         // Insert an extra "ping" as a sentinel value to guard us from finishing
19211         // too quickly in parallel below
19212         pingCount.incrementAndGet();
19213 
19214         synchronized (ActivityManagerService.this) {
19215             synchronized (mProcLock) {
19216                 final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
19217                         mProcessList.getProcessNamesLOSP().getMap();
19218                 final int numProc = pmap.size();
19219                 for (int iProc = 0; iProc < numProc; iProc++) {
19220                     final SparseArray<ProcessRecord> apps = pmap.valueAt(iProc);
19221                     for (int iApp = 0, numApps = apps.size(); iApp < numApps; iApp++) {
19222                         final ProcessRecord app = apps.valueAt(iApp);
19223                         final IApplicationThread thread = app.getOnewayThread();
19224                         if (thread != null) {
19225                             mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(app,
19226                                     CachedAppOptimizer.UNFREEZE_REASON_PING);
19227                             pingCount.incrementAndGet();
19228                             try {
19229                                 thread.schedulePing(pongCallback);
19230                             } catch (RemoteException ignored) {
19231                                 // When we failed to ping remote process, pretend as
19232                                 // if we received the expected pong
19233                                 pongCallback.sendResult(null);
19234                             }
19235                         }
19236                     }
19237                 }
19238             }
19239         }
19240 
19241         // Now that we've dispatched all "ping" events above, we can send our
19242         // "pong" sentinel value
19243         pongCallback.sendResult(null);
19244 
19245         // Wait for any remaining "pong" events to trickle in
19246         for (int i = 0; i < 30; i++) {
19247             try {
19248                 if (finishedLatch.await(1, TimeUnit.SECONDS)) {
19249                     pw.println("Finished application barriers!");
19250                     pw.flush();
19251                     return;
19252                 } else {
19253                     pw.println("Waiting for application barriers, at " + pongCount.get() + " of "
19254                             + pingCount.get() + "...");
19255                     pw.flush();
19256                 }
19257             } catch (InterruptedException ignored) {
19258             }
19259         }
19260         pw.println("Gave up waiting for application barriers!");
19261         pw.flush();
19262     }
19263 
19264     void waitForBroadcastDispatch(@NonNull PrintWriter pw, @NonNull Intent intent) {
19265         enforceCallingPermission(permission.DUMP, "waitForBroadcastDispatch");
19266         for (BroadcastQueue queue : mBroadcastQueues) {
19267             queue.waitForDispatched(intent, pw);
19268         }
19269     }
19270 
19271     void setIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) {
19272         Objects.requireNonNull(broadcastAction);
19273         enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()");
19274         synchronized (mDeliveryGroupPolicyIgnoredActions) {
19275             mDeliveryGroupPolicyIgnoredActions.add(broadcastAction);
19276         }
19277     }
19278 
19279     void clearIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) {
19280         Objects.requireNonNull(broadcastAction);
19281         enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()");
19282         synchronized (mDeliveryGroupPolicyIgnoredActions) {
19283             mDeliveryGroupPolicyIgnoredActions.remove(broadcastAction);
19284         }
19285     }
19286 
19287     boolean shouldIgnoreDeliveryGroupPolicy(@Nullable String broadcastAction) {
19288         if (broadcastAction == null) {
19289             return false;
19290         }
19291         synchronized (mDeliveryGroupPolicyIgnoredActions) {
19292             return mDeliveryGroupPolicyIgnoredActions.contains(broadcastAction);
19293         }
19294     }
19295 
19296     void dumpDeliveryGroupPolicyIgnoredActions(IndentingPrintWriter ipw) {
19297         synchronized (mDeliveryGroupPolicyIgnoredActions) {
19298             ipw.println(mDeliveryGroupPolicyIgnoredActions);
19299         }
19300     }
19301 
19302     @Override
19303     public void forceDelayBroadcastDelivery(@NonNull String targetPackage,
19304             long delayedDurationMs) {
19305         Objects.requireNonNull(targetPackage);
19306         Preconditions.checkArgumentNonnegative(delayedDurationMs);
19307         enforceCallingPermission(permission.DUMP, "forceDelayBroadcastDelivery()");
19308         // Ignore request if modern queue is not enabled
19309         if (!mEnableModernQueue) {
19310             return;
19311         }
19312 
19313         for (BroadcastQueue queue : mBroadcastQueues) {
19314             queue.forceDelayBroadcastDelivery(targetPackage, delayedDurationMs);
19315         }
19316     }
19317 
19318     @Override
19319     public boolean isModernBroadcastQueueEnabled() {
19320         enforceCallingPermission(permission.DUMP, "isModernBroadcastQueueEnabled()");
19321         return mEnableModernQueue;
19322     }
19323 
19324     @Override
19325     public boolean isProcessFrozen(int pid) {
19326         enforceCallingPermission(permission.DUMP, "isProcessFrozen()");
19327         return mOomAdjuster.mCachedAppOptimizer.isProcessFrozen(pid);
19328     }
19329 
19330     @Override
19331     @ReasonCode
19332     public int getBackgroundRestrictionExemptionReason(int uid) {
19333         enforceCallingPermission(android.Manifest.permission.DEVICE_POWER,
19334                 "getBackgroundRestrictionExemptionReason()");
19335         return mAppRestrictionController.getBackgroundRestrictionExemptionReason(uid);
19336     }
19337 
19338     /**
19339      * Set an app's background restriction level.
19340      * This interface is intended for the shell command to use.
19341      */
19342     void setBackgroundRestrictionLevel(String packageName, int uid, int userId,
19343             @RestrictionLevel int level, int reason, int subReason) {
19344         final int callingUid = Binder.getCallingUid();
19345         if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) {
19346             throw new SecurityException(
19347                     "No permission to change app restriction level");
19348         }
19349         final long callingId = Binder.clearCallingIdentity();
19350         try {
19351             final int curBucket = mUsageStatsService.getAppStandbyBucket(packageName, userId,
19352                     SystemClock.elapsedRealtime());
19353             mAppRestrictionController.applyRestrictionLevel(packageName, uid, level,
19354                     null /* trackerInfo */, curBucket, true /* allowUpdateBucket */,
19355                     reason, subReason);
19356         } finally {
19357             Binder.restoreCallingIdentity(callingId);
19358         }
19359     }
19360 
19361     /**
19362      * Get an app's background restriction level.
19363      * This interface is intended for the shell command to use.
19364      */
19365     @RestrictionLevel int getBackgroundRestrictionLevel(String packageName, int userId) {
19366         final int callingUid = Binder.getCallingUid();
19367         if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) {
19368             throw new SecurityException(
19369                     "Don't have permission to query app background restriction level");
19370         }
19371         final long callingId = Binder.clearCallingIdentity();
19372         try {
19373             return mInternal.getRestrictionLevel(packageName, userId);
19374         } finally {
19375             Binder.restoreCallingIdentity(callingId);
19376         }
19377     }
19378 
19379     /**
19380      * Start/stop foreground service delegate on a app's process.
19381      * This interface is intended for the shell command to use.
19382      */
19383     void setForegroundServiceDelegate(String packageName, int uid, boolean isStart,
19384             @ForegroundServiceDelegationOptions.DelegationService int delegateService,
19385             String clientInstanceName) {
19386         final int callingUid = Binder.getCallingUid();
19387         if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) {
19388             throw new SecurityException(
19389                     "No permission to start/stop foreground service delegate");
19390         }
19391         final long callingId = Binder.clearCallingIdentity();
19392         try {
19393             boolean foundPid = false;
19394             synchronized (this) {
19395                 ArrayList<ForegroundServiceDelegationOptions> delegates = new ArrayList<>();
19396                 synchronized (mPidsSelfLocked) {
19397                     for (int i = 0; i < mPidsSelfLocked.size(); i++) {
19398                         final ProcessRecord p = mPidsSelfLocked.valueAt(i);
19399                         final IApplicationThread thread = p.getThread();
19400                         if (p.uid == uid && thread != null) {
19401                             foundPid = true;
19402                             int pid = mPidsSelfLocked.keyAt(i);
19403                             ForegroundServiceDelegationOptions options =
19404                                     new ForegroundServiceDelegationOptions(pid, uid, packageName,
19405                                             null /* clientAppThread */,
19406                                             false /* isSticky */,
19407                                             clientInstanceName, 0 /* foregroundServiceType */,
19408                                             delegateService);
19409                             delegates.add(options);
19410                         }
19411                     }
19412                 }
19413                 for (int i = delegates.size() - 1; i >= 0; i--) {
19414                     final ForegroundServiceDelegationOptions options = delegates.get(i);
19415                     if (isStart) {
19416                         mInternal.startForegroundServiceDelegate(options,
19417                                 null /* connection */);
19418                     } else {
19419                         mInternal.stopForegroundServiceDelegate(options);
19420                     }
19421                 }
19422             }
19423             if (!foundPid) {
19424                 Slog.e(TAG, "setForegroundServiceDelegate can not find process for packageName:"
19425                         + packageName + " uid:" + uid);
19426             }
19427         } finally {
19428             Binder.restoreCallingIdentity(callingId);
19429         }
19430     }
19431 
19432     /**
19433      * Force the settings cache to be loaded
19434      */
19435     void refreshSettingsCache() {
19436         mCoreSettingsObserver.onChange(true);
19437     }
19438 
19439     /**
19440      * Reset the dropbox rate limiter here and in BootReceiver
19441      */
19442     void resetDropboxRateLimiter() {
19443         mDropboxRateLimiter.reset();
19444         BootReceiver.resetDropboxRateLimiter();
19445     }
19446 
19447     /**
19448      * Kill processes for the user with id userId and that depend on the package named packageName
19449      */
19450     @Override
19451     public void killPackageDependents(String packageName, int userId) {
19452         enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()");
19453         if (packageName == null) {
19454             throw new NullPointerException(
19455                     "Cannot kill the dependents of a package without its name.");
19456         }
19457 
19458         final long callingId = Binder.clearCallingIdentity();
19459         IPackageManager pm = AppGlobals.getPackageManager();
19460         int pkgUid = -1;
19461         try {
19462             pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
19463         } catch (RemoteException e) {
19464         }
19465         if (userId != UserHandle.USER_ALL && pkgUid == -1) {
19466             throw new IllegalArgumentException(
19467                     "Cannot kill dependents of non-existing package " + packageName);
19468         }
19469         try {
19470             synchronized(this) {
19471                 synchronized (mProcLock) {
19472                     mProcessList.killPackageProcessesLSP(packageName, UserHandle.getAppId(pkgUid),
19473                             userId, ProcessList.FOREGROUND_APP_ADJ,
19474                             ApplicationExitInfo.REASON_DEPENDENCY_DIED,
19475                             ApplicationExitInfo.SUBREASON_UNKNOWN,
19476                             "dep: " + packageName);
19477                 }
19478             }
19479         } finally {
19480             Binder.restoreCallingIdentity(callingId);
19481         }
19482     }
19483 
19484     @Override
19485     public int restartUserInBackground(int userId, int userStartMode) {
19486         return mUserController.restartUser(userId, userStartMode);
19487     }
19488 
19489     @Override
19490     public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) {
19491         enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
19492                 "scheduleApplicationInfoChanged()");
19493 
19494         final long origId = Binder.clearCallingIdentity();
19495         try {
19496             final boolean updateFrameworkRes = packageNames.contains("android");
19497             synchronized (mProcLock) {
19498                 updateApplicationInfoLOSP(packageNames, updateFrameworkRes, userId);
19499             }
19500 
19501             AppWidgetManagerInternal widgets = LocalServices.getService(
19502                     AppWidgetManagerInternal.class);
19503             if (widgets != null) {
19504                 widgets.applyResourceOverlaysToWidgets(new HashSet<>(packageNames), userId,
19505                         updateFrameworkRes);
19506             }
19507         } finally {
19508             Binder.restoreCallingIdentity(origId);
19509         }
19510     }
19511 
19512     /**
19513      * Synchronously update the system ActivityThread, bypassing any deferred threading so any
19514      * resources and overlaid values are available immediately.
19515      */
19516     public void updateSystemUiContext() {
19517         final PackageManagerInternal packageManagerInternal = getPackageManagerInternal();
19518 
19519         ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android",
19520                 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM);
19521         ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai);
19522     }
19523 
19524     @GuardedBy(anyOf = {"this", "mProcLock"})
19525     private void updateApplicationInfoLOSP(@NonNull List<String> packagesToUpdate,
19526             boolean updateFrameworkRes, int userId) {
19527         if (updateFrameworkRes) {
19528             ParsingPackageUtils.readConfigUseRoundIcon(null);
19529         }
19530 
19531         mProcessList.updateApplicationInfoLOSP(packagesToUpdate, userId, updateFrameworkRes);
19532 
19533         if (updateFrameworkRes) {
19534             // Update system server components that need to know about changed overlays. Because the
19535             // overlay is applied in ActivityThread, we need to serialize through its thread too.
19536             final Executor executor = ActivityThread.currentActivityThread().getExecutor();
19537             final DisplayManagerInternal display =
19538                     LocalServices.getService(DisplayManagerInternal.class);
19539             if (display != null) {
19540                 executor.execute(display::onOverlayChanged);
19541             }
19542             if (mWindowManager != null) {
19543                 executor.execute(mWindowManager::onOverlayChanged);
19544             }
19545         }
19546     }
19547 
19548     /**
19549      * Update the binder call heavy hitter watcher per the new configuration
19550      */
19551     void scheduleUpdateBinderHeavyHitterWatcherConfig() {
19552         // There are two sets of configs: the default watcher and the auto sampler,
19553         // the default one takes precedence. System would kick off auto sampler when there is
19554         // an anomaly (i.e., consecutive ANRs), but it'll be stopped automatically after a while.
19555         mHandler.post(() -> {
19556             final boolean enabled;
19557             final int batchSize;
19558             final float threshold;
19559             final BinderCallHeavyHitterListener listener;
19560             synchronized (mProcLock) {
19561                 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
19562                     // Default watcher takes precedence, ignore the auto sampler.
19563                     mHandler.removeMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG);
19564                     // Set the watcher with the default watcher's config
19565                     enabled = true;
19566                     batchSize = mConstants.BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE;
19567                     threshold = mConstants.BINDER_HEAVY_HITTER_WATCHER_THRESHOLD;
19568                     listener = (a, b, c, d) -> mHandler.post(
19569                             () -> handleBinderHeavyHitters(a, b, c, d));
19570                 } else if (mHandler.hasMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG)) {
19571                     // There is an ongoing auto sampler session, update it
19572                     enabled = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED;
19573                     batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE;
19574                     threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD;
19575                     listener = (a, b, c, d) -> mHandler.post(
19576                             () -> handleBinderHeavyHitters(a, b, c, d));
19577                 } else {
19578                     // Stop it
19579                     enabled = false;
19580                     batchSize = 0;
19581                     threshold = 0.0f;
19582                     listener = null;
19583                 }
19584             }
19585             Binder.setHeavyHitterWatcherConfig(enabled, batchSize, threshold, listener);
19586         });
19587     }
19588 
19589     /**
19590      * Kick off the watcher to run for given timeout, it could be throttled however.
19591      */
19592     void scheduleBinderHeavyHitterAutoSampler() {
19593         mHandler.post(() -> {
19594             final int batchSize;
19595             final float threshold;
19596             final long now;
19597             synchronized (mProcLock) {
19598                 if (!mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED) {
19599                     // It's configured OFF
19600                     return;
19601                 }
19602                 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
19603                     // If the default watcher is active already, don't start the auto sampler
19604                     return;
19605                 }
19606                 now = SystemClock.uptimeMillis();
19607                 if (mLastBinderHeavyHitterAutoSamplerStart
19608                         + BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS > now) {
19609                     // Too frequent, throttle it
19610                     return;
19611                 }
19612                 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE;
19613                 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD;
19614             }
19615             // No lock is needed because we are accessing these variables in handle thread only.
19616             mLastBinderHeavyHitterAutoSamplerStart = now;
19617             // Start the watcher with the auto sampler's config.
19618             Binder.setHeavyHitterWatcherConfig(true, batchSize, threshold,
19619                     (a, b, c, d) -> mHandler.post(() -> handleBinderHeavyHitters(a, b, c, d)));
19620             // Schedule to stop it after given timeout.
19621             mHandler.sendMessageDelayed(mHandler.obtainMessage(
19622                     BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG),
19623                     BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS);
19624         });
19625     }
19626 
19627     /**
19628      * Stop the binder heavy hitter auto sampler after given timeout.
19629      */
19630     private void handleBinderHeavyHitterAutoSamplerTimeOut() {
19631         synchronized (mProcLock) {
19632             if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
19633                 // The default watcher is ON, don't bother to stop it.
19634                 return;
19635             }
19636         }
19637         Binder.setHeavyHitterWatcherConfig(false, 0, 0.0f, null);
19638     }
19639 
19640     /**
19641      * Handle the heavy hitters
19642      */
19643     private void handleBinderHeavyHitters(@NonNull final List<HeavyHitterContainer> hitters,
19644             final int totalBinderCalls, final float threshold, final long timeSpan) {
19645         final int size = hitters.size();
19646         if (size == 0) {
19647             return;
19648         }
19649         // Simply log it for now
19650         final String pfmt = "%.1f%%";
19651         final BinderTransactionNameResolver resolver = new BinderTransactionNameResolver();
19652         final StringBuilder sb = new StringBuilder("Excessive incoming binder calls(>")
19653                 .append(String.format(pfmt, threshold * 100))
19654                 .append(',').append(totalBinderCalls)
19655                 .append(',').append(timeSpan)
19656                 .append("ms): ");
19657         for (int i = 0; i < size; i++) {
19658             if (i > 0) {
19659                 sb.append(", ");
19660             }
19661             final HeavyHitterContainer container = hitters.get(i);
19662             sb.append('[').append(container.mUid)
19663                     .append(',').append(container.mClass.getName())
19664                     .append(',').append(resolver.getMethodName(container.mClass, container.mCode))
19665                     .append(',').append(container.mCode)
19666                     .append(',').append(String.format(pfmt, container.mFrequency * 100))
19667                     .append(']');
19668         }
19669         Slog.w(TAG, sb.toString());
19670     }
19671 
19672     /**
19673      * Attach an agent to the specified process (proces name or PID)
19674      */
19675     public void attachAgent(String process, String path) {
19676         try {
19677             synchronized (mProcLock) {
19678                 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_SYSTEM,
19679                         "attachAgent");
19680                 IApplicationThread thread;
19681                 if (proc == null || (thread = proc.getThread()) == null) {
19682                     throw new IllegalArgumentException("Unknown process: " + process);
19683                 }
19684 
19685                 enforceDebuggable(proc);
19686 
19687                 thread.attachAgent(path);
19688             }
19689         } catch (RemoteException e) {
19690             throw new IllegalStateException("Process disappeared");
19691         }
19692     }
19693 
19694     /**
19695      * When power button is very long pressed, call this interface to do some pre-shutdown work
19696      * like persisting database etc.
19697      */
19698     public void prepareForPossibleShutdown() {
19699         if (mUsageStatsService != null) {
19700             mUsageStatsService.prepareForPossibleShutdown();
19701         }
19702     }
19703 
19704     @VisibleForTesting
19705     public static class Injector {
19706         private final Context mContext;
19707         private NetworkManagementInternal mNmi;
19708 
19709         private UserController mUserController;
19710 
19711         public Injector(Context context) {
19712             mContext = context;
19713         }
19714 
19715         public Context getContext() {
19716             return mContext;
19717         }
19718 
19719         public AppOpsService getAppOpsService(File recentAccessesFile, File storageFile,
19720                 Handler handler) {
19721             return new AppOpsService(recentAccessesFile, storageFile, handler, getContext());
19722         }
19723 
19724         public Handler getUiHandler(ActivityManagerService service) {
19725             return service.new UiHandler();
19726         }
19727 
19728         public boolean isNetworkRestrictedForUid(int uid) {
19729             if (ensureHasNetworkManagementInternal()) {
19730                 return mNmi.isNetworkRestrictedForUid(uid);
19731             }
19732             return false;
19733         }
19734 
19735         /**
19736          * Called by {@code AMS.getDisplayIdsForStartingVisibleBackgroundUsers()}.
19737          */
19738         // NOTE: ideally Injector should have no complex logic, but if this logic was moved to AMS,
19739         // it could not be tested with the existing ActivityManagerServiceTest (as DisplayManager,
19740         // DisplayInfo, etc... are final and UserManager.isUsersOnSecondaryDisplaysEnabled is
19741         // static).
19742         // So, the logic was added here, and tested on ActivityManagerServiceInjectorTest (which
19743         // was added on FrameworksMockingServicesTests and hence uses Extended Mockito to mock
19744         // final and static stuff)
19745         @Nullable
19746         public int[] getDisplayIdsForStartingVisibleBackgroundUsers() {
19747             if (!UserManager.isVisibleBackgroundUsersEnabled()) {
19748                 Slogf.w(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): not supported");
19749                 return null;
19750             }
19751 
19752             // NOTE: DisplayManagerInternal doesn't have a method to list all displays
19753             DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
19754 
19755             Display[] allDisplays = displayManager.getDisplays();
19756 
19757             // allDisplays should contain at least Display.DEFAULT_DISPLAY, but it's better to
19758             // double check, just in case...
19759             if (allDisplays == null || allDisplays.length == 0) {
19760                 Slogf.wtf(TAG, "displayManager (%s) returned no displays", displayManager);
19761                 return null;
19762             }
19763             boolean hasDefaultDisplay = false;
19764             for (Display display : allDisplays) {
19765                 if (display.getDisplayId() == Display.DEFAULT_DISPLAY) {
19766                     hasDefaultDisplay = true;
19767                     break;
19768                 }
19769             }
19770             if (!hasDefaultDisplay) {
19771                 Slogf.wtf(TAG, "displayManager (%s) has %d displays (%s), but none has id "
19772                         + "DEFAULT_DISPLAY (%d)", displayManager, allDisplays.length,
19773                         Arrays.toString(allDisplays), Display.DEFAULT_DISPLAY);
19774                 return null;
19775             }
19776 
19777             boolean allowOnDefaultDisplay = UserManager
19778                     .isVisibleBackgroundUsersOnDefaultDisplayEnabled();
19779             int displaysSize = allDisplays.length;
19780             if (!allowOnDefaultDisplay) {
19781                 displaysSize--;
19782             }
19783             int[] displayIds = new int[displaysSize];
19784 
19785             int numberValidDisplays = 0;
19786             for (Display display : allDisplays) {
19787                 int displayId = display.getDisplayId();
19788                 // TODO(b/247592632): check other properties like isSecure or proper display type
19789                 if (display.isValid() && ((display.getFlags() & Display.FLAG_PRIVATE) == 0)
19790                         && (allowOnDefaultDisplay || displayId != Display.DEFAULT_DISPLAY)) {
19791                     displayIds[numberValidDisplays++] = displayId;
19792                 }
19793             }
19794 
19795             if (numberValidDisplays == 0) {
19796                 // TODO(b/247580038): remove this workaround once a virtual display on Car's
19797                 // KitchenSink (or other app) can be used while running CTS tests on devices that
19798                 // don't have a real display.
19799                 // STOPSHIP: if not removed, it should at least be unit tested
19800                 String testingProp = "fw.display_ids_for_starting_users_for_testing_purposes";
19801                 int displayId = SystemProperties.getInt(testingProp, Display.DEFAULT_DISPLAY);
19802                 if (allowOnDefaultDisplay && displayId == Display.DEFAULT_DISPLAY
19803                         || displayId > 0) {
19804                     Slogf.w(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): no valid "
19805                             + "display found, but returning %d as set by property %s", displayId,
19806                             testingProp);
19807                     return new int[] { displayId };
19808                 }
19809                 Slogf.e(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): no valid display"
19810                         + " on %s", Arrays.toString(allDisplays));
19811                 return null;
19812             }
19813 
19814             if (numberValidDisplays != displayIds.length) {
19815                 int[] validDisplayIds = new int[numberValidDisplays];
19816                 System.arraycopy(displayIds, 0, validDisplayIds, 0, numberValidDisplays);
19817                 if (DEBUG_MU) {
19818                     Slogf.d(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): returning "
19819                             + "only valid displays (%d instead of %d): %s", numberValidDisplays,
19820                             displayIds.length, Arrays.toString(validDisplayIds));
19821                 }
19822                 return validDisplayIds;
19823             }
19824 
19825             if (DEBUG_MU) {
19826                 Slogf.d(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): returning all (but "
19827                         + "DEFAULT_DISPLAY) displays : %s", Arrays.toString(displayIds));
19828             }
19829             return displayIds;
19830         }
19831 
19832         /**
19833          * Called by {@code AMS.startUserInBackgroundVisibleOnDisplay()}.
19834          */
19835         public boolean startUserInBackgroundVisibleOnDisplay(int userId, int displayId,
19836                 @Nullable IProgressListener unlockProgressListener) {
19837             return mUserController.startUserVisibleOnDisplay(userId, displayId,
19838                     unlockProgressListener);
19839         }
19840 
19841         /**
19842          * Return the process list instance
19843          */
19844         public ProcessList getProcessList(ActivityManagerService service) {
19845             return new ProcessList();
19846         }
19847 
19848         /**
19849          * Returns the {@link BatteryStatsService} instance
19850          */
19851         public BatteryStatsService getBatteryStatsService() {
19852             return new BatteryStatsService(mContext, SystemServiceManager.ensureSystemDir(),
19853                 BackgroundThread.get().getHandler());
19854         }
19855 
19856         /**
19857          * Returns the {@link ActiveServices} instance
19858          */
19859         public ActiveServices getActiveServices(ActivityManagerService service) {
19860             return new ActiveServices(service);
19861         }
19862 
19863         private boolean ensureHasNetworkManagementInternal() {
19864             if (mNmi == null) {
19865                 mNmi = LocalServices.getService(NetworkManagementInternal.class);
19866             }
19867             return mNmi != null;
19868         }
19869     }
19870 
19871     @Override
19872     public void startDelegateShellPermissionIdentity(int delegateUid,
19873             @Nullable String[] permissions) {
19874         if (UserHandle.getCallingAppId() != Process.SHELL_UID
19875                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
19876             throw new SecurityException("Only the shell can delegate its permissions");
19877         }
19878 
19879         // We allow delegation only to one instrumentation started from the shell
19880         synchronized (mProcLock) {
19881             // If the delegate is already set up for the target UID, nothing to do.
19882             if (mAppOpsService.getAppOpsServiceDelegate() != null) {
19883                 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) {
19884                     throw new IllegalStateException("Bad shell delegate state");
19885                 }
19886                 final ShellDelegate delegate = (ShellDelegate) mAppOpsService
19887                         .getAppOpsServiceDelegate();
19888                 if (delegate.getDelegateUid() != delegateUid) {
19889                     throw new SecurityException("Shell can delegate permissions only "
19890                             + "to one instrumentation at a time");
19891                 }
19892             }
19893 
19894             final int instrCount = mActiveInstrumentation.size();
19895             for (int i = 0; i < instrCount; i++) {
19896                 final ActiveInstrumentation instr = mActiveInstrumentation.get(i);
19897                 if (instr.mTargetInfo.uid != delegateUid) {
19898                     continue;
19899                 }
19900                 // If instrumentation started from the shell the connection is not null
19901                 if (instr.mUiAutomationConnection == null) {
19902                     throw new SecurityException("Shell can delegate its permissions" +
19903                             " only to an instrumentation started from the shell");
19904                 }
19905 
19906                 // Hook them up...
19907                 final ShellDelegate shellDelegate = new ShellDelegate(delegateUid,
19908                         permissions);
19909                 mAppOpsService.setAppOpsServiceDelegate(shellDelegate);
19910                 final String packageName = instr.mTargetInfo.packageName;
19911                 final List<String> permissionNames = permissions != null ?
19912                         Arrays.asList(permissions) : null;
19913                 getPermissionManagerInternal().startShellPermissionIdentityDelegation(
19914                         delegateUid, packageName, permissionNames);
19915                 return;
19916             }
19917         }
19918     }
19919 
19920     @Override
19921     public void stopDelegateShellPermissionIdentity() {
19922         if (UserHandle.getCallingAppId() != Process.SHELL_UID
19923                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
19924             throw new SecurityException("Only the shell can delegate its permissions");
19925         }
19926         synchronized (mProcLock) {
19927             mAppOpsService.setAppOpsServiceDelegate(null);
19928             getPermissionManagerInternal().stopShellPermissionIdentityDelegation();
19929         }
19930     }
19931 
19932     @Override
19933     public List<String> getDelegatedShellPermissions() {
19934         if (UserHandle.getCallingAppId() != Process.SHELL_UID
19935                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
19936             throw new SecurityException("Only the shell can get delegated permissions");
19937         }
19938         synchronized (mProcLock) {
19939             return getPermissionManagerInternal().getDelegatedShellPermissions();
19940         }
19941     }
19942 
19943     private class ShellDelegate implements CheckOpsDelegate {
19944         private final int mTargetUid;
19945         @Nullable
19946         private final String[] mPermissions;
19947 
19948         ShellDelegate(int targetUid, @Nullable String[] permissions) {
19949             mTargetUid = targetUid;
19950             mPermissions = permissions;
19951         }
19952 
19953         int getDelegateUid() {
19954             return mTargetUid;
19955         }
19956 
19957         @Override
19958         public int checkOperation(int code, int uid, String packageName,
19959                 String attributionTag, boolean raw,
19960                 QuintFunction<Integer, Integer, String, String, Boolean, Integer> superImpl) {
19961             if (uid == mTargetUid && isTargetOp(code)) {
19962                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
19963                         Process.SHELL_UID);
19964                 final long identity = Binder.clearCallingIdentity();
19965                 try {
19966                     return superImpl.apply(code, shellUid, "com.android.shell", null, raw);
19967                 } finally {
19968                     Binder.restoreCallingIdentity(identity);
19969                 }
19970             }
19971             return superImpl.apply(code, uid, packageName, attributionTag, raw);
19972         }
19973 
19974         @Override
19975         public int checkAudioOperation(int code, int usage, int uid, String packageName,
19976                 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) {
19977             if (uid == mTargetUid && isTargetOp(code)) {
19978                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
19979                         Process.SHELL_UID);
19980                 final long identity = Binder.clearCallingIdentity();
19981                 try {
19982                     return superImpl.apply(code, usage, shellUid, "com.android.shell");
19983                 } finally {
19984                     Binder.restoreCallingIdentity(identity);
19985                 }
19986             }
19987             return superImpl.apply(code, usage, uid, packageName);
19988         }
19989 
19990         @Override
19991         public SyncNotedAppOp noteOperation(int code, int uid, @Nullable String packageName,
19992                 @Nullable String featureId, boolean shouldCollectAsyncNotedOp,
19993                 @Nullable String message, boolean shouldCollectMessage,
19994                 @NonNull HeptFunction<Integer, Integer, String, String, Boolean, String, Boolean,
19995                         SyncNotedAppOp> superImpl) {
19996             if (uid == mTargetUid && isTargetOp(code)) {
19997                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
19998                         Process.SHELL_UID);
19999                 final long identity = Binder.clearCallingIdentity();
20000                 try {
20001                     return superImpl.apply(code, shellUid, "com.android.shell", featureId,
20002                             shouldCollectAsyncNotedOp, message, shouldCollectMessage);
20003                 } finally {
20004                     Binder.restoreCallingIdentity(identity);
20005                 }
20006             }
20007             return superImpl.apply(code, uid, packageName, featureId, shouldCollectAsyncNotedOp,
20008                     message, shouldCollectMessage);
20009         }
20010 
20011         @Override
20012         public SyncNotedAppOp noteProxyOperation(int code,
20013                 @NonNull AttributionSource attributionSource, boolean shouldCollectAsyncNotedOp,
20014                 @Nullable String message, boolean shouldCollectMessage, boolean skiProxyOperation,
20015                 @NonNull HexFunction<Integer, AttributionSource, Boolean, String, Boolean,
20016                                 Boolean, SyncNotedAppOp> superImpl) {
20017             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
20018                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
20019                         attributionSource.getUid()), Process.SHELL_UID);
20020                 final long identity = Binder.clearCallingIdentity();
20021                 try {
20022                     return superImpl.apply(code, new AttributionSource(shellUid,
20023                             Process.INVALID_PID, "com.android.shell",
20024                             attributionSource.getAttributionTag(), attributionSource.getToken(),
20025                             /*renouncedPermissions*/ null, attributionSource.getNext()),
20026                             shouldCollectAsyncNotedOp, message, shouldCollectMessage,
20027                             skiProxyOperation);
20028                 } finally {
20029                     Binder.restoreCallingIdentity(identity);
20030                 }
20031             }
20032             return superImpl.apply(code, attributionSource, shouldCollectAsyncNotedOp,
20033                     message, shouldCollectMessage, skiProxyOperation);
20034         }
20035 
20036         @Override
20037         public SyncNotedAppOp startOperation(IBinder token, int code, int uid,
20038                 @Nullable String packageName, @Nullable String attributionTag,
20039                 boolean startIfModeDefault, boolean shouldCollectAsyncNotedOp,
20040                 @Nullable String message, boolean shouldCollectMessage,
20041                 @AttributionFlags int attributionFlags, int attributionChainId,
20042                 @NonNull UndecFunction<IBinder, Integer, Integer, String, String, Boolean,
20043                         Boolean, String, Boolean, Integer, Integer, SyncNotedAppOp> superImpl) {
20044             if (uid == mTargetUid && isTargetOp(code)) {
20045                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
20046                         Process.SHELL_UID);
20047                 final long identity = Binder.clearCallingIdentity();
20048                 try {
20049                     return superImpl.apply(token, code, shellUid, "com.android.shell",
20050                             attributionTag, startIfModeDefault, shouldCollectAsyncNotedOp, message,
20051                             shouldCollectMessage, attributionFlags, attributionChainId);
20052                 } finally {
20053                     Binder.restoreCallingIdentity(identity);
20054                 }
20055             }
20056             return superImpl.apply(token, code, uid, packageName, attributionTag,
20057                     startIfModeDefault, shouldCollectAsyncNotedOp, message, shouldCollectMessage,
20058                     attributionFlags, attributionChainId);
20059         }
20060 
20061         @Override
20062         public SyncNotedAppOp startProxyOperation(@NonNull IBinder clientId, int code,
20063                 @NonNull AttributionSource attributionSource, boolean startIfModeDefault,
20064                 boolean shouldCollectAsyncNotedOp, String message, boolean shouldCollectMessage,
20065                 boolean skipProxyOperation, @AttributionFlags int proxyAttributionFlags,
20066                 @AttributionFlags int proxiedAttributionFlags, int attributionChainId,
20067                 @NonNull UndecFunction<IBinder, Integer, AttributionSource,
20068                         Boolean, Boolean, String, Boolean, Boolean, Integer, Integer, Integer,
20069                         SyncNotedAppOp> superImpl) {
20070             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
20071                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
20072                         attributionSource.getUid()), Process.SHELL_UID);
20073                 final long identity = Binder.clearCallingIdentity();
20074                 try {
20075                     return superImpl.apply(clientId, code, new AttributionSource(shellUid,
20076                             Process.INVALID_PID, "com.android.shell",
20077                             attributionSource.getAttributionTag(), attributionSource.getToken(),
20078                             /*renouncedPermissions*/ null, attributionSource.getNext()),
20079                             startIfModeDefault, shouldCollectAsyncNotedOp, message,
20080                             shouldCollectMessage, skipProxyOperation, proxyAttributionFlags,
20081                             proxiedAttributionFlags, attributionChainId);
20082                 } finally {
20083                     Binder.restoreCallingIdentity(identity);
20084                 }
20085             }
20086             return superImpl.apply(clientId, code, attributionSource, startIfModeDefault,
20087                     shouldCollectAsyncNotedOp, message, shouldCollectMessage, skipProxyOperation,
20088                     proxyAttributionFlags, proxiedAttributionFlags, attributionChainId);
20089         }
20090 
20091         @Override
20092         public void finishProxyOperation(@NonNull IBinder clientId, int code,
20093                 @NonNull AttributionSource attributionSource, boolean skipProxyOperation,
20094                 @NonNull QuadFunction<IBinder, Integer, AttributionSource, Boolean,
20095                         Void> superImpl) {
20096             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
20097                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
20098                         attributionSource.getUid()), Process.SHELL_UID);
20099                 final long identity = Binder.clearCallingIdentity();
20100                 try {
20101                     superImpl.apply(clientId, code, new AttributionSource(shellUid,
20102                             Process.INVALID_PID, "com.android.shell",
20103                             attributionSource.getAttributionTag(), attributionSource.getToken(),
20104                             /*renouncedPermissions*/ null, attributionSource.getNext()),
20105                             skipProxyOperation);
20106                 } finally {
20107                     Binder.restoreCallingIdentity(identity);
20108                 }
20109             }
20110             superImpl.apply(clientId, code, attributionSource, skipProxyOperation);
20111         }
20112 
20113         private boolean isTargetOp(int code) {
20114             // null permissions means all ops are targeted
20115             if (mPermissions == null) {
20116                 return true;
20117             }
20118             // no permission for the op means the op is targeted
20119             final String permission = AppOpsManager.opToPermission(code);
20120             if (permission == null) {
20121                 return true;
20122             }
20123             return isTargetPermission(permission);
20124         }
20125 
20126         private boolean isTargetPermission(@NonNull String permission) {
20127             // null permissions means all permissions are targeted
20128             return (mPermissions == null || ArrayUtils.contains(mPermissions, permission));
20129         }
20130     }
20131 
20132     /**
20133      * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would
20134      * cause a watchdog kill.
20135      */
20136     void maybeTriggerWatchdog() {
20137         final String key = "debug.trigger.watchdog";
20138         if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) {
20139             Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!");
20140 
20141             // Clear the property; otherwise the system would hang again after a watchdog restart.
20142             SystemProperties.set(key, "");
20143             synchronized (ActivityManagerService.this) {
20144                 try {
20145                     // Arbitrary long sleep for watchdog to catch.
20146                     Thread.sleep(60 * 60 * 1000);
20147                 } catch (InterruptedException e) {
20148                 }
20149             }
20150         }
20151     }
20152 
20153     private boolean isOnFgOffloadQueue(int flags) {
20154         return ((flags & Intent.FLAG_RECEIVER_OFFLOAD_FOREGROUND) != 0);
20155     }
20156 
20157     private boolean isOnBgOffloadQueue(int flags) {
20158         return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0));
20159     }
20160 
20161     @Override
20162     public ParcelFileDescriptor getLifeMonitor() {
20163         if (!isCallerShell()) {
20164             throw new SecurityException("Only shell can call it");
20165         }
20166         synchronized (mProcLock) {
20167             try {
20168                 if (mLifeMonitorFds == null) {
20169                     mLifeMonitorFds = ParcelFileDescriptor.createPipe();
20170                 }
20171                 // The returned FD will be closed, but we want to keep our reader open,
20172                 // so return a dup instead.
20173                 return mLifeMonitorFds[0].dup();
20174             } catch (IOException e) {
20175                 Slog.w(TAG, "Unable to create pipe", e);
20176                 return null;
20177             }
20178         }
20179     }
20180 
20181     @Override
20182     public void setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken) {
20183         final int callingUid = Binder.getCallingUid();
20184         final int userId = UserHandle.getCallingUserId();
20185         if (getPackageManagerInternal().getPackageUid(activity.getPackageName(),
20186                 /*flags=*/ 0, userId) != callingUid) {
20187             throw new SecurityException("Calling uid " + callingUid + " cannot set locusId"
20188                     + "for package " + activity.getPackageName());
20189         }
20190         mActivityTaskManager.setLocusId(locusId, appToken);
20191         if (mUsageStatsService != null) {
20192             mUsageStatsService.reportLocusUpdate(activity, userId, locusId, appToken);
20193         }
20194     }
20195 
20196     @Override
20197     public boolean isAppFreezerSupported() {
20198         final long token = Binder.clearCallingIdentity();
20199 
20200         try {
20201             return CachedAppOptimizer.isFreezerSupported();
20202         } finally {
20203             Binder.restoreCallingIdentity(token);
20204         }
20205     }
20206 
20207     @Override
20208     public boolean isAppFreezerEnabled() {
20209         return mOomAdjuster.mCachedAppOptimizer.useFreezer();
20210     }
20211 
20212     public boolean isAppFreezerExemptInstPkg() {
20213         return mOomAdjuster.mCachedAppOptimizer.freezerExemptInstPkg();
20214     }
20215 
20216     /**
20217      * Resets the state of the {@link com.android.server.am.AppErrors} instance.
20218      * This is intended for testing within the CTS only and is protected by
20219      * android.permission.RESET_APP_ERRORS.
20220      */
20221     @Override
20222     public void resetAppErrors() {
20223         enforceCallingPermission(Manifest.permission.RESET_APP_ERRORS, "resetAppErrors");
20224         mAppErrors.resetState();
20225     }
20226 
20227     @Override
20228     public boolean enableAppFreezer(boolean enable) {
20229         int callerUid = Binder.getCallingUid();
20230 
20231         // Only system can toggle the freezer state
20232         if (callerUid == SYSTEM_UID || Build.IS_DEBUGGABLE) {
20233             return mOomAdjuster.mCachedAppOptimizer.enableFreezer(enable);
20234         } else {
20235             throw new SecurityException("Caller uid " + callerUid + " cannot set freezer state ");
20236         }
20237     }
20238 
20239     /**
20240      * Suppress or reenable the rate limit on foreground service notification deferral.
20241      * @param enable false to suppress rate-limit policy; true to reenable it.
20242      */
20243     @Override
20244     public boolean enableFgsNotificationRateLimit(boolean enable) {
20245         enforceCallingPermission(permission.WRITE_DEVICE_CONFIG,
20246                 "enableFgsNotificationRateLimit");
20247         synchronized (this) {
20248             return mServices.enableFgsNotificationRateLimitLocked(enable);
20249         }
20250     }
20251 
20252     /**
20253      * Holds the AM lock for the specified amount of milliseconds.
20254      * Intended for use by the tests that need to imitate lock contention.
20255      * The token should be obtained by
20256      * {@link android.content.pm.PackageManager#getHoldLockToken()}.
20257      */
20258     @Override
20259     public void holdLock(IBinder token, int durationMs) {
20260         getTestUtilityServiceLocked().verifyHoldLockToken(token);
20261 
20262         synchronized (this) {
20263             SystemClock.sleep(durationMs);
20264         }
20265     }
20266 
20267     static void traceBegin(long traceTag, String methodName, String subInfo) {
20268         if (Trace.isTagEnabled(traceTag)) {
20269             Trace.traceBegin(traceTag, methodName + subInfo);
20270         }
20271     }
20272 
20273     /**
20274      * Gets an {@code int} argument from the given {@code index} on {@code args}, logging an error
20275      * message on {@code pw} when it cannot be parsed.
20276      *
20277      * Returns {@code int} argument or {@code invalidValue} if it could not be parsed.
20278      */
20279     private static int getIntArg(PrintWriter pw, String[] args, int index, int invalidValue) {
20280         if (index > args.length) {
20281             pw.println("Missing argument");
20282             return invalidValue;
20283         }
20284         String arg = args[index];
20285         try {
20286             return Integer.parseInt(arg);
20287         } catch (Exception e) {
20288             pw.printf("Non-numeric argument at index %d: %s\n", index, arg);
20289             return invalidValue;
20290         }
20291     }
20292 
20293     private void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken,
20294             @MediaProjectionTokenEvent int event) {
20295         synchronized (mMediaProjectionTokenMap) {
20296             final int index = mMediaProjectionTokenMap.indexOfKey(uid);
20297             ArraySet<IBinder> tokens;
20298             if (event == MEDIA_PROJECTION_TOKEN_EVENT_CREATED) {
20299                 if (index < 0) {
20300                     tokens = new ArraySet();
20301                     mMediaProjectionTokenMap.put(uid, tokens);
20302                 } else {
20303                     tokens = mMediaProjectionTokenMap.valueAt(index);
20304                 }
20305                 tokens.add(projectionToken);
20306             } else if (event == MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED && index >= 0) {
20307                 tokens = mMediaProjectionTokenMap.valueAt(index);
20308                 tokens.remove(projectionToken);
20309                 if (tokens.isEmpty()) {
20310                     mMediaProjectionTokenMap.removeAt(index);
20311                 }
20312             }
20313         }
20314     }
20315 
20316     /**
20317      * @return {@code true} if the MediaProjectionManagerService has created a media projection
20318      *         for the given {@code uid} because the user has granted the permission;
20319      *         it doesn't necessarily mean it has started the projection.
20320      *
20321      * <p>It doesn't check the {@link AppOpsManager#OP_PROJECT_MEDIA}.</p>
20322      */
20323     boolean isAllowedMediaProjectionNoOpCheck(int uid) {
20324         synchronized (mMediaProjectionTokenMap) {
20325             final int index = mMediaProjectionTokenMap.indexOfKey(uid);
20326             return index >= 0 && !mMediaProjectionTokenMap.valueAt(index).isEmpty();
20327         }
20328     }
20329 
20330     /**
20331      * Deal with binder transactions to frozen apps.
20332      *
20333      * @param debugPid The binder transaction sender
20334      * @param code The binder transaction code
20335      * @param flags The binder transaction flags
20336      * @param err The binder transaction error
20337      */
20338     @Override
20339     public void frozenBinderTransactionDetected(int debugPid, int code, int flags, int err) {
20340         final ProcessRecord app;
20341         synchronized (mPidsSelfLocked) {
20342             app = mPidsSelfLocked.get(debugPid);
20343         }
20344         mOomAdjuster.mCachedAppOptimizer.binderError(debugPid, app, code, flags, err);
20345     }
20346 }
20347